mirror of
https://github.com/ajayyy/SponsorBlockServer.git
synced 2025-12-06 19:47:00 +03:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a860b89ef0 | ||
|
|
4650316067 | ||
|
|
08d458bdd6 | ||
|
|
6abfba1b12 | ||
|
|
d038279d79 | ||
|
|
35d3627760 | ||
|
|
dcffb83e62 | ||
|
|
a0465a44ae | ||
|
|
db55d314ee | ||
|
|
b2af4fc7b0 | ||
|
|
4f28d92eb8 | ||
|
|
c822a37a6e | ||
|
|
fd636a2770 | ||
|
|
c2e0d5a98f |
14
.eslintrc.js
14
.eslintrc.js
@@ -29,18 +29,4 @@ module.exports = {
|
||||
"semi": "warn",
|
||||
"no-console": "warn"
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ["src/**/*.ts"],
|
||||
|
||||
parserOptions: {
|
||||
project: ["./tsconfig.json"],
|
||||
},
|
||||
|
||||
rules: {
|
||||
"@typescript-eslint/no-misused-promises": "warn",
|
||||
"@typescript-eslint/no-floating-promises" : "warn"
|
||||
}
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
3
.github/pull_request_template.md
vendored
3
.github/pull_request_template.md
vendored
@@ -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
21
.github/workflows/ci.yml
vendored
Normal 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
|
||||
5
.github/workflows/docker-build.yml
vendored
5
.github/workflows/docker-build.yml
vendored
@@ -19,10 +19,9 @@ on:
|
||||
jobs:
|
||||
build_container:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
|
||||
21
.github/workflows/eslint.yml
vendored
Normal file
21
.github/workflows/eslint.yml
vendored
Normal 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
|
||||
23
.github/workflows/generate-sqlite-base.yml
vendored
23
.github/workflows/generate-sqlite-base.yml
vendored
@@ -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@v3
|
||||
- uses: actions/setup-node@v3
|
||||
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@v3
|
||||
- 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
29
.github/workflows/postgres-redis-ci.yml
vendored
Normal 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
|
||||
13
.github/workflows/sb-server.yml
vendored
13
.github/workflows/sb-server.yml
vendored
@@ -2,15 +2,24 @@ name: Docker image builds
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- debug
|
||||
- master
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
sb-server:
|
||||
uses: ./.github/workflows/docker-build.yml
|
||||
with:
|
||||
name: "sb-server-debug"
|
||||
name: "sb-server"
|
||||
username: "ajayyy"
|
||||
folder: "."
|
||||
secrets:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
rsync-host:
|
||||
needs: sb-server
|
||||
uses: ./.github/workflows/docker-build.yml
|
||||
with:
|
||||
name: "rsync-host"
|
||||
username: "ajayyy"
|
||||
folder: "./containers/rsync"
|
||||
secrets:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
2
.github/workflows/take-action.yml
vendored
2
.github/workflows/take-action.yml
vendored
@@ -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 }}
|
||||
|
||||
116
.github/workflows/test.yaml
vendored
116
.github/workflows/test.yaml
vendored
@@ -1,116 +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@v3
|
||||
- uses: actions/setup-node@v3
|
||||
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@v3
|
||||
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@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
cache: npm
|
||||
- id: cache
|
||||
uses: actions/cache/restore@v3
|
||||
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 SQLite Tests
|
||||
timeout-minutes: 5
|
||||
run: npx nyc --silent npm test
|
||||
- name: cache nyc output
|
||||
uses: actions/cache/save@v3
|
||||
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@v3
|
||||
- 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@v3
|
||||
with:
|
||||
node-version: 18
|
||||
cache: npm
|
||||
- id: cache
|
||||
uses: actions/cache/restore@v3
|
||||
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
|
||||
timeout-minutes: 5
|
||||
run: npx nyc --silent npm test
|
||||
- name: cache nyc output
|
||||
uses: actions/cache/save@v3
|
||||
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@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: restore postgres nyc output
|
||||
uses: actions/cache/restore@v3
|
||||
with:
|
||||
key: nyc-postgres-${{ github.sha }}
|
||||
path: ${{ github.workspace }}/.nyc_output
|
||||
- name: restore sqlite nyc output
|
||||
uses: actions/cache/restore@v3
|
||||
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@v3
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -45,7 +45,3 @@ working
|
||||
.DS_Store
|
||||
/.idea/
|
||||
/dist/
|
||||
|
||||
# nyc coverage output
|
||||
.nyc_output/
|
||||
coverage/
|
||||
14
.nycrc.json
14
.nycrc.json
@@ -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/*"
|
||||
]
|
||||
}
|
||||
@@ -126,6 +126,7 @@
|
||||
| channelID | TEXT | not null |
|
||||
| title | TEXT | not null |
|
||||
| published | REAL | not null |
|
||||
| genreUrl | TEXT | not null |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
@@ -208,7 +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
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
|
||||
@@ -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 entrypoint.sh .
|
||||
COPY databases/*.sql databases/
|
||||
EXPOSE 8080
|
||||
CMD ./entrypoint.sh
|
||||
CMD ./entrypoint.sh
|
||||
682
LICENSE
682
LICENSE
@@ -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.
|
||||
|
||||
27
LICENSE.old
27
LICENSE.old
@@ -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.
|
||||
@@ -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.
|
||||
23
ci.json
23
ci.json
@@ -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,7 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"maxNumberOfActiveWarnings": 3,
|
||||
"hoursAfterWarningExpires": 24,
|
||||
"rateLimit": {
|
||||
"vote": {
|
||||
@@ -69,12 +67,5 @@
|
||||
"max": 20,
|
||||
"statusCode": 200
|
||||
}
|
||||
},
|
||||
"patreon": {
|
||||
"clientId": "testClientID",
|
||||
"clientSecret": "testClientSecret",
|
||||
"redirectUri": "http://127.0.0.1/fake/callback"
|
||||
},
|
||||
"minReputationToSubmitFiller": -1,
|
||||
"minUserIDLength": 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
comment: false
|
||||
@@ -66,6 +66,5 @@
|
||||
{
|
||||
"name": "vipUsers"
|
||||
}]
|
||||
},
|
||||
"minUserIDLength": 30 // minimum length of UserID to be accepted
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,10 @@ RUN apk add restic --repository http://dl-cdn.alpinelinux.org/alpine/latest-stab
|
||||
|
||||
COPY ./backup.sh /usr/src/app/backup.sh
|
||||
RUN chmod +x /usr/src/app/backup.sh
|
||||
COPY ./forget.sh /usr/src/app/forget.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 * * 1 /usr/src/app/forget.sh' >> /etc/crontabs/root
|
||||
|
||||
CMD crond -l 2 -f
|
||||
CMD crond -l 2 -f
|
||||
@@ -26,22 +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
|
||||
);
|
||||
|
||||
COMMIT;
|
||||
|
||||
@@ -32,58 +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 EXTENSION IF NOT EXISTS pgcrypto; --!sqlite-ignore
|
||||
CREATE EXTENSION IF NOT EXISTS pg_trgm; --!sqlite-ignore
|
||||
|
||||
|
||||
@@ -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,45 +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_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"
|
||||
ON public."titles" USING btree
|
||||
("hashedVideoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC 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_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"
|
||||
ON public."thumbnails" USING btree
|
||||
("hashedVideoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -1,7 +0,0 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "videoInfo" DROP COLUMN "genreUrl";
|
||||
|
||||
UPDATE "config" SET value = 34 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
maxmemory-policy allkeys-lru
|
||||
maxmemory 6000mb
|
||||
maxmemory 6500mb
|
||||
|
||||
appendonly no
|
||||
save ""
|
||||
@@ -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 --inspect dist/src/index.js
|
||||
node dist/src/index.js
|
||||
11
nginx/cors.conf
Normal file
11
nginx/cors.conf
Normal 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
7
nginx/error.conf
Normal 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
1
nginx/error/error.html
Normal file
@@ -0,0 +1 @@
|
||||
<!--# echo var="status"--> <!--# echo var="status_text"--> https://status.sponsor.ajay.app
|
||||
15
nginx/error_map.conf
Normal file
15
nginx/error_map.conf
Normal 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
317
nginx/nginx.conf
Normal 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
12
nginx/proxy.conf
Normal 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;
|
||||
6747
package-lock.json
generated
6747
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
59
package.json
59
package.json
@@ -5,56 +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.1.3",
|
||||
"better-sqlite3": "^8.0.1",
|
||||
"cron": "^2.1.0",
|
||||
"express": "^4.18.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.0",
|
||||
"express-rate-limit": "^6.3.0",
|
||||
"lodash": "^4.17.21",
|
||||
"pg": "^8.8.0",
|
||||
"pg": "^8.7.1",
|
||||
"rate-limit-redis": "^3.0.1",
|
||||
"redis": "^4.5.0",
|
||||
"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/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.1.0",
|
||||
"nodemon": "^2.0.20",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
48
src/app.ts
48
src/app.ts
@@ -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,17 +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";
|
||||
|
||||
export function createServer(callback: () => void): Server {
|
||||
// Create a service (the app object is just a callback).
|
||||
@@ -60,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);
|
||||
@@ -83,14 +75,15 @@ export function createServer(callback: () => void): Server {
|
||||
return app.listen(config.port, callback);
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-misused-promises */
|
||||
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
|
||||
@@ -203,29 +196,20 @@ function setupRoutes(router: Router) {
|
||||
|
||||
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/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);
|
||||
|
||||
/* 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 */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "fs";
|
||||
import { SBSConfig } from "./types/config.model";
|
||||
import packageJson from "../package.json";
|
||||
import { isNumber } from "lodash";
|
||||
import { isBoolean, isNumber } from "lodash";
|
||||
|
||||
const isTestMode = process.env.npm_lifecycle_script === packageJson.scripts.test;
|
||||
const configFile = process.env.TEST_POSTGRES ? "ci.json"
|
||||
@@ -20,7 +20,7 @@ addDefaults(config, {
|
||||
privateDBSchema: "./databases/_private.db.sql",
|
||||
readOnly: false,
|
||||
webhooks: [],
|
||||
categoryList: ["sponsor", "selfpromo", "exclusive_access", "interaction", "intro", "outro", "preview", "music_offtopic", "filler", "poi_highlight", "chapter"],
|
||||
categoryList: ["sponsor", "selfpromo", "exclusive_access", "interaction", "intro", "outro", "preview", "music_offtopic", "filler", "poi_highlight"],
|
||||
categorySupport: {
|
||||
sponsor: ["skip", "mute", "full"],
|
||||
selfpromo: ["skip", "mute", "full"],
|
||||
@@ -42,9 +42,6 @@ addDefaults(config, {
|
||||
discordNeuralBlockRejectWebhookURL: null,
|
||||
discordFailedReportChannelWebhookURL: null,
|
||||
discordReportChannelWebhookURL: null,
|
||||
discordMaliciousReportWebhookURL: null,
|
||||
minReputationToSubmitChapter: 0,
|
||||
minReputationToSubmitFiller: 0,
|
||||
getTopUsersCacheTimeMinutes: 240,
|
||||
globalSalt: null,
|
||||
mode: "",
|
||||
@@ -62,10 +59,15 @@ addDefaults(config, {
|
||||
max: 10,
|
||||
statusCode: 200,
|
||||
message: "OK",
|
||||
},
|
||||
rate: {
|
||||
windowMs: 900000,
|
||||
max: 20,
|
||||
statusCode: 200,
|
||||
message: "Success",
|
||||
}
|
||||
},
|
||||
userCounterURL: null,
|
||||
userCounterRatio: 10,
|
||||
newLeafURLs: null,
|
||||
maxRewardTimePerSegmentInSeconds: 600,
|
||||
poiMinimumStartTime: 2,
|
||||
@@ -75,26 +77,8 @@ addDefaults(config, {
|
||||
host: "",
|
||||
password: "",
|
||||
port: 5432,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 10000,
|
||||
maxTries: 3,
|
||||
maxActiveRequests: 0,
|
||||
timeout: 60000,
|
||||
highLoadThreshold: 10
|
||||
},
|
||||
postgresReadOnly: {
|
||||
enabled: false,
|
||||
weight: 1,
|
||||
user: "",
|
||||
host: "",
|
||||
password: "",
|
||||
port: 5432,
|
||||
readTimeout: 250,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 10000,
|
||||
maxTries: 3,
|
||||
fallbackOnFail: true,
|
||||
stopRetryThreshold: 800
|
||||
max: 150,
|
||||
min: 10
|
||||
},
|
||||
dumpDatabase: {
|
||||
enabled: false,
|
||||
@@ -128,21 +112,6 @@ addDefaults(config, {
|
||||
},
|
||||
{
|
||||
name: "ratings"
|
||||
},
|
||||
{
|
||||
name: "titles"
|
||||
},
|
||||
{
|
||||
name: "titleVotes"
|
||||
},
|
||||
{
|
||||
name: "thumbnails"
|
||||
},
|
||||
{
|
||||
name: "thumbnailTimestamps"
|
||||
},
|
||||
{
|
||||
name: "thumbnailVotes"
|
||||
}]
|
||||
},
|
||||
diskCacheURL: null,
|
||||
@@ -153,36 +122,8 @@ addDefaults(config, {
|
||||
host: "",
|
||||
port: 0
|
||||
},
|
||||
disableOfflineQueue: true,
|
||||
expiryTime: 24 * 60 * 60,
|
||||
getTimeout: 40,
|
||||
maxConnections: 15000,
|
||||
maxWriteConnections: 1000,
|
||||
commandsQueueMaxLength: 3000,
|
||||
stopWritingAfterResponseTime: 50,
|
||||
responseTimePause: 1000,
|
||||
disableHashCache: 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"]
|
||||
},
|
||||
minUserIDLength: 30
|
||||
disableOfflineQueue: true
|
||||
}
|
||||
});
|
||||
loadFromEnv(config);
|
||||
migrate(config);
|
||||
@@ -231,7 +172,7 @@ function loadFromEnv(config: SBSConfig, prefix = "") {
|
||||
} else if (process.env[fullKey]) {
|
||||
const value = process.env[fullKey];
|
||||
if (isNumber(value)) {
|
||||
config[key] = parseFloat(value);
|
||||
config[key] = parseInt(value, 10);
|
||||
} else if (value.toLowerCase() === "true" || value.toLowerCase() === "false") {
|
||||
config[key] = value === "true";
|
||||
} else if (key === "newLeafURLs") {
|
||||
|
||||
@@ -57,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) {
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
export interface QueryOption {
|
||||
useReplica?: boolean;
|
||||
forceReplica?: boolean;
|
||||
}
|
||||
|
||||
export interface IDatabase {
|
||||
init(): Promise<void>;
|
||||
|
||||
prepare(type: QueryType, query: string, params?: any[], options?: QueryOption): Promise<any | any[] | void>;
|
||||
|
||||
highLoad(): boolean;
|
||||
prepare(type: QueryType, query: string, params?: any[]): Promise<any | any[] | void>;
|
||||
}
|
||||
|
||||
export type QueryType = "get" | "all" | "run";
|
||||
export type QueryType = "get" | "all" | "run";
|
||||
|
||||
@@ -32,8 +32,4 @@ export class Mysql implements IDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
highLoad() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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,32 +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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,10 +95,6 @@ export class Sqlite implements IDatabase {
|
||||
private static processUpgradeQuery(query: string): string {
|
||||
return query.replace(/^.*--!sqlite-ignore/gm, "");
|
||||
}
|
||||
|
||||
highLoad() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface SqliteConfig {
|
||||
|
||||
@@ -17,13 +17,14 @@ if (config.mysql) {
|
||||
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({
|
||||
@@ -33,13 +34,14 @@ if (config.mysql) {
|
||||
readOnly: config.readOnly,
|
||||
createDbIfNotExists: config.createDatabaseIfNotExist,
|
||||
postgres: {
|
||||
...config.postgres,
|
||||
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({
|
||||
|
||||
12
src/index.ts
12
src/index.ts
@@ -4,7 +4,6 @@ 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) => {
|
||||
@@ -13,14 +12,7 @@ async function init() {
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
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.
|
||||
@@ -35,4 +27,4 @@ async function init() {
|
||||
}).setTimeout(15000);
|
||||
}
|
||||
|
||||
init().catch((err) => Logger.error(`Index.js: ${err}`));
|
||||
init();
|
||||
|
||||
@@ -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");
|
||||
res.header("Access-Control-Allow-Headers", "Content-Type");
|
||||
next();
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { VideoID, VideoIDHash, Service } from "../types/segments.model";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import { skipSegmentsHashKey, skipSegmentsKey, videoLabelsHashKey, videoLabelsKey } from "../utils/redisKeys";
|
||||
|
||||
type hashType = "skipSegments" | "skipSegmentsHash" | "videoLabel" | "videoLabelHash";
|
||||
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.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 === "videoLabel") redisKey = videoLabelsKey(hashKey as VideoID, service);
|
||||
else if (hashType === "videoLabelHash") redisKey = videoLabelsHashKey(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);
|
||||
*/
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1,74 +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";
|
||||
|
||||
interface AddFeatureRequest extends Request {
|
||||
body: {
|
||||
userID: HashedUserID;
|
||||
adminUserID: string;
|
||||
feature: string;
|
||||
enabled: string;
|
||||
}
|
||||
}
|
||||
|
||||
const allowedFeatures = {
|
||||
vip: [
|
||||
Feature.ChapterSubmitter,
|
||||
Feature.FillerSubmitter
|
||||
],
|
||||
admin: [
|
||||
Feature.ChapterSubmitter,
|
||||
Feature.FillerSubmitter
|
||||
]
|
||||
};
|
||||
|
||||
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()]);
|
||||
}
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -35,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({
|
||||
@@ -49,7 +48,7 @@ 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.",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
@@ -124,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.
|
||||
@@ -135,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>
|
||||
@@ -238,7 +232,7 @@ async function queueDump(): Promise<void> {
|
||||
|
||||
resolve(error ? stderr : stdout);
|
||||
});
|
||||
});
|
||||
})
|
||||
|
||||
dumpFiles.push({
|
||||
fileName,
|
||||
|
||||
@@ -1,52 +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;
|
||||
},
|
||||
params: {
|
||||
type: TokenType;
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateTokenRequest(req: GenerateTokenRequest, res: Response): Promise<Response> {
|
||||
const { query: { code, adminUserID }, params: { type } } = req;
|
||||
const adminUserIDHash = adminUserID ? (await getHashCache(adminUserID)) : null;
|
||||
|
||||
if (!code || !type) {
|
||||
return res.status(400).send("Invalid request");
|
||||
}
|
||||
|
||||
if (type === TokenType.patreon || (type === TokenType.local && adminUserIDHash === config.adminUserID)) {
|
||||
const licenseKey = await createAndSaveToken(type, code);
|
||||
|
||||
/* istanbul ignore else */
|
||||
if (licenseKey) {
|
||||
return res.status(200).send(`
|
||||
<h1>
|
||||
Your license key:
|
||||
</h1>
|
||||
<p>
|
||||
<b>
|
||||
${licenseKey}
|
||||
</b>
|
||||
</p>
|
||||
<p>
|
||||
Copy this into the textbox in the other tab
|
||||
</p>
|
||||
`);
|
||||
} else {
|
||||
return res.status(401).send(`
|
||||
<h1>
|
||||
Failed to generate an license key
|
||||
</h1>
|
||||
`);
|
||||
}
|
||||
} else {
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
}
|
||||
@@ -1,222 +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, BrandingHashDBResult, BrandingResult, 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";
|
||||
|
||||
enum BrandingSubmissionType {
|
||||
Title = "title",
|
||||
Thumbnail = "thumbnail"
|
||||
}
|
||||
|
||||
export async function getVideoBranding(res: Response, videoID: VideoID, service: Service, ip: IPAddress): Promise<BrandingResult> {
|
||||
const getTitles = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "titles"."title", "titles"."original", "titleVotes"."votes", "titleVotes"."locked", "titleVotes"."shadowHidden", "titles"."UUID", "titles"."videoID", "titles"."hashedVideoID"
|
||||
FROM "titles" JOIN "titleVotes" ON "titles"."UUID" = "titleVotes"."UUID"
|
||||
WHERE "titles"."videoID" = ? AND "titles"."service" = ? AND "titleVotes"."votes" > -2`,
|
||||
[videoID, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<TitleDBResult[]>;
|
||||
|
||||
const getThumbnails = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "thumbnailTimestamps"."timestamp", "thumbnails"."original", "thumbnailVotes"."votes", "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"."videoID" = ? AND "thumbnails"."service" = ? AND "thumbnailVotes"."votes" > -2`,
|
||||
[videoID, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<ThumbnailDBResult[]>;
|
||||
|
||||
const getBranding = async () => ({
|
||||
titles: await getTitles(),
|
||||
thumbnails: await getThumbnails()
|
||||
});
|
||||
|
||||
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(branding.titles, branding.thumbnails, ip, cache);
|
||||
}
|
||||
|
||||
export async function getVideoBrandingByHash(videoHashPrefix: VideoIDHash, service: Service, ip: IPAddress): Promise<Record<VideoID, BrandingResult>> {
|
||||
const getTitles = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "titles"."title", "titles"."original", "titleVotes"."votes", "titleVotes"."locked", "titleVotes"."shadowHidden", "titles"."UUID", "titles"."videoID", "titles"."hashedVideoID"
|
||||
FROM "titles" JOIN "titleVotes" ON "titles"."UUID" = "titleVotes"."UUID"
|
||||
WHERE "titles"."hashedVideoID" LIKE ? AND "titles"."service" = ? AND "titleVotes"."votes" > -2`,
|
||||
[`${videoHashPrefix}%`, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<TitleDBResult[]>;
|
||||
|
||||
const getThumbnails = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "thumbnailTimestamps"."timestamp", "thumbnails"."original", "thumbnailVotes"."votes", "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" > -2`,
|
||||
[`${videoHashPrefix}%`, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<ThumbnailDBResult[]>;
|
||||
|
||||
const branding = await QueryCacher.get(async () => {
|
||||
// Make sure they are both called in parallel
|
||||
const branding = {
|
||||
titles: getTitles(),
|
||||
thumbnails: getThumbnails()
|
||||
};
|
||||
|
||||
const dbResult: Record<VideoID, BrandingHashDBResult> = {};
|
||||
const initResult = (submission: BrandingDBSubmission) => {
|
||||
dbResult[submission.videoID] = dbResult[submission.videoID] || {
|
||||
titles: [],
|
||||
thumbnails: []
|
||||
};
|
||||
};
|
||||
|
||||
(await branding.titles).map((title) => {
|
||||
initResult(title);
|
||||
dbResult[title.videoID].titles.push(title);
|
||||
});
|
||||
(await branding.thumbnails).map((thumbnail) => {
|
||||
initResult(thumbnail);
|
||||
dbResult[thumbnail.videoID].thumbnails.push(thumbnail);
|
||||
});
|
||||
|
||||
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(branding[castedKey].titles, branding[castedKey].thumbnails, ip, cache);
|
||||
}));
|
||||
|
||||
return processedResult;
|
||||
}
|
||||
|
||||
async function filterAndSortBranding(dbTitles: TitleDBResult[], dbThumbnails: ThumbnailDBResult[], 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))
|
||||
.sort((a, b) => b.votes - a.votes)
|
||||
.sort((a, b) => b.locked - a.locked)
|
||||
.map((r) => ({
|
||||
title: r.title,
|
||||
original: r.original === 1,
|
||||
votes: r.votes,
|
||||
locked: r.locked === 1,
|
||||
UUID: r.UUID,
|
||||
})) as TitleResult[];
|
||||
|
||||
const thumbnails = shuffleArray(dbThumbnails.filter(await shouldKeepThumbnails))
|
||||
.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,
|
||||
locked: r.locked === 1,
|
||||
UUID: r.UUID
|
||||
})) as ThumbnailResult[];
|
||||
|
||||
return {
|
||||
titles,
|
||||
thumbnails
|
||||
};
|
||||
}
|
||||
|
||||
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.HIDDEN) 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
|
||||
return false;
|
||||
}
|
||||
}));
|
||||
|
||||
return (_, index) => shouldKeep[index];
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
if (!videoID) {
|
||||
return res.status(400).send("Missing parameter: videoID");
|
||||
}
|
||||
|
||||
const ip = getIP(req);
|
||||
try {
|
||||
const result = await getVideoBranding(res, videoID, service, ip);
|
||||
|
||||
const status = result.titles.length > 0 || result.thumbnails.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);
|
||||
|
||||
try {
|
||||
const result = await getVideoBrandingByHash(hashPrefix, service, ip);
|
||||
|
||||
const status = !isEmpty(result) ? 200 : 404;
|
||||
return res.status(status).json(result);
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
return res.status(500).send([]);
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ 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 OR ("views" > 25 AND "votes" >= 0)) AND "videoID" IN (
|
||||
WHERE ("votes" > 0 OR ("views" > 100 AND "votes" >= 0)) AND "videoID" IN (
|
||||
SELECT "videoID"
|
||||
FROM "videoInfo"
|
||||
WHERE "channelID" = ?
|
||||
|
||||
@@ -7,11 +7,7 @@ export async function getDaysSavedFormatted(req: Request, res: Response): Promis
|
||||
if (row !== undefined) {
|
||||
//send this result
|
||||
return res.send({
|
||||
daysSaved: row.daysSaved?.toFixed(2) ?? "0",
|
||||
});
|
||||
} else {
|
||||
return res.send({
|
||||
daysSaved: 0
|
||||
daysSaved: row.daysSaved.toFixed(2),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -11,47 +11,46 @@ 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";
|
||||
|
||||
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) {
|
||||
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 {
|
||||
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = await 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));
|
||||
}
|
||||
|
||||
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 = cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted]?.some(
|
||||
@@ -61,9 +60,19 @@ async function prepareCategorySegments(req: Request, videoID: VideoID, service:
|
||||
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],
|
||||
@@ -87,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;
|
||||
@@ -94,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) => ({
|
||||
@@ -115,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;
|
||||
@@ -134,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;
|
||||
@@ -150,24 +168,20 @@ 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;
|
||||
data.segments = (await prepareCategorySegments(req, videoID as VideoID, service, videoData.segments, cache, canUseCache))
|
||||
.filter((segment: Segment) => categories.includes(segment?.category) && actionTypes.includes(segment?.actionType))
|
||||
.map((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
|
||||
}));
|
||||
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));
|
||||
|
||||
if (forcePoiAsSkip) {
|
||||
data.segments = data.segments.map((segment) => ({
|
||||
@@ -179,10 +193,15 @@ 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 */ {
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return null;
|
||||
}
|
||||
@@ -192,10 +211,9 @@ 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) {
|
||||
@@ -209,10 +227,9 @@ 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));
|
||||
@@ -283,13 +300,18 @@ function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOf
|
||||
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
|
||||
? 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 = getWeightedRandomChoice(groups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Full);
|
||||
chosenGroups = getWeightedRandomChoice(chosenGroups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Poi);
|
||||
@@ -303,9 +325,6 @@ async function chooseSegments(videoID: VideoID, service: Service, segments: DBSe
|
||||
//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
|
||||
@@ -314,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);
|
||||
@@ -327,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;
|
||||
}
|
||||
@@ -391,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(() => null);
|
||||
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 => {
|
||||
@@ -453,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
|
||||
};
|
||||
|
||||
@@ -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,27 +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, 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, requiredSegments, service);
|
||||
|
||||
try {
|
||||
await getEtag("skipSegmentsHash", 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);
|
||||
}
|
||||
|
||||
@@ -2,53 +2,31 @@ import { db } from "../databases/databases";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { Request, Response } from "express";
|
||||
import os from "os";
|
||||
import redis, { getRedisStats } from "../utils/redis";
|
||||
import { promiseOrTimeout } from "../utils/promise";
|
||||
import { Postgres } from "../databases/Postgres";
|
||||
import redis from "../utils/redis";
|
||||
|
||||
export async function getStatus(req: Request, res: Response): Promise<Response> {
|
||||
const startTime = Date.now();
|
||||
let value = req.params.value as string[] | string;
|
||||
value = Array.isArray(value) ? value[0] : value;
|
||||
let processTime, redisProcessTime = -1;
|
||||
try {
|
||||
const dbStartTime = Date.now();
|
||||
const dbVersion = await promiseOrTimeout(db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"]), 5000)
|
||||
.then(e => {
|
||||
processTime = Date.now() - dbStartTime;
|
||||
return e.value;
|
||||
})
|
||||
.catch(e => /* istanbul ignore next */ {
|
||||
Logger.error(`status: SQL query timed out: ${e}`);
|
||||
return -1;
|
||||
});
|
||||
const dbVersion = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value;
|
||||
let statusRequests: unknown = 0;
|
||||
const redisStartTime = Date.now();
|
||||
const numberRequests = await promiseOrTimeout(redis.increment("statusRequest"), 5000)
|
||||
.then(e => {
|
||||
redisProcessTime = Date.now() - redisStartTime;
|
||||
return e;
|
||||
}).catch(e => /* istanbul ignore next */ {
|
||||
Logger.error(`status: redis increment timed out ${e}`);
|
||||
return [-1];
|
||||
});
|
||||
statusRequests = numberRequests?.[0];
|
||||
try {
|
||||
const numberRequests = await redis.increment("statusRequest");
|
||||
statusRequests = numberRequests?.[0];
|
||||
} catch (error) { } // eslint-disable-line no-empty
|
||||
|
||||
const statusValues: Record<string, any> = {
|
||||
uptime: process.uptime(),
|
||||
commit: (global as any)?.HEADCOMMIT ?? "unknown",
|
||||
commit: (global as any).HEADCOMMIT || "unknown",
|
||||
db: Number(dbVersion),
|
||||
startTime,
|
||||
processTime,
|
||||
redisProcessTime,
|
||||
processTime: Date.now() - startTime,
|
||||
loadavg: os.loadavg().slice(1), // only return 5 & 15 minute load average
|
||||
statusRequests,
|
||||
hostname: os.hostname(),
|
||||
postgresStats: (db as Postgres)?.getStats?.(),
|
||||
redisStats: getRedisStats(),
|
||||
statusRequests
|
||||
};
|
||||
return value ? res.send(JSON.stringify(statusValues[value])) : res.send(statusValues);
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
@@ -2,12 +2,9 @@ import { db } from "../databases/databases";
|
||||
import { createMemoryCache } from "../utils/createMemoryCache";
|
||||
import { config } from "../config";
|
||||
import { Request, Response } from "express";
|
||||
import { validateCategories } from "../utils/parseParams";
|
||||
|
||||
const MILLISECONDS_IN_MINUTE = 60000;
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const getTopCategoryUsersWithCache = createMemoryCache(generateTopCategoryUsersStats, config.getTopUsersCacheTimeMinutes * MILLISECONDS_IN_MINUTE);
|
||||
/* istanbul ignore next */
|
||||
const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400;
|
||||
|
||||
interface DBSegment {
|
||||
@@ -28,7 +25,7 @@ async function generateTopCategoryUsersStats(sortBy: string, category: string) {
|
||||
SUM("votes") as "userVotes", COALESCE("userNames"."userName", "sponsorTimes"."userID") as "userName" FROM "sponsorTimes" LEFT JOIN "userNames" ON "sponsorTimes"."userID"="userNames"."userID"
|
||||
LEFT JOIN "shadowBannedUsers" ON "sponsorTimes"."userID"="shadowBannedUsers"."userID"
|
||||
WHERE "sponsorTimes"."category" = ? AND "sponsorTimes"."votes" > -1 AND "sponsorTimes"."shadowHidden" != 1 AND "shadowBannedUsers"."userID" IS NULL
|
||||
GROUP BY COALESCE("userName", "sponsorTimes"."userID") HAVING SUM("votes") > 2
|
||||
GROUP BY COALESCE("userName", "sponsorTimes"."userID") HAVING SUM("votes") > 20
|
||||
ORDER BY "${sortBy}" DESC LIMIT 100`, [maxRewardTimePerSegmentInSeconds, maxRewardTimePerSegmentInSeconds, category]);
|
||||
|
||||
if (rows) {
|
||||
@@ -36,10 +33,11 @@ async function generateTopCategoryUsersStats(sortBy: string, category: string) {
|
||||
userNames.push(row.userName);
|
||||
viewCounts.push(row.viewCount);
|
||||
totalSubmissions.push(row.totalSubmissions);
|
||||
minutesSaved.push(category === "chapter" ? 0 : row.minutesSaved);
|
||||
minutesSaved.push(row.minutesSaved);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
userNames,
|
||||
viewCounts,
|
||||
@@ -52,15 +50,11 @@ export async function getTopCategoryUsers(req: Request, res: Response): Promise<
|
||||
const sortType = parseInt(req.query.sortType as string);
|
||||
const category = req.query.category as string;
|
||||
|
||||
if (sortType == undefined || !validateCategories([category]) ) {
|
||||
if (sortType == undefined || !config.categoryList.includes(category) ) {
|
||||
//invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
if (db.highLoad()) {
|
||||
return res.status(503).send("Disabled for load reasons");
|
||||
}
|
||||
|
||||
//setup which sort type to use
|
||||
let sortBy = "";
|
||||
if (sortType == 0) {
|
||||
|
||||
@@ -4,7 +4,6 @@ import { config } from "../config";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
const MILLISECONDS_IN_MINUTE = 60000;
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const getTopUsersWithCache = createMemoryCache(generateTopUsersStats, config.getTopUsersCacheTimeMinutes * MILLISECONDS_IN_MINUTE);
|
||||
const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400;
|
||||
|
||||
@@ -28,12 +27,11 @@ async function generateTopUsersStats(sortBy: string, categoryStatsEnabled = fals
|
||||
SUM(CASE WHEN category = 'poi_highlight' THEN 1 ELSE 0 END) as "categorySumHighlight",
|
||||
SUM(CASE WHEN category = 'filler' THEN 1 ELSE 0 END) as "categorySumFiller",
|
||||
SUM(CASE WHEN category = 'exclusive_access' THEN 1 ELSE 0 END) as "categorySumExclusiveAccess",
|
||||
SUM(CASE WHEN category = 'chapter' THEN 1 ELSE 0 END) as "categorySumChapter",
|
||||
`;
|
||||
}
|
||||
|
||||
const rows = await db.prepare("all", `SELECT COUNT(*) as "totalSubmissions", SUM(views) as "viewCount",
|
||||
SUM(CASE WHEN "sponsorTimes"."actionType" = 'chapter' THEN 0 ELSE ((CASE WHEN "sponsorTimes"."endTime" - "sponsorTimes"."startTime" > ? THEN ? ELSE "sponsorTimes"."endTime" - "sponsorTimes"."startTime" END) / 60) * "sponsorTimes"."views" END) as "minutesSaved",
|
||||
SUM(((CASE WHEN "sponsorTimes"."endTime" - "sponsorTimes"."startTime" > ? THEN ? ELSE "sponsorTimes"."endTime" - "sponsorTimes"."startTime" END) / 60) * "sponsorTimes"."views") as "minutesSaved",
|
||||
SUM("votes") as "userVotes", ${additionalFields} COALESCE("userNames"."userName", "sponsorTimes"."userID") as "userName" FROM "sponsorTimes" LEFT JOIN "userNames" ON "sponsorTimes"."userID"="userNames"."userID"
|
||||
LEFT JOIN "shadowBannedUsers" ON "sponsorTimes"."userID"="shadowBannedUsers"."userID"
|
||||
WHERE "sponsorTimes"."votes" > -1 AND "sponsorTimes"."shadowHidden" != 1 AND "shadowBannedUsers"."userID" IS NULL
|
||||
@@ -56,8 +54,7 @@ async function generateTopUsersStats(sortBy: string, categoryStatsEnabled = fals
|
||||
row.categorySumPreview,
|
||||
row.categorySumHighlight,
|
||||
row.categorySumFiller,
|
||||
row.categorySumExclusiveAccess,
|
||||
row.categorySumChapter
|
||||
row.categorySumExclusiveAccess
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -75,6 +72,11 @@ export async function getTopUsers(req: Request, res: Response): Promise<Response
|
||||
const sortType = parseInt(req.query.sortType as string);
|
||||
const categoryStatsEnabled = req.query.categoryStats;
|
||||
|
||||
if (sortType == undefined) {
|
||||
//invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
//setup which sort type to use
|
||||
let sortBy = "";
|
||||
if (sortType == 0) {
|
||||
@@ -88,10 +90,6 @@ export async function getTopUsers(req: Request, res: Response): Promise<Response
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
if (db.highLoad()) {
|
||||
return res.status(503).send("Disabled for load reasons");
|
||||
}
|
||||
|
||||
const stats = await getTopUsersWithCache(sortBy, categoryStatsEnabled);
|
||||
|
||||
//send this result
|
||||
|
||||
@@ -3,7 +3,6 @@ import { config } from "../config";
|
||||
import { Request, Response } from "express";
|
||||
import axios from "axios";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { getCWSUsers } from "../utils/getCWSUsers";
|
||||
|
||||
// A cache of the number of chrome web store users
|
||||
let chromeUsersCache = 0;
|
||||
@@ -11,110 +10,73 @@ let firefoxUsersCache = 0;
|
||||
|
||||
// By the privacy friendly user counter
|
||||
let apiUsersCache = 0;
|
||||
|
||||
let lastUserCountCheck = 0;
|
||||
|
||||
interface DBStatsData {
|
||||
userCount: number,
|
||||
viewCount: number,
|
||||
totalSubmissions: number,
|
||||
minutesSaved: number
|
||||
}
|
||||
|
||||
let lastFetch: DBStatsData = {
|
||||
userCount: 0,
|
||||
viewCount: 0,
|
||||
totalSubmissions: 0,
|
||||
minutesSaved: 0
|
||||
};
|
||||
|
||||
updateExtensionUsers();
|
||||
|
||||
export async function getTotalStats(req: Request, res: Response): Promise<void> {
|
||||
const countContributingUsers = Boolean(req.query?.countContributingUsers == "true");
|
||||
const row = await getStats(countContributingUsers);
|
||||
lastFetch = row;
|
||||
const userCountQuery = `(SELECT COUNT(*) FROM (SELECT DISTINCT "userID" from "sponsorTimes") t) "userCount",`;
|
||||
|
||||
/* istanbul ignore if */
|
||||
if (!row) res.sendStatus(500);
|
||||
const extensionUsers = chromeUsersCache + firefoxUsersCache;
|
||||
const row = await db.prepare("get", `SELECT ${req.query.countContributingUsers ? userCountQuery : ""} COUNT(*) as "totalSubmissions",
|
||||
SUM("views") as "viewCount", SUM(("endTime" - "startTime") / 60 * "views") as "minutesSaved" FROM "sponsorTimes" WHERE "shadowHidden" != 1 AND "votes" >= 0`, []);
|
||||
|
||||
//send this result
|
||||
res.send({
|
||||
userCount: row.userCount ?? 0,
|
||||
activeUsers: extensionUsers,
|
||||
apiUsers: Math.max(apiUsersCache, extensionUsers),
|
||||
viewCount: row.viewCount,
|
||||
totalSubmissions: row.totalSubmissions,
|
||||
minutesSaved: row.minutesSaved,
|
||||
});
|
||||
if (row !== undefined) {
|
||||
const extensionUsers = chromeUsersCache + firefoxUsersCache;
|
||||
|
||||
// Check if the cache should be updated (every ~14 hours)
|
||||
const now = Date.now();
|
||||
if (now - lastUserCountCheck > 5000000) {
|
||||
lastUserCountCheck = now;
|
||||
//send this result
|
||||
res.send({
|
||||
userCount: row.userCount,
|
||||
activeUsers: extensionUsers,
|
||||
apiUsers: Math.max(apiUsersCache, extensionUsers),
|
||||
viewCount: row.viewCount,
|
||||
totalSubmissions: row.totalSubmissions,
|
||||
minutesSaved: row.minutesSaved,
|
||||
});
|
||||
|
||||
updateExtensionUsers();
|
||||
}
|
||||
}
|
||||
// Check if the cache should be updated (every ~14 hours)
|
||||
const now = Date.now();
|
||||
if (now - lastUserCountCheck > 5000000) {
|
||||
lastUserCountCheck = now;
|
||||
|
||||
function getStats(countContributingUsers: boolean): Promise<DBStatsData> {
|
||||
if (db.highLoad()) {
|
||||
return Promise.resolve(lastFetch);
|
||||
} else {
|
||||
const userCountQuery = `(SELECT COUNT(*) FROM (SELECT DISTINCT "userID" from "sponsorTimes") t) "userCount",`;
|
||||
|
||||
return db.prepare("get", `SELECT ${countContributingUsers ? userCountQuery : ""} COUNT(*) as "totalSubmissions",
|
||||
SUM("views") as "viewCount", SUM(("endTime" - "startTime") / 60 * "views") as "minutesSaved" FROM "sponsorTimes" WHERE "shadowHidden" != 1 AND "votes" >= 0 AND "actionType" != 'chapter'`, []);
|
||||
updateExtensionUsers();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateExtensionUsers() {
|
||||
/* istanbul ignore else */
|
||||
if (config.userCounterURL) {
|
||||
axios.get(`${config.userCounterURL}/api/v1/userCount`)
|
||||
.then(res => apiUsersCache = Math.max(apiUsersCache, res.data.userCount))
|
||||
.catch( /* istanbul ignore next */ () => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
|
||||
.then(res => {
|
||||
apiUsersCache = Math.max(apiUsersCache, res.data.userCount);
|
||||
})
|
||||
.catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
|
||||
}
|
||||
|
||||
const mozillaAddonsUrl = "https://addons.mozilla.org/api/v3/addons/addon/sponsorblock/";
|
||||
const chromeExtensionUrl = "https://chrome.google.com/webstore/detail/sponsorblock-for-youtube/mnjggcdmjocbbbhaepdhchncahnbgone";
|
||||
const chromeExtId = "mnjggcdmjocbbbhaepdhchncahnbgone";
|
||||
|
||||
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)
|
||||
);
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
function getChromeUsers(chromeExtensionUrl: string): Promise<number> {
|
||||
return axios.get(chromeExtensionUrl)
|
||||
.then(res => {
|
||||
const body = res.data;
|
||||
// 2021-01-05
|
||||
// [...]<span><meta itemprop="interactionCount" content="UserDownloads:100.000+"/><meta itemprop="opera[...]
|
||||
const matchingString = '"UserDownloads:';
|
||||
const matchingStringLen = matchingString.length;
|
||||
const userDownloadsStartIndex = body.indexOf(matchingString);
|
||||
/* istanbul ignore else */
|
||||
if (userDownloadsStartIndex >= 0) {
|
||||
const closingQuoteIndex = body.indexOf('"', userDownloadsStartIndex + matchingStringLen);
|
||||
const userDownloadsStr = body.substr(userDownloadsStartIndex + matchingStringLen, closingQuoteIndex - userDownloadsStartIndex).replace(",", "").replace(".", "");
|
||||
return parseInt(userDownloadsStr);
|
||||
} else {
|
||||
lastUserCountCheck = 0;
|
||||
}
|
||||
firefoxUsersCache = res.data.average_daily_users;
|
||||
axios.get(chromeExtensionUrl)
|
||||
.then(res => {
|
||||
const body = res.data;
|
||||
// 2021-01-05
|
||||
// [...]<span><meta itemprop="interactionCount" content="UserDownloads:100.000+"/><meta itemprop="opera[...]
|
||||
const matchingString = '"UserDownloads:';
|
||||
const matchingStringLen = matchingString.length;
|
||||
const userDownloadsStartIndex = body.indexOf(matchingString);
|
||||
if (userDownloadsStartIndex >= 0) {
|
||||
const closingQuoteIndex = body.indexOf('"', userDownloadsStartIndex + matchingStringLen);
|
||||
const userDownloadsStr = body.substr(userDownloadsStartIndex + matchingStringLen, closingQuoteIndex - userDownloadsStartIndex).replace(",","").replace(".","");
|
||||
chromeUsersCache = parseInt(userDownloadsStr);
|
||||
}
|
||||
else {
|
||||
lastUserCountCheck = 0;
|
||||
}
|
||||
})
|
||||
.catch(() => Logger.debug(`Failing to connect to ${chromeExtensionUrl}`));
|
||||
})
|
||||
.catch(/* istanbul ignore next */ () => {
|
||||
Logger.debug(`Failing to connect to ${chromeExtensionUrl}`);
|
||||
return 0;
|
||||
.catch(() => {
|
||||
Logger.debug(`Failing to connect to ${mozillaAddonsUrl}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ function getFuzzyUserID(userName: string): Promise<{userName: string, userID: Us
|
||||
try {
|
||||
return db.prepare("all", `SELECT "userName", "userID" FROM "userNames" WHERE "userName"
|
||||
LIKE ? ESCAPE '\\' LIMIT 10`, [userName]);
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ function getFuzzyUserID(userName: string): Promise<{userName: string, userID: Us
|
||||
function getExactUserID(userName: string): Promise<{userName: string, userID: UserID }[]> {
|
||||
try {
|
||||
return db.prepare("all", `SELECT "userName", "userID" from "userNames" WHERE "userName" = ? LIMIT 10`, [userName]);
|
||||
} catch (err) /* istanbul ignore next */{
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,6 @@ export async function getUserID(req: Request, res: Response): Promise<Response>
|
||||
: await getFuzzyUserID(userName);
|
||||
|
||||
if (results === undefined || results === null) {
|
||||
/* istanbul ignore next */
|
||||
return res.sendStatus(500);
|
||||
} else if (results.length === 0) {
|
||||
return res.sendStatus(404);
|
||||
|
||||
@@ -5,17 +5,16 @@ import { Request, Response } from "express";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { HashedUserID, UserID } from "../types/user.model";
|
||||
import { getReputation } from "../utils/reputation";
|
||||
import { Category, SegmentUUID } from "../types/segments.model";
|
||||
import { SegmentUUID } from "../types/segments.model";
|
||||
import { config } from "../config";
|
||||
import { canSubmit } from "../utils/permissions";
|
||||
const maxRewardTime = config.maxRewardTimePerSegmentInSeconds;
|
||||
|
||||
async function dbGetSubmittedSegmentSummary(userID: HashedUserID): Promise<{ minutesSaved: number, segmentCount: number }> {
|
||||
try {
|
||||
const row = await db.prepare("get",
|
||||
`SELECT SUM(CASE WHEN "actionType" = 'chapter' THEN 0 ELSE ((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views" END) as "minutesSaved",
|
||||
`SELECT SUM(((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views") as "minutesSaved",
|
||||
count(*) as "segmentCount" FROM "sponsorTimes"
|
||||
WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`, [maxRewardTime, maxRewardTime, userID], { useReplica: true });
|
||||
WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`, [maxRewardTime, maxRewardTime, userID]);
|
||||
if (row.minutesSaved != null) {
|
||||
return {
|
||||
minutesSaved: row.minutesSaved,
|
||||
@@ -27,16 +26,16 @@ async function dbGetSubmittedSegmentSummary(userID: HashedUserID): Promise<{ min
|
||||
segmentCount: 0,
|
||||
};
|
||||
}
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function dbGetIgnoredSegmentCount(userID: HashedUserID): Promise<number> {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT COUNT(*) as "ignoredSegmentCount" FROM "sponsorTimes" WHERE "userID" = ? AND ( "votes" <= -2 OR "shadowHidden" = 1 )`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT COUNT(*) as "ignoredSegmentCount" FROM "sponsorTimes" WHERE "userID" = ? AND ( "votes" <= -2 OR "shadowHidden" = 1 )`, [userID]);
|
||||
return row?.ignoredSegmentCount ?? 0;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -45,34 +44,34 @@ async function dbGetUsername(userID: HashedUserID) {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
|
||||
return row?.userName ?? userID;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function dbGetViewsForUser(userID: HashedUserID) {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT SUM("views") as "viewCount" FROM "sponsorTimes" WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT SUM("views") as "viewCount" FROM "sponsorTimes" WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`, [userID]);
|
||||
return row?.viewCount ?? 0;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function dbGetIgnoredViewsForUser(userID: HashedUserID) {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT SUM("views") as "ignoredViewCount" FROM "sponsorTimes" WHERE "userID" = ? AND ( "votes" <= -2 OR "shadowHidden" = 1 )`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT SUM("views") as "ignoredViewCount" FROM "sponsorTimes" WHERE "userID" = ? AND ( "votes" <= -2 OR "shadowHidden" = 1 )`, [userID]);
|
||||
return row?.ignoredViewCount ?? 0;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function dbGetWarningsForUser(userID: HashedUserID): Promise<number> {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT COUNT(*) as total FROM "warnings" WHERE "userID" = ? AND "enabled" = 1`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT COUNT(*) as total FROM "warnings" WHERE "userID" = ? AND "enabled" = 1`, [userID]);
|
||||
return row?.total ?? 0;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(`Couldn't get warnings for user ${userID}. returning 0`);
|
||||
return 0;
|
||||
}
|
||||
@@ -80,18 +79,18 @@ async function dbGetWarningsForUser(userID: HashedUserID): Promise<number> {
|
||||
|
||||
async function dbGetLastSegmentForUser(userID: HashedUserID): Promise<SegmentUUID> {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT "UUID" FROM "sponsorTimes" WHERE "userID" = ? ORDER BY "timeSubmitted" DESC LIMIT 1`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT "UUID" FROM "sponsorTimes" WHERE "userID" = ? ORDER BY "timeSubmitted" DESC LIMIT 1`, [userID]);
|
||||
return row?.UUID ?? null;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function dbGetActiveWarningReasonForUser(userID: HashedUserID): Promise<string> {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT reason FROM "warnings" WHERE "userID" = ? AND "enabled" = 1 ORDER BY "issueTime" DESC LIMIT 1`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT reason FROM "warnings" WHERE "userID" = ? AND "enabled" = 1 ORDER BY "issueTime" DESC LIMIT 1`, [userID]);
|
||||
return row?.reason ?? "";
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(`Couldn't get reason for user ${userID}. returning blank`);
|
||||
return "";
|
||||
}
|
||||
@@ -99,22 +98,13 @@ async function dbGetActiveWarningReasonForUser(userID: HashedUserID): Promise<st
|
||||
|
||||
async function dbGetBanned(userID: HashedUserID): Promise<boolean> {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ? LIMIT 1`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ? LIMIT 1`, [userID]);
|
||||
return row?.userCount > 0 ?? false;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function getPermissions(userID: HashedUserID): Promise<Record<string, boolean>> {
|
||||
const result: Record<string, boolean> = {};
|
||||
for (const category of config.categoryList) {
|
||||
result[category] = (await canSubmit(userID, category as Category)).canSubmit;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
type cases = Record<string, any>
|
||||
|
||||
const executeIfFunction = (f: any) =>
|
||||
@@ -129,18 +119,16 @@ const functionSwitch = (cases: cases) => (defaultCase: string) => (key: string)
|
||||
const dbGetValue = (userID: HashedUserID, property: string): Promise<string|SegmentUUID|number> => {
|
||||
return functionSwitch({
|
||||
userID,
|
||||
userName: () => dbGetUsername(userID),
|
||||
ignoredSegmentCount: () => dbGetIgnoredSegmentCount(userID),
|
||||
viewCount: () => dbGetViewsForUser(userID),
|
||||
ignoredViewCount: () => dbGetIgnoredViewsForUser(userID),
|
||||
warnings: () => dbGetWarningsForUser(userID),
|
||||
warningReason: () => dbGetActiveWarningReasonForUser(userID),
|
||||
banned: () => dbGetBanned(userID),
|
||||
reputation: () => getReputation(userID),
|
||||
vip: () => isUserVIP(userID),
|
||||
lastSegmentID: () => dbGetLastSegmentForUser(userID),
|
||||
permissions: () => getPermissions(userID),
|
||||
freeChaptersAccess: () => true
|
||||
userName: dbGetUsername(userID),
|
||||
ignoredSegmentCount: dbGetIgnoredSegmentCount(userID),
|
||||
viewCount: dbGetViewsForUser(userID),
|
||||
ignoredViewCount: dbGetIgnoredViewsForUser(userID),
|
||||
warnings: dbGetWarningsForUser(userID),
|
||||
warningReason: dbGetActiveWarningReasonForUser(userID),
|
||||
banned: dbGetBanned(userID),
|
||||
reputation: getReputation(userID),
|
||||
vip: isUserVIP(userID),
|
||||
lastSegmentID: dbGetLastSegmentForUser(userID),
|
||||
})("")(property);
|
||||
};
|
||||
|
||||
@@ -150,7 +138,7 @@ async function getUserInfo(req: Request, res: Response): Promise<Response> {
|
||||
const defaultProperties: string[] = ["userID", "userName", "minutesSaved", "segmentCount", "ignoredSegmentCount",
|
||||
"viewCount", "ignoredViewCount", "warnings", "warningReason", "reputation",
|
||||
"vip", "lastSegmentID"];
|
||||
const allProperties: string[] = [...defaultProperties, "banned", "permissions", "freeChaptersAccess"];
|
||||
const allProperties: string[] = [...defaultProperties, "banned"];
|
||||
let paramValues: string[] = req.query.values
|
||||
? JSON.parse(req.query.values as string)
|
||||
: req.query.value
|
||||
@@ -187,9 +175,9 @@ async function getUserInfo(req: Request, res: Response): Promise<Response> {
|
||||
export async function endpoint(req: Request, res: Response): Promise<Response> {
|
||||
try {
|
||||
return await getUserInfo(req, res);
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
if (err instanceof SyntaxError) { // catch JSON.parse error
|
||||
return res.status(400).send("Invalid values JSON");
|
||||
} else return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ async function dbGetUserSummary(userID: HashedUserID, fetchCategoryStats: boolea
|
||||
SUM(CASE WHEN "category" = 'poi_highlight' THEN 1 ELSE 0 END) as "categorySumHighlight",
|
||||
SUM(CASE WHEN "category" = 'filler' THEN 1 ELSE 0 END) as "categorySumFiller",
|
||||
SUM(CASE WHEN "category" = 'exclusive_access' THEN 1 ELSE 0 END) as "categorySumExclusiveAccess",
|
||||
SUM(CASE WHEN "category" = 'chapter' THEN 1 ELSE 0 END) as "categorySumChapter",
|
||||
`;
|
||||
}
|
||||
if (fetchActionTypeStats) {
|
||||
@@ -30,16 +29,15 @@ async function dbGetUserSummary(userID: HashedUserID, fetchCategoryStats: boolea
|
||||
SUM(CASE WHEN "actionType" = 'mute' THEN 1 ELSE 0 END) as "typeSumMute",
|
||||
SUM(CASE WHEN "actionType" = 'full' THEN 1 ELSE 0 END) as "typeSumFull",
|
||||
SUM(CASE WHEN "actionType" = 'poi' THEN 1 ELSE 0 END) as "typeSumPoi",
|
||||
SUM(CASE WHEN "actionType" = 'chapter' THEN 1 ELSE 0 END) as "typeSumChapter",
|
||||
`;
|
||||
}
|
||||
try {
|
||||
const row = await db.prepare("get", `
|
||||
SELECT SUM(CASE WHEN "actionType" = 'chapter' THEN 0 ELSE ((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views" END) as "minutesSaved",
|
||||
SELECT SUM(((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views") as "minutesSaved",
|
||||
${additionalQuery}
|
||||
count(*) as "segmentCount"
|
||||
FROM "sponsorTimes"
|
||||
WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`,
|
||||
WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" !=1`,
|
||||
[maxRewardTimePerSegmentInSeconds, maxRewardTimePerSegmentInSeconds, userID]);
|
||||
const source = (row.minutesSaved != null) ? row : {};
|
||||
const handler = { get: (target: Record<string, any>, name: string) => target?.[name] || 0 };
|
||||
@@ -62,7 +60,6 @@ async function dbGetUserSummary(userID: HashedUserID, fetchCategoryStats: boolea
|
||||
poi_highlight: proxy.categorySumHighlight,
|
||||
filler: proxy.categorySumFiller,
|
||||
exclusive_access: proxy.categorySumExclusiveAccess,
|
||||
chapter: proxy.categorySumChapter,
|
||||
};
|
||||
}
|
||||
if (fetchActionTypeStats) {
|
||||
@@ -70,12 +67,11 @@ async function dbGetUserSummary(userID: HashedUserID, fetchCategoryStats: boolea
|
||||
skip: proxy.typeSumSkip,
|
||||
mute: proxy.typeSumMute,
|
||||
full: proxy.typeSumFull,
|
||||
poi: proxy.typeSumPoi,
|
||||
chapter: proxy.typeSumChapter,
|
||||
poi: proxy.typeSumPoi
|
||||
};
|
||||
}
|
||||
return result;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return null;
|
||||
}
|
||||
@@ -85,7 +81,7 @@ async function dbGetUsername(userID: HashedUserID) {
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
|
||||
return row?.userName ?? userID;
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export async function getUsername(req: Request, res: Response): Promise<Response
|
||||
userID = await getHashCache(userID);
|
||||
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
|
||||
|
||||
if (row !== undefined) {
|
||||
return res.send({
|
||||
@@ -27,7 +27,7 @@ export async function getUsername(req: Request, res: Response): Promise<Response
|
||||
userName: userID,
|
||||
});
|
||||
}
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
import { Request, Response } from "express";
|
||||
import { db } from "../databases/databases";
|
||||
import { videoLabelsHashKey, videoLabelsKey } from "../utils/redisKeys";
|
||||
import { SBRecord } from "../types/lib.model";
|
||||
import { DBSegment, Segment, Service, VideoData, VideoID, VideoIDHash } from "../types/segments.model";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import { getService } from "../utils/getService";
|
||||
|
||||
function transformDBSegments(segments: DBSegment[]): Segment[] {
|
||||
return segments.map((chosenSegment) => ({
|
||||
category: chosenSegment.category,
|
||||
actionType: chosenSegment.actionType,
|
||||
segment: [chosenSegment.startTime, chosenSegment.endTime],
|
||||
UUID: chosenSegment.UUID,
|
||||
locked: chosenSegment.locked,
|
||||
votes: chosenSegment.votes,
|
||||
videoDuration: chosenSegment.videoDuration,
|
||||
userID: chosenSegment.userID,
|
||||
description: chosenSegment.description
|
||||
}));
|
||||
}
|
||||
|
||||
async function getLabelsByVideoID(videoID: VideoID, service: Service): Promise<Segment[]> {
|
||||
try {
|
||||
const segments: DBSegment[] = await getSegmentsFromDBByVideoID(videoID, service);
|
||||
return chooseSegment(segments);
|
||||
} catch (err) {
|
||||
if (err) {
|
||||
Logger.error(err as string);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function getLabelsByHash(hashedVideoIDPrefix: VideoIDHash, service: Service): Promise<SBRecord<VideoID, VideoData>> {
|
||||
const segments: SBRecord<VideoID, VideoData> = {};
|
||||
|
||||
try {
|
||||
type SegmentWithHashPerVideoID = SBRecord<VideoID, { hash: VideoIDHash, segments: DBSegment[] }>;
|
||||
|
||||
const segmentPerVideoID: SegmentWithHashPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service))
|
||||
.reduce((acc: SegmentWithHashPerVideoID, segment: DBSegment) => {
|
||||
acc[segment.videoID] = acc[segment.videoID] || {
|
||||
hash: segment.hashedVideoID,
|
||||
segments: []
|
||||
};
|
||||
|
||||
acc[segment.videoID].segments ??= [];
|
||||
acc[segment.videoID].segments.push(segment);
|
||||
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
for (const [videoID, videoData] of Object.entries(segmentPerVideoID)) {
|
||||
const data: VideoData = {
|
||||
segments: chooseSegment(videoData.segments),
|
||||
};
|
||||
|
||||
if (data.segments.length > 0) {
|
||||
segments[videoID] = data;
|
||||
}
|
||||
}
|
||||
|
||||
return segments;
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function getSegmentsFromDBByHash(hashedVideoIDPrefix: VideoIDHash, service: Service): Promise<DBSegment[]> {
|
||||
const fetchFromDB = () => db
|
||||
.prepare(
|
||||
"all",
|
||||
`SELECT "startTime", "endTime", "videoID", "votes", "locked", "UUID", "userID", "category", "actionType", "hashedVideoID", "description" FROM "sponsorTimes"
|
||||
WHERE "hashedVideoID" LIKE ? AND "service" = ? AND "actionType" = 'full' AND "hidden" = 0 AND "shadowHidden" = 0`,
|
||||
[`${hashedVideoIDPrefix}%`, service]
|
||||
) as Promise<DBSegment[]>;
|
||||
|
||||
if (hashedVideoIDPrefix.length === 3) {
|
||||
return await QueryCacher.get(fetchFromDB, videoLabelsHashKey(hashedVideoIDPrefix, service));
|
||||
}
|
||||
|
||||
return await fetchFromDB();
|
||||
}
|
||||
|
||||
async function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): Promise<DBSegment[]> {
|
||||
const fetchFromDB = () => db
|
||||
.prepare(
|
||||
"all",
|
||||
`SELECT "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "description" FROM "sponsorTimes"
|
||||
WHERE "videoID" = ? AND "service" = ? AND "actionType" = 'full' AND "hidden" = 0 AND "shadowHidden" = 0`,
|
||||
[videoID, service]
|
||||
) as Promise<DBSegment[]>;
|
||||
|
||||
return await QueryCacher.get(fetchFromDB, videoLabelsKey(videoID, service));
|
||||
}
|
||||
|
||||
function chooseSegment<T extends DBSegment>(choices: T[]): Segment[] {
|
||||
// filter out -2 segments
|
||||
choices = choices.filter((segment) => segment.votes > -2);
|
||||
const results = [];
|
||||
// trivial decisions
|
||||
if (choices.length === 0) {
|
||||
return [];
|
||||
} else if (choices.length === 1) {
|
||||
return transformDBSegments(choices);
|
||||
}
|
||||
// if locked, only choose from locked
|
||||
const locked = choices.filter((segment) => segment.locked);
|
||||
if (locked.length > 0) {
|
||||
choices = locked;
|
||||
}
|
||||
//no need to filter, just one label
|
||||
if (choices.length === 1) {
|
||||
return transformDBSegments(choices);
|
||||
}
|
||||
// sponsor > exclusive > selfpromo
|
||||
const findCategory = (category: string) => choices.find((segment) => segment.category === category);
|
||||
|
||||
const categoryResult = findCategory("sponsor") ?? findCategory("exclusive_access") ?? findCategory("selfpromo");
|
||||
if (categoryResult) results.push(categoryResult);
|
||||
|
||||
return transformDBSegments(results);
|
||||
}
|
||||
|
||||
async function handleGetLabel(req: Request, res: Response): Promise<Segment[] | false> {
|
||||
const videoID = req.query.videoID as VideoID;
|
||||
if (!videoID) {
|
||||
res.status(400).send("videoID not specified");
|
||||
return false;
|
||||
}
|
||||
|
||||
const service = getService(req.query.service, req.body.service);
|
||||
const segments = await getLabelsByVideoID(videoID, service);
|
||||
|
||||
if (!segments || segments.length === 0) {
|
||||
res.sendStatus(404);
|
||||
return false;
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
async function endpoint(req: Request, res: Response): Promise<Response> {
|
||||
try {
|
||||
const segments = await handleGetLabel(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 {
|
||||
getLabelsByVideoID,
|
||||
getLabelsByHash,
|
||||
endpoint
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
import { hashPrefixTester } from "../utils/hashPrefixTester";
|
||||
import { getLabelsByHash } from "./getVideoLabel";
|
||||
import { Request, Response } from "express";
|
||||
import { VideoIDHash, Service } from "../types/segments.model";
|
||||
import { getService } from "../utils/getService";
|
||||
|
||||
export async function getVideoLabelsByHash(req: Request, res: Response): Promise<Response> {
|
||||
let hashPrefix = req.params.prefix as VideoIDHash;
|
||||
if (!req.params.prefix || !hashPrefixTester(req.params.prefix)) {
|
||||
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, req.body.service);
|
||||
|
||||
// Get all video id's that match hash prefix
|
||||
const segments = await getLabelsByHash(hashPrefix, service);
|
||||
|
||||
if (!segments) return res.status(404).json([]);
|
||||
|
||||
const output = Object.entries(segments).map(([videoID, data]) => ({
|
||||
videoID,
|
||||
segments: data.segments,
|
||||
}));
|
||||
return res.status(output.length === 0 ? 404 : 200).json(output);
|
||||
}
|
||||
@@ -15,7 +15,7 @@ export async function getViewsForUser(req: Request, res: Response): Promise<Resp
|
||||
userID = await getHashCache(userID);
|
||||
|
||||
try {
|
||||
const row = await db.prepare("get", `SELECT SUM("views") as "viewCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID], { useReplica: true });
|
||||
const row = await db.prepare("get", `SELECT SUM("views") as "viewCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID]);
|
||||
|
||||
//increase the view count by one
|
||||
if (row.viewCount != null) {
|
||||
@@ -25,7 +25,7 @@ export async function getViewsForUser(req: Request, res: Response): Promise<Resp
|
||||
} else {
|
||||
return res.sendStatus(404);
|
||||
}
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
24
src/routes/oldGetVideoSponsorTimes.ts
Normal file
24
src/routes/oldGetVideoSponsorTimes.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { handleGetSegments } from "./getSkipSegments";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise<Response> {
|
||||
const segments = await handleGetSegments(req, res);
|
||||
|
||||
if (segments) {
|
||||
// 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,
|
||||
});
|
||||
}
|
||||
|
||||
// Error has already been handled in the other method
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
import { Request, Response } from "express";
|
||||
import { config } from "../config";
|
||||
import { db, privateDB } from "../databases/databases";
|
||||
|
||||
import { BrandingSubmission, BrandingUUID, TimeThumbnailSubmission } from "../types/branding.model";
|
||||
import { HashedIP, IPAddress, VideoID } from "../types/segments.model";
|
||||
import { HashedUserID } from "../types/user.model";
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
import { getIP } from "../utils/getIP";
|
||||
import { getService } from "../utils/getService";
|
||||
import { isUserVIP } from "../utils/isUserVIP";
|
||||
import { Logger } from "../utils/logger";
|
||||
import crypto from "crypto";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
|
||||
enum BrandingType {
|
||||
Title,
|
||||
Thumbnail
|
||||
}
|
||||
|
||||
interface ExistingVote {
|
||||
UUID: BrandingUUID;
|
||||
type: number;
|
||||
id: number;
|
||||
}
|
||||
|
||||
export async function postBranding(req: Request, res: Response) {
|
||||
const { videoID, userID, title, thumbnail } = req.body as BrandingSubmission;
|
||||
const service = getService(req.body.service);
|
||||
|
||||
if (!videoID || !userID || userID.length < 30 || !service
|
||||
|| ((!title || !title.title)
|
||||
&& (!thumbnail || thumbnail.original == null
|
||||
|| (!thumbnail.original && !(thumbnail as TimeThumbnailSubmission).timestamp)))) {
|
||||
res.status(400).send("Bad Request");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const hashedUserID = await getHashCache(userID);
|
||||
// const isVip = await isUserVIP(hashedUserID);
|
||||
const isVip = false; // TODO: In future, reenable locks
|
||||
const hashedVideoID = await getHashCache(videoID, 1);
|
||||
const hashedIP = await getHashCache(getIP(req) + config.globalSalt as IPAddress);
|
||||
|
||||
const now = Date.now();
|
||||
const voteType = 1;
|
||||
|
||||
await Promise.all([(async () => {
|
||||
if (title) {
|
||||
const existingUUID = (await db.prepare("get", `SELECT "UUID" from "titles" where "videoID" = ? AND "title" = ?`, [videoID, title.title]))?.UUID;
|
||||
const UUID = existingUUID || crypto.randomUUID();
|
||||
|
||||
const existingVote = await handleExistingVotes(BrandingType.Title, videoID, hashedUserID, UUID, hashedIP, voteType);
|
||||
if (existingUUID) {
|
||||
await updateVoteTotals(BrandingType.Title, existingVote, UUID, isVip);
|
||||
} else {
|
||||
await db.prepare("run", `INSERT INTO "titles" ("videoID", "title", "original", "userID", "service", "hashedVideoID", "timeSubmitted", "UUID") VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[videoID, title.title, title.original ? 1 : 0, hashedUserID, service, hashedVideoID, now, UUID]);
|
||||
|
||||
await db.prepare("run", `INSERT INTO "titleVotes" ("UUID", "votes", "locked", "shadowHidden") VALUES (?, 0, ?, 0);`,
|
||||
[UUID, isVip ? 1 : 0]);
|
||||
}
|
||||
|
||||
if (isVip) {
|
||||
// unlock all other titles
|
||||
await db.prepare("run", `UPDATE "titleVotes" SET "locked" = 0 WHERE "UUID" != ? AND "videoID" = ?`, [UUID, videoID]);
|
||||
}
|
||||
}
|
||||
})(), (async () => {
|
||||
if (thumbnail) {
|
||||
const existingUUID = thumbnail.original
|
||||
? (await db.prepare("get", `SELECT "UUID" from "thumbnails" where "videoID" = ? AND "original" = 1`, [videoID]))?.UUID
|
||||
: (await db.prepare("get", `SELECT "thumbnails"."UUID" from "thumbnailTimestamps" JOIN "thumbnails" ON "thumbnails"."UUID" = "thumbnailTimestamps"."UUID"
|
||||
WHERE "thumbnailTimestamps"."timestamp" = ? AND "thumbnails"."videoID" = ?`, [(thumbnail as TimeThumbnailSubmission).timestamp, videoID]))?.UUID;
|
||||
const UUID = existingUUID || crypto.randomUUID();
|
||||
|
||||
const existingVote = await handleExistingVotes(BrandingType.Thumbnail, videoID, hashedUserID, UUID, hashedIP, voteType);
|
||||
if (existingUUID) {
|
||||
await updateVoteTotals(BrandingType.Thumbnail, existingVote, UUID, isVip);
|
||||
} else {
|
||||
await db.prepare("run", `INSERT INTO "thumbnails" ("videoID", "original", "userID", "service", "hashedVideoID", "timeSubmitted", "UUID") VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
[videoID, thumbnail.original ? 1 : 0, hashedUserID, service, hashedVideoID, now, UUID]);
|
||||
|
||||
await db.prepare("run", `INSERT INTO "thumbnailVotes" ("UUID", "votes", "locked", "shadowHidden") VALUES (?, 0, ?, 0)`,
|
||||
[UUID, isVip ? 1 : 0]);
|
||||
|
||||
if (!thumbnail.original) {
|
||||
await db.prepare("run", `INSERT INTO "thumbnailTimestamps" ("UUID", "timestamp") VALUES (?, ?)`,
|
||||
[UUID, (thumbnail as TimeThumbnailSubmission).timestamp]);
|
||||
}
|
||||
|
||||
if (isVip) {
|
||||
// unlock all other titles
|
||||
await db.prepare("run", `UPDATE "thumbnailVotes" SET "locked" = 0 WHERE "UUID" != ? AND "videoID" = ?`, [UUID, videoID]);
|
||||
}
|
||||
}
|
||||
}
|
||||
})()]);
|
||||
|
||||
QueryCacher.clearBrandingCache({ videoID, hashedVideoID, service });
|
||||
res.status(200).send("OK");
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
res.status(500).send("Internal Server Error");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds an existing vote, if found, and it's for a different submission, it undoes it, and points to the new submission.
|
||||
* If no existing vote, it adds one.
|
||||
*/
|
||||
async function handleExistingVotes(type: BrandingType, videoID: VideoID,
|
||||
hashedUserID: HashedUserID, UUID: BrandingUUID, hashedIP: HashedIP, voteType: number): Promise<ExistingVote> {
|
||||
const table = type === BrandingType.Title ? `"titleVotes"` : `"thumbnailVotes"`;
|
||||
|
||||
const existingVote = await privateDB.prepare("get", `SELECT "id", "UUID", "type" from ${table} where "videoID" = ? AND "userID" = ?`, [videoID, hashedUserID]);
|
||||
if (existingVote && existingVote.UUID !== UUID) {
|
||||
if (existingVote.type === 1) {
|
||||
await db.prepare("run", `UPDATE ${table} SET "votes" = "votes" - 1 WHERE "UUID" = ?`, [existingVote.UUID]);
|
||||
}
|
||||
|
||||
await privateDB.prepare("run", `UPDATE ${table} SET "type" = ?, "UUID" = ? WHERE "id" = ?`, [voteType, UUID, existingVote.id]);
|
||||
} else if (!existingVote) {
|
||||
await privateDB.prepare("run", `INSERT INTO ${table} ("videoID", "UUID", "userID", "hashedIP", "type") VALUES (?, ?, ?, ?, ?)`,
|
||||
[videoID, UUID, hashedUserID, hashedIP, voteType]);
|
||||
}
|
||||
|
||||
return existingVote;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only called if an existing vote exists.
|
||||
* Will update public vote totals and locked status.
|
||||
*/
|
||||
async function updateVoteTotals(type: BrandingType, existingVote: ExistingVote, UUID: BrandingUUID, isVip: boolean): Promise<void> {
|
||||
if (!existingVote) return;
|
||||
|
||||
const table = type === BrandingType.Title ? `"titleVotes"` : `"thumbnailVotes"`;
|
||||
|
||||
// Don't upvote if we vote on the same submission
|
||||
if (!existingVote || existingVote.UUID !== UUID) {
|
||||
await db.prepare("run", `UPDATE ${table} SET "votes" = "votes" + 1 WHERE "UUID" = ?`, [UUID]);
|
||||
}
|
||||
|
||||
if (isVip) {
|
||||
await db.prepare("run", `UPDATE ${table} SET "locked" = 1 WHERE "UUID" = ?`, [UUID]);
|
||||
}
|
||||
}
|
||||
@@ -44,15 +44,10 @@ export async function postClearCache(req: Request, res: Response): Promise<Respo
|
||||
hashedVideoID,
|
||||
service
|
||||
});
|
||||
QueryCacher.clearBrandingCache({
|
||||
videoID,
|
||||
hashedVideoID,
|
||||
service
|
||||
});
|
||||
return res.status(200).json({
|
||||
message: `Cache cleared on video ${videoID}`
|
||||
});
|
||||
} catch(err) /* istanbul ignore next */ {
|
||||
} catch(err) {
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ export async function postLockCategories(req: Request, res: Response): Promise<s
|
||||
|
||||
if (!userIsVIP) {
|
||||
res.status(403).json({
|
||||
message: "Must be a VIP to lock videos.",
|
||||
message: "Must be a VIP to mark videos.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -66,7 +66,7 @@ export async function postLockCategories(req: Request, res: Response): Promise<s
|
||||
for (const lock of locksToApply) {
|
||||
try {
|
||||
await db.prepare("run", `INSERT INTO "lockCategories" ("videoID", "userID", "actionType", "category", "hashedVideoID", "reason", "service") VALUES(?, ?, ?, ?, ?, ?, ?)`, [videoID, userID, lock.actionType, lock.category, hashedVideoID, reason, service]);
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(`Error submitting 'lockCategories' marker for category '${lock.category}' and actionType '${lock.actionType}' for video '${videoID}' (${service})`);
|
||||
Logger.error(err as string);
|
||||
res.status(500).json({
|
||||
@@ -82,7 +82,7 @@ export async function postLockCategories(req: Request, res: Response): Promise<s
|
||||
await db.prepare("run",
|
||||
'UPDATE "lockCategories" SET "reason" = ?, "userID" = ? WHERE "videoID" = ? AND "actionType" = ? AND "category" = ? AND "service" = ?',
|
||||
[reason, userID, videoID, lock.actionType, lock.category, service]);
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(`Error submitting 'lockCategories' marker for category '${lock.category}' and actionType '${lock.actionType}' for video '${videoID}' (${service})`);
|
||||
Logger.error(err as string);
|
||||
res.status(500).json({
|
||||
|
||||
@@ -37,7 +37,7 @@ export async function postPurgeAllSegments(req: Request, res: Response): Promise
|
||||
service
|
||||
});
|
||||
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ export async function postSegmentShift(req: Request, res: Response): Promise<Res
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { config } from "../config";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { db, privateDB } from "../databases/databases";
|
||||
import { getMaxResThumbnail } from "../utils/youtubeApi";
|
||||
import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi";
|
||||
import { getSubmissionUUID } from "../utils/getSubmissionUUID";
|
||||
import { getHash } from "../utils/getHash";
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
@@ -13,6 +13,7 @@ import { ActionType, Category, IncomingSegment, IPAddress, SegmentUUID, Service,
|
||||
import { deleteLockCategories } from "./deleteLockCategories";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import { getReputation } from "../utils/reputation";
|
||||
import { APIVideoData, APIVideoInfo } from "../types/youtubeApi.model";
|
||||
import { HashedUserID, UserID } from "../types/user.model";
|
||||
import { isUserVIP } from "../utils/isUserVIP";
|
||||
import { isUserTempVIP } from "../utils/isUserTempVIP";
|
||||
@@ -20,10 +21,6 @@ import { parseUserAgent } from "../utils/userAgent";
|
||||
import { getService } from "../utils/getService";
|
||||
import axios from "axios";
|
||||
import { vote } from "./voteOnSponsorTime";
|
||||
import { canSubmit } from "../utils/permissions";
|
||||
import { getVideoDetails, videoDetails } from "../utils/getVideoDetails";
|
||||
import * as youtubeID from "../utils/youtubeID";
|
||||
import { banUser } from "./shadowBanUser";
|
||||
|
||||
type CheckResult = {
|
||||
pass: boolean,
|
||||
@@ -37,7 +34,7 @@ const CHECK_PASS: CheckResult = {
|
||||
errorCode: 0
|
||||
};
|
||||
|
||||
async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: videoDetails, { submissionStart, submissionEnd }: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) {
|
||||
async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: APIVideoData, { submissionStart, submissionEnd }: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) {
|
||||
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
|
||||
const userName = row !== undefined ? row.userName : null;
|
||||
|
||||
@@ -50,7 +47,7 @@ async function sendWebhookNotification(userID: string, videoID: string, UUID: st
|
||||
"video": {
|
||||
"id": videoID,
|
||||
"title": youtubeData?.title,
|
||||
"thumbnail": getMaxResThumbnail(videoID),
|
||||
"thumbnail": getMaxResThumbnail(youtubeData) || null,
|
||||
"url": `https://www.youtube.com/watch?v=${videoID}`,
|
||||
},
|
||||
"submission": {
|
||||
@@ -66,16 +63,19 @@ async function sendWebhookNotification(userID: string, videoID: string, UUID: st
|
||||
});
|
||||
}
|
||||
|
||||
async function sendWebhooks(apiVideoDetails: videoDetails, userID: string, videoID: string, UUID: string, segmentInfo: any, service: Service) {
|
||||
if (apiVideoDetails && service == Service.YouTube) {
|
||||
async function sendWebhooks(apiVideoInfo: APIVideoInfo, userID: string, videoID: string, UUID: string, segmentInfo: any, service: Service) {
|
||||
if (apiVideoInfo && service == Service.YouTube) {
|
||||
const userSubmissionCountRow = await db.prepare("get", `SELECT count(*) as "submissionCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID]);
|
||||
|
||||
const { data, err } = apiVideoInfo;
|
||||
if (err) return;
|
||||
|
||||
const startTime = parseFloat(segmentInfo.segment[0]);
|
||||
const endTime = parseFloat(segmentInfo.segment[1]);
|
||||
sendWebhookNotification(userID, videoID, UUID, userSubmissionCountRow.submissionCount, apiVideoDetails, {
|
||||
sendWebhookNotification(userID, videoID, UUID, userSubmissionCountRow.submissionCount, data, {
|
||||
submissionStart: startTime,
|
||||
submissionEnd: endTime,
|
||||
}, segmentInfo).catch((e) => Logger.error(`sending webhooks: ${e}`));
|
||||
}, segmentInfo);
|
||||
|
||||
// If it is a first time submission
|
||||
// Then send a notification to discord
|
||||
@@ -83,7 +83,7 @@ async function sendWebhooks(apiVideoDetails: videoDetails, userID: string, video
|
||||
|
||||
axios.post(config.discordFirstTimeSubmissionsWebhookURL, {
|
||||
embeds: [{
|
||||
title: apiVideoDetails.title,
|
||||
title: data?.title,
|
||||
url: `https://www.youtube.com/watch?v=${videoID}&t=${(parseInt(startTime.toFixed(0)) - 2)}s#requiredSegment=${UUID}`,
|
||||
description: `Submission ID: ${UUID}\
|
||||
\n\nTimestamp: \
|
||||
@@ -94,7 +94,7 @@ async function sendWebhooks(apiVideoDetails: videoDetails, userID: string, video
|
||||
name: userID,
|
||||
},
|
||||
thumbnail: {
|
||||
url: getMaxResThumbnail(videoID),
|
||||
url: getMaxResThumbnail(data) || "",
|
||||
},
|
||||
}],
|
||||
})
|
||||
@@ -119,10 +119,18 @@ async function sendWebhooks(apiVideoDetails: videoDetails, userID: string, video
|
||||
// Looks like this was broken for no defined youtube key - fixed but IMO we shouldn't return
|
||||
// false for a pass - it was confusing and lead to this bug - any use of this function in
|
||||
// the future could have the same problem.
|
||||
async function autoModerateSubmission(apiVideoDetails: videoDetails,
|
||||
submission: { videoID: VideoID; userID: HashedUserID; segments: IncomingSegment[], service: Service, videoDuration: number }) {
|
||||
async function autoModerateSubmission(apiVideoInfo: APIVideoInfo,
|
||||
submission: { videoID: VideoID; userID: UserID; segments: IncomingSegment[], service: Service, videoDuration: number }) {
|
||||
|
||||
const apiVideoDuration = (apiVideoInfo: APIVideoInfo) => {
|
||||
if (!apiVideoInfo) return undefined;
|
||||
const { err, data } = apiVideoInfo;
|
||||
// return undefined if API error
|
||||
if (err) return undefined;
|
||||
return data?.lengthSeconds;
|
||||
};
|
||||
// get duration from API
|
||||
const apiDuration = apiVideoDetails.duration;
|
||||
const apiDuration = apiVideoDuration(apiVideoInfo);
|
||||
// if API fail or returns 0, get duration from client
|
||||
const duration = apiDuration || submission.videoDuration;
|
||||
// return false on undefined or 0
|
||||
@@ -130,16 +138,14 @@ async function autoModerateSubmission(apiVideoDetails: videoDetails,
|
||||
|
||||
const segments = submission.segments;
|
||||
// map all times to float array
|
||||
const allSegmentTimes = segments.filter((s) => s.actionType !== ActionType.Chapter)
|
||||
.map(segment => [parseFloat(segment.segment[0]), parseFloat(segment.segment[1])]);
|
||||
const allSegmentTimes = segments.map(segment => [parseFloat(segment.segment[0]), parseFloat(segment.segment[1])]);
|
||||
|
||||
// add previous submissions by this user
|
||||
const allSubmittedByUser = await db.prepare("all", `SELECT "startTime", "endTime" FROM "sponsorTimes" WHERE "userID" = ? AND "videoID" = ? AND "votes" > -1 AND "actionType" != 'chapter' AND "hidden" = 0`
|
||||
, [submission.userID, submission.videoID]) as { startTime: string, endTime: string }[];
|
||||
const allSubmittedByUser = await db.prepare("all", `SELECT "startTime", "endTime" FROM "sponsorTimes" WHERE "userID" = ? AND "videoID" = ? AND "votes" > -1 AND "hidden" = 0`, [submission.userID, submission.videoID]);
|
||||
|
||||
if (allSubmittedByUser) {
|
||||
//add segments the user has previously submitted
|
||||
const allSubmittedTimes = allSubmittedByUser.map((segment) => [parseFloat(segment.startTime), parseFloat(segment.endTime)]);
|
||||
const allSubmittedTimes = allSubmittedByUser.map((segment: { startTime: string, endTime: string }) => [parseFloat(segment.startTime), parseFloat(segment.endTime)]);
|
||||
allSegmentTimes.push(...allSubmittedTimes);
|
||||
}
|
||||
|
||||
@@ -156,7 +162,15 @@ async function autoModerateSubmission(apiVideoDetails: videoDetails,
|
||||
return false;
|
||||
}
|
||||
|
||||
async function checkUserActiveWarning(userID: HashedUserID): Promise<CheckResult> {
|
||||
function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise<APIVideoInfo> {
|
||||
if (config.newLeafURLs !== null) {
|
||||
return YouTubeAPI.listVideos(videoID, ignoreCache);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkUserActiveWarning(userID: string): Promise<CheckResult> {
|
||||
const MILLISECONDS_IN_HOUR = 3600000;
|
||||
const now = Date.now();
|
||||
const warnings = (await db.prepare("all",
|
||||
@@ -186,24 +200,15 @@ async function checkUserActiveWarning(userID: HashedUserID): Promise<CheckResult
|
||||
return CHECK_PASS;
|
||||
}
|
||||
|
||||
async function checkInvalidFields(videoID: VideoID, userID: UserID, hashedUserID: HashedUserID
|
||||
, segments: IncomingSegment[], videoDurationParam: number, userAgent: string, service: Service): Promise<CheckResult> {
|
||||
function checkInvalidFields(videoID: VideoID, userID: UserID, segments: IncomingSegment[]): CheckResult {
|
||||
const invalidFields = [];
|
||||
const errors = [];
|
||||
if (typeof videoID !== "string" || videoID?.length == 0) {
|
||||
invalidFields.push("videoID");
|
||||
}
|
||||
if (service === Service.YouTube && config.mode !== "test") {
|
||||
const sanitizedVideoID = youtubeID.validate(videoID) ? videoID : youtubeID.sanitize(videoID);
|
||||
if (!youtubeID.validate(sanitizedVideoID)) {
|
||||
invalidFields.push("videoID");
|
||||
errors.push("YouTube videoID could not be extracted");
|
||||
}
|
||||
}
|
||||
const minLength = config.minUserIDLength;
|
||||
if (typeof userID !== "string" || userID?.length < minLength) {
|
||||
if (typeof userID !== "string" || userID?.length < 30) {
|
||||
invalidFields.push("userID");
|
||||
if (userID?.length < minLength) errors.push(`userID must be at least ${minLength} characters long`);
|
||||
if (userID?.length < 30) errors.push(`userID must be at least 30 characters long`);
|
||||
}
|
||||
if (!Array.isArray(segments) || segments.length == 0) {
|
||||
invalidFields.push("segments");
|
||||
@@ -218,20 +223,10 @@ async function checkInvalidFields(videoID: VideoID, userID: UserID, hashedUserID
|
||||
}
|
||||
|
||||
if (typeof segmentPair.description !== "string"
|
||||
|| (segmentPair.actionType === ActionType.Chapter && segmentPair.description.length > 60 )
|
||||
|| (segmentPair.description.length !== 0 && segmentPair.actionType !== ActionType.Chapter)) {
|
||||
invalidFields.push("segment description");
|
||||
}
|
||||
|
||||
if (segmentPair.actionType === ActionType.Chapter && segmentPair.description.length > 200) {
|
||||
invalidFields.push("chapter name (too long)");
|
||||
}
|
||||
|
||||
const permission = await canSubmit(hashedUserID, segmentPair.category);
|
||||
if (!permission.canSubmit) {
|
||||
Logger.warn(`Rejecting submission due to lack of permissions for category ${segmentPair.category}: ${segmentPair.segment} ${hashedUserID} ${videoID} ${videoDurationParam} ${userAgent}`);
|
||||
invalidFields.push(`permission to submit ${segmentPair.category}`);
|
||||
errors.push(permission.reason);
|
||||
}
|
||||
}
|
||||
|
||||
if (invalidFields.length !== 0) {
|
||||
@@ -240,7 +235,7 @@ async function checkInvalidFields(videoID: VideoID, userID: UserID, hashedUserID
|
||||
const formattedErrors = errors.reduce((p, c, i) => p + (i !== 0 ? ". " : " ") + c, "");
|
||||
return {
|
||||
pass: false,
|
||||
errorMessage: `No valid ${formattedFields}.${formattedErrors}`,
|
||||
errorMessage: `No valid ${formattedFields} field(s) provided.${formattedErrors}`,
|
||||
errorCode: 400
|
||||
};
|
||||
}
|
||||
@@ -249,7 +244,7 @@ async function checkInvalidFields(videoID: VideoID, userID: UserID, hashedUserID
|
||||
}
|
||||
|
||||
async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, userID: HashedUserID, videoID: VideoID,
|
||||
segments: IncomingSegment[], service: Service, isVIP: boolean, isTempVIP: boolean, lockedCategoryList: Array<any>): Promise<CheckResult> {
|
||||
segments: IncomingSegment[], service: string, isVIP: boolean, lockedCategoryList: Array<any>): Promise<CheckResult> {
|
||||
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
if (segments[i] === undefined || segments[i].segment === undefined || segments[i].category === undefined) {
|
||||
@@ -264,22 +259,15 @@ async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, user
|
||||
// Reject segment if it's in the locked categories list
|
||||
const lockIndex = lockedCategoryList.findIndex(c => segments[i].category === c.category && segments[i].actionType === c.actionType);
|
||||
if (!isVIP && lockIndex !== -1) {
|
||||
QueryCacher.clearSegmentCache({
|
||||
videoID,
|
||||
hashedVideoID: await getHashCache(videoID, 1),
|
||||
service,
|
||||
userID
|
||||
});
|
||||
|
||||
// TODO: Do something about the fradulent submission
|
||||
Logger.warn(`Caught a submission for a locked category. userID: '${userID}', videoID: '${videoID}', category: '${segments[i].category}', times: ${segments[i].segment}`);
|
||||
return {
|
||||
pass: false,
|
||||
errorCode: 403,
|
||||
errorMessage:
|
||||
`Users have voted that all the segments required for this video have already been submitted for the following category: ` +
|
||||
`Users have voted that new segments aren't needed for the following category: ` +
|
||||
`'${segments[i].category}'\n` +
|
||||
`${lockedCategoryList[lockIndex].reason?.length !== 0 ? `\nReason: '${lockedCategoryList[lockIndex].reason}\n'` : ""}` +
|
||||
`You may need to refresh if you don't see the segments.\n` +
|
||||
`${lockedCategoryList[lockIndex].reason?.length !== 0 ? `\nReason: '${lockedCategoryList[lockIndex].reason}'` : ""}\n` +
|
||||
`${(segments[i].category === "sponsor" ? "\nMaybe the segment you are submitting is a different category that you have not enabled and is not a sponsor. " +
|
||||
"Categories that aren't sponsor, such as self-promotion can be enabled in the options.\n" : "")}` +
|
||||
`\nIf you believe this is incorrect, please contact someone on chat.sponsor.ajay.app, discord.gg/SponsorBlock or matrix.to/#/#sponsor:ajay.app`
|
||||
@@ -309,11 +297,11 @@ async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, user
|
||||
}
|
||||
|
||||
// Check for POI segments before some seconds
|
||||
if (!(isVIP || isTempVIP) && segments[i].actionType === ActionType.Poi && startTime < config.poiMinimumStartTime) {
|
||||
if (!isVIP && segments[i].actionType === ActionType.Poi && startTime < config.poiMinimumStartTime) {
|
||||
return { pass: false, errorMessage: `POI cannot be that early`, errorCode: 400 };
|
||||
}
|
||||
|
||||
if (!(isVIP || isTempVIP) && segments[i].category === "sponsor"
|
||||
if (!isVIP && segments[i].category === "sponsor"
|
||||
&& segments[i].actionType !== ActionType.Full && (endTime - startTime) < 1) {
|
||||
// Too short
|
||||
return { pass: false, errorMessage: "Segments must be longer than 1 second long", errorCode: 400 };
|
||||
@@ -321,7 +309,7 @@ async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, user
|
||||
|
||||
//check if this info has already been submitted before
|
||||
const duplicateCheck2Row = await db.prepare("get", `SELECT "UUID" FROM "sponsorTimes" WHERE "startTime" = ?
|
||||
and "endTime" = ? and "category" = ? and "actionType" = ? and "description" = ? and "videoID" = ? and "service" = ?`, [startTime, endTime, segments[i].category, segments[i].actionType, segments[i].description, videoID, service]);
|
||||
and "endTime" = ? and "category" = ? and "actionType" = ? and "videoID" = ? and "service" = ?`, [startTime, endTime, segments[i].category, segments[i].actionType, videoID, service]);
|
||||
if (duplicateCheck2Row) {
|
||||
if (segments[i].actionType === ActionType.Full) {
|
||||
// Forward as vote
|
||||
@@ -337,24 +325,29 @@ async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, user
|
||||
return CHECK_PASS;
|
||||
}
|
||||
|
||||
async function checkByAutoModerator(videoID: VideoID, userID: HashedUserID, segments: IncomingSegment[], service: Service, apiVideoDetails: videoDetails, videoDuration: number): Promise<CheckResult> {
|
||||
async function checkByAutoModerator(videoID: any, userID: any, segments: Array<any>, service:string, apiVideoInfo: APIVideoInfo, videoDuration: number): Promise<CheckResult> {
|
||||
// Auto moderator check
|
||||
if (service == Service.YouTube) {
|
||||
const autoModerateResult = await autoModerateSubmission(apiVideoDetails, { videoID, userID, segments, service, videoDuration });
|
||||
const autoModerateResult = await autoModerateSubmission(apiVideoInfo, { userID, videoID, segments, service, videoDuration });
|
||||
if (autoModerateResult) {
|
||||
return {
|
||||
pass: false,
|
||||
errorCode: 403,
|
||||
errorMessage: `Submissions rejected: ${autoModerateResult} If this is an issue, send a message on Discord.`
|
||||
errorMessage: `Request rejected by auto moderator: ${autoModerateResult} If this is an issue, send a message on Discord.`
|
||||
};
|
||||
}
|
||||
}
|
||||
return CHECK_PASS;
|
||||
}
|
||||
|
||||
async function updateDataIfVideoDurationChange(videoID: VideoID, service: Service, videoDuration: VideoDuration, videoDurationParam: VideoDuration) {
|
||||
async function updateDataIfVideoDurationChange(videoID: VideoID, service: Service, videoDuration: VideoDuration, videoDurationParam: VideoDuration, logData: any) {
|
||||
let lockedCategoryList = await db.prepare("all", 'SELECT category, "actionType", reason from "lockCategories" where "videoID" = ? AND "service" = ?', [videoID, service]);
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`got locked categories: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
const previousSubmissions = await db.prepare("all",
|
||||
`SELECT "videoDuration", "UUID"
|
||||
FROM "sponsorTimes"
|
||||
@@ -365,22 +358,31 @@ async function updateDataIfVideoDurationChange(videoID: VideoID, service: Servic
|
||||
[videoID, service]
|
||||
) as {videoDuration: VideoDuration, UUID: SegmentUUID}[];
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`got previous submissions: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
// If the video's duration is changed, then the video should be unlocked and old submissions should be hidden
|
||||
const videoDurationChanged = (videoDuration: number) => videoDuration != 0
|
||||
&& previousSubmissions.length > 0 && !previousSubmissions.some((e) => Math.abs(videoDuration - e.videoDuration) < 2);
|
||||
|
||||
let apiVideoDetails: videoDetails = null;
|
||||
let apiVideoInfo: APIVideoInfo = null;
|
||||
if (service == Service.YouTube) {
|
||||
// Don't use cache if we don't know the video duration, or the client claims that it has changed
|
||||
const ignoreCache = !videoDurationParam || previousSubmissions.length === 0 || videoDurationChanged(videoDurationParam);
|
||||
apiVideoDetails = await getVideoDetails(videoID, ignoreCache);
|
||||
apiVideoInfo = await getYouTubeVideoInfo(videoID, !videoDurationParam || previousSubmissions.length === 0 || videoDurationChanged(videoDurationParam));
|
||||
}
|
||||
const apiVideoDuration = apiVideoDetails?.duration as VideoDuration;
|
||||
const apiVideoDuration = apiVideoInfo?.data?.lengthSeconds as VideoDuration;
|
||||
if (!videoDurationParam || (apiVideoDuration && Math.abs(videoDurationParam - apiVideoDuration) > 2)) {
|
||||
// If api duration is far off, take that one instead (it is only precise to seconds, not millis)
|
||||
videoDuration = apiVideoDuration || 0 as VideoDuration;
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`got api response: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
// Only treat as difference if both the api duration and submitted duration have changed
|
||||
if (videoDurationChanged(videoDuration) && (!videoDurationParam || videoDurationChanged(videoDurationParam))) {
|
||||
// Hide all previous submissions
|
||||
@@ -388,12 +390,17 @@ async function updateDataIfVideoDurationChange(videoID: VideoID, service: Servic
|
||||
await db.prepare("run", `UPDATE "sponsorTimes" SET "hidden" = 1 WHERE "UUID" = ?`, [submission.UUID]);
|
||||
}
|
||||
lockedCategoryList = [];
|
||||
deleteLockCategories(videoID, null, null, service).catch((e) => Logger.error(`deleting lock categories: ${e}`));
|
||||
deleteLockCategories(videoID, null, null, service);
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`updated old submissions: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
return {
|
||||
videoDuration,
|
||||
apiVideoDetails,
|
||||
apiVideoInfo,
|
||||
lockedCategoryList
|
||||
};
|
||||
}
|
||||
@@ -488,47 +495,85 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
|
||||
proxySubmission(req);
|
||||
}
|
||||
|
||||
const logData = {
|
||||
extraLogging: req.query.extraLogging,
|
||||
startTime: Date.now(),
|
||||
lastTime: Date.now()
|
||||
};
|
||||
|
||||
// eslint-disable-next-line prefer-const
|
||||
let { videoID, userID: paramUserID, service, videoDuration, videoDurationParam, segments, userAgent } = preprocessInput(req);
|
||||
|
||||
//hash the userID
|
||||
if (!paramUserID) {
|
||||
return res.status(400).send("No userID provided");
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`preprocess: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
const userID: HashedUserID = await getHashCache(paramUserID);
|
||||
|
||||
const invalidCheckResult = await checkInvalidFields(videoID, paramUserID, userID, segments, videoDurationParam, userAgent, service);
|
||||
const invalidCheckResult = checkInvalidFields(videoID, paramUserID, segments);
|
||||
if (!invalidCheckResult.pass) {
|
||||
return res.status(invalidCheckResult.errorCode).send(invalidCheckResult.errorMessage);
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`invalid fields: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
//hash the userID
|
||||
const userID = await getHashCache(paramUserID);
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`userid: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
const userWarningCheckResult = await checkUserActiveWarning(userID);
|
||||
if (!userWarningCheckResult.pass) {
|
||||
Logger.warn(`Caught a submission for a warned user. userID: '${userID}', videoID: '${videoID}', category: '${segments.reduce<string>((prev, val) => `${prev} ${val.category}`, "")}', times: ${segments.reduce<string>((prev, val) => `${prev} ${val.segment}`, "")}`);
|
||||
return res.status(userWarningCheckResult.errorCode).send(userWarningCheckResult.errorMessage);
|
||||
}
|
||||
|
||||
const isVIP = (await isUserVIP(userID));
|
||||
const isTempVIP = (await isUserTempVIP(userID, videoID));
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`warning done: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
const isVIP = await isUserVIP(userID);
|
||||
const isTempVIP = await isUserTempVIP(userID, videoID);
|
||||
const rawIP = getIP(req);
|
||||
|
||||
const newData = await updateDataIfVideoDurationChange(videoID, service, videoDuration, videoDurationParam);
|
||||
const newData = await updateDataIfVideoDurationChange(videoID, service, videoDuration, videoDurationParam, logData);
|
||||
videoDuration = newData.videoDuration;
|
||||
const { lockedCategoryList, apiVideoDetails } = newData;
|
||||
const { lockedCategoryList, apiVideoInfo } = newData;
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`duration change done: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
// Check if all submissions are correct
|
||||
const segmentCheckResult = await checkEachSegmentValid(rawIP, paramUserID, userID, videoID, segments, service, isVIP, isTempVIP, lockedCategoryList);
|
||||
const segmentCheckResult = await checkEachSegmentValid(rawIP, paramUserID, userID, videoID, segments, service, isVIP, lockedCategoryList);
|
||||
if (!segmentCheckResult.pass) {
|
||||
return res.status(segmentCheckResult.errorCode).send(segmentCheckResult.errorMessage);
|
||||
}
|
||||
|
||||
if (!(isVIP || isTempVIP)) {
|
||||
const autoModerateCheckResult = await checkByAutoModerator(videoID, userID, segments, service, apiVideoDetails, videoDurationParam);
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`valid segmenrs done: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
if (!isVIP && !isTempVIP) {
|
||||
const autoModerateCheckResult = await checkByAutoModerator(videoID, userID, segments, service, apiVideoInfo, videoDurationParam);
|
||||
if (!autoModerateCheckResult.pass) {
|
||||
return res.status(autoModerateCheckResult.errorCode).send(autoModerateCheckResult.errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Checks done: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
// Will be filled when submitting
|
||||
const UUIDs = [];
|
||||
const newSegments = [];
|
||||
@@ -536,6 +581,11 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
|
||||
//hash the ip 5000 times so no one can get it from the database
|
||||
const hashedIP = await getHashCache(rawIP + config.globalSalt);
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`IP hash done: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
try {
|
||||
//get current time
|
||||
const timeSubmitted = Date.now();
|
||||
@@ -546,49 +596,65 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
|
||||
// }
|
||||
|
||||
//check to see if this user is shadowbanned
|
||||
const userBanCount = (await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ? LIMIT 1`, [userID]))?.userCount;
|
||||
const ipBanCount = (await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedIPs" WHERE "hashedIP" = ? LIMIT 1`, [hashedIP]))?.userCount;
|
||||
const shadowBanCount = userBanCount || ipBanCount;
|
||||
const shadowBanRow = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ? LIMIT 1`, [userID]);
|
||||
const startingVotes = 0;
|
||||
const reputation = await getReputation(userID);
|
||||
|
||||
if (!userBanCount && ipBanCount) {
|
||||
// Make sure the whole user is banned
|
||||
banUser(userID, true, true, 1, config.categoryList as Category[])
|
||||
.catch((e) => Logger.error(`Error banning user after submitting from a banned IP: ${e}`));
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Ban check complete: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
for (const segmentInfo of segments) {
|
||||
// Full segments are always rejected since there can only be one, so shadow hide wouldn't work
|
||||
if (segmentInfo.ignoreSegment
|
||||
|| (shadowBanCount && segmentInfo.actionType === ActionType.Full)) {
|
||||
|| (shadowBanRow.userCount && segmentInfo.actionType === ActionType.Full)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
//this can just be a hash of the data
|
||||
//it's better than generating an actual UUID like what was used before
|
||||
//also better for duplication checking
|
||||
const UUID = getSubmissionUUID(videoID, segmentInfo.category, segmentInfo.actionType,
|
||||
segmentInfo.description, userID, parseFloat(segmentInfo.segment[0]), parseFloat(segmentInfo.segment[1]), service);
|
||||
const UUID = getSubmissionUUID(videoID, segmentInfo.category, segmentInfo.actionType, userID, parseFloat(segmentInfo.segment[0]), parseFloat(segmentInfo.segment[1]), service);
|
||||
const hashedVideoID = getHash(videoID, 1);
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Submission prep done: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
const startingLocked = isVIP ? 1 : 0;
|
||||
try {
|
||||
await db.prepare("run", `INSERT INTO "sponsorTimes"
|
||||
("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "category", "actionType", "service", "videoDuration", "reputation", "shadowHidden", "hashedVideoID", "userAgent", "description")
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
||||
videoID, segmentInfo.segment[0], segmentInfo.segment[1], startingVotes, startingLocked, UUID, userID, timeSubmitted, 0
|
||||
, segmentInfo.category, segmentInfo.actionType, service, videoDuration, reputation, shadowBanCount, hashedVideoID, userAgent, segmentInfo.description
|
||||
, segmentInfo.category, segmentInfo.actionType, service, videoDuration, reputation, shadowBanRow.userCount, hashedVideoID, userAgent, segmentInfo.description
|
||||
],
|
||||
);
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Normal DB done: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
//add to private db as well
|
||||
await privateDB.prepare("run", `INSERT INTO "sponsorTimes" VALUES(?, ?, ?, ?)`, [videoID, hashedIP, timeSubmitted, service]);
|
||||
|
||||
await db.prepare("run", `INSERT INTO "videoInfo" ("videoID", "channelID", "title", "published")
|
||||
SELECT ?, ?, ?, ?
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Private db: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
await db.prepare("run", `INSERT INTO "videoInfo" ("videoID", "channelID", "title", "published", "genreUrl")
|
||||
SELECT ?, ?, ?, ?, ?
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "videoInfo" WHERE "videoID" = ?)`, [
|
||||
videoID, apiVideoDetails?.authorId || "", apiVideoDetails?.title || "", apiVideoDetails?.published || 0, videoID]);
|
||||
videoID, apiVideoInfo?.data?.authorId || "", apiVideoInfo?.data?.title || "", apiVideoInfo?.data?.published || 0, apiVideoInfo?.data?.genreUrl || "", videoID]);
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Video info: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
// Clear redis cache for this video
|
||||
QueryCacher.clearSegmentCache({
|
||||
@@ -615,8 +681,13 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Sending webhooks: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
sendWebhooks(apiVideoDetails, userID, videoID, UUIDs[i], segments[i], service).catch((e) => Logger.error(`call send webhooks ${e}`));
|
||||
sendWebhooks(apiVideoInfo, userID, videoID, UUIDs[i], segments[i], service);
|
||||
}
|
||||
return res.json(newSegments);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import { isUserVIP } from "../utils/isUserVIP";
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
import { HashedUserID, UserID } from "../types/user.model";
|
||||
import { config } from "../config";
|
||||
import { generateWarningDiscord, warningData, dispatchEvent } from "../utils/webhookUtils";
|
||||
|
||||
type warningEntry = {
|
||||
userID: HashedUserID,
|
||||
@@ -22,18 +21,18 @@ function checkExpiredWarning(warning: warningEntry): boolean {
|
||||
return warning.issueTime > expiry && !warning.enabled;
|
||||
}
|
||||
|
||||
const getUsername = (userID: HashedUserID) => db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID], { useReplica: true });
|
||||
|
||||
export async function postWarning(req: Request, res: Response): Promise<Response> {
|
||||
if (!req.body.userID) return res.status(400).json({ "message": "Missing parameters" });
|
||||
|
||||
const issuerUserID: HashedUserID = req.body.issuerUserID ? await getHashCache(req.body.issuerUserID as UserID) : null;
|
||||
const userID: HashedUserID = issuerUserID ? req.body.userID : await getHashCache(req.body.userID as UserID);
|
||||
// exit early if no body passed in
|
||||
if (!req.body.userID && !req.body.issuerUserID) return res.status(400).json({ "message": "Missing parameters" });
|
||||
// Collect user input data
|
||||
const issuerUserID: HashedUserID = await getHashCache(<UserID> req.body.issuerUserID);
|
||||
const userID: UserID = req.body.userID;
|
||||
const issueTime = new Date().getTime();
|
||||
const enabled: boolean = req.body.enabled ?? true;
|
||||
const reason: string = req.body.reason ?? "";
|
||||
|
||||
if ((!issuerUserID && enabled) || (issuerUserID && !await isUserVIP(issuerUserID))) {
|
||||
// Ensure user is a VIP
|
||||
if (!await isUserVIP(issuerUserID)) {
|
||||
Logger.warn(`Permission violation: User ${issuerUserID} attempted to warn user ${userID}.`);
|
||||
return res.status(403).json({ "message": "Not a VIP" });
|
||||
}
|
||||
@@ -53,8 +52,8 @@ export async function postWarning(req: Request, res: Response): Promise<Response
|
||||
// check if warning is still within issue time and warning is not enabled
|
||||
} else if (checkExpiredWarning(previousWarning) ) {
|
||||
await db.prepare(
|
||||
"run", 'UPDATE "warnings" SET "enabled" = 1, "reason" = ? WHERE "userID" = ? AND "issueTime" = ?',
|
||||
[reason, userID, previousWarning.issueTime]
|
||||
"run", 'UPDATE "warnings" SET "enabled" = 1 WHERE "userID" = ? AND "issueTime" = ?',
|
||||
[userID, previousWarning.issueTime]
|
||||
);
|
||||
resultStatus = "re-enabled";
|
||||
} else {
|
||||
@@ -65,27 +64,6 @@ export async function postWarning(req: Request, res: Response): Promise<Response
|
||||
resultStatus = "removed from";
|
||||
}
|
||||
|
||||
const targetUsername = await getUsername(userID) ?? null;
|
||||
const issuerUsername = await getUsername(issuerUserID) ?? null;
|
||||
const webhookData = {
|
||||
target: {
|
||||
userID,
|
||||
username: targetUsername
|
||||
},
|
||||
issuer: {
|
||||
userID: issuerUserID,
|
||||
username: issuerUsername
|
||||
},
|
||||
reason
|
||||
} as warningData;
|
||||
|
||||
try {
|
||||
const warning = generateWarningDiscord(webhookData);
|
||||
dispatchEvent("warning", warning);
|
||||
} catch /* istanbul ignore next */ (err) {
|
||||
Logger.error(`Error sending warning to Discord ${err}`);
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
message: `Warning ${resultStatus} user '${userID}'.`,
|
||||
});
|
||||
|
||||
91
src/routes/ratings/getRating.ts
Normal file
91
src/routes/ratings/getRating.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { Request, Response } from "express";
|
||||
import { db } from "../../databases/databases";
|
||||
import { RatingType } from "../../types/ratings.model";
|
||||
import { Service, VideoID, VideoIDHash } from "../../types/segments.model";
|
||||
import { getService } from "../../utils/getService";
|
||||
import { hashPrefixTester } from "../../utils/hashPrefixTester";
|
||||
import { Logger } from "../../utils/logger";
|
||||
import { QueryCacher } from "../../utils/queryCacher";
|
||||
import { ratingHashKey } from "../../utils/redisKeys";
|
||||
|
||||
interface DBRating {
|
||||
videoID: VideoID,
|
||||
hashedVideoID: VideoIDHash,
|
||||
service: Service,
|
||||
type: RatingType,
|
||||
count: number
|
||||
}
|
||||
|
||||
export async function getRating(req: Request, res: Response): Promise<Response> {
|
||||
let hashPrefixes: VideoIDHash[] = [];
|
||||
try {
|
||||
hashPrefixes = req.query.hashPrefixes
|
||||
? JSON.parse(req.query.hashPrefixes as string)
|
||||
: Array.isArray(req.query.prefix)
|
||||
? req.query.prefix
|
||||
: [req.query.prefix ?? req.params.prefix];
|
||||
if (!Array.isArray(hashPrefixes)) {
|
||||
return res.status(400).send("hashPrefixes parameter does not match format requirements.");
|
||||
}
|
||||
|
||||
hashPrefixes.map((hashPrefix) => hashPrefix?.toLowerCase());
|
||||
} catch(error) {
|
||||
return res.status(400).send("Bad parameter: hashPrefixes (invalid JSON)");
|
||||
}
|
||||
if (hashPrefixes.length === 0 || hashPrefixes.length > 75
|
||||
|| hashPrefixes.some((hashPrefix) => !hashPrefix || !hashPrefixTester(hashPrefix))) {
|
||||
return res.status(400).send("Hash prefix does not match format requirements."); // Exit early on faulty prefix
|
||||
}
|
||||
|
||||
let types: RatingType[] = [];
|
||||
try {
|
||||
types = req.query.types
|
||||
? JSON.parse(req.query.types as string)
|
||||
: req.query.type
|
||||
? Array.isArray(req.query.type)
|
||||
? req.query.type
|
||||
: [req.query.type]
|
||||
: [RatingType.Upvote, RatingType.Downvote];
|
||||
if (!Array.isArray(types)) {
|
||||
return res.status(400).send("Types parameter does not match format requirements.");
|
||||
}
|
||||
|
||||
types = types.map((type) => parseInt(type as unknown as string, 10));
|
||||
} catch(error) {
|
||||
return res.status(400).send("Bad parameter: types (invalid JSON)");
|
||||
}
|
||||
|
||||
const service: Service = getService(req.query.service, req.body.service);
|
||||
|
||||
try {
|
||||
const ratings = (await getRatings(hashPrefixes, service))
|
||||
.filter((rating) => types.includes(rating.type))
|
||||
.map((rating) => ({
|
||||
videoID: rating.videoID,
|
||||
hash: rating.hashedVideoID,
|
||||
service: rating.service,
|
||||
type: rating.type,
|
||||
count: rating.count
|
||||
}));
|
||||
|
||||
return res.status((ratings.length) ? 200 : 404)
|
||||
.send(ratings ?? []);
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
|
||||
function getRatings(hashPrefixes: VideoIDHash[], service: Service): Promise<DBRating[]> {
|
||||
const fetchFromDB = (hashPrefixes: VideoIDHash[]) => db
|
||||
.prepare(
|
||||
"all",
|
||||
`SELECT "videoID", "hashedVideoID", "type", "count" FROM "ratings" WHERE "hashedVideoID" ~* ? AND "service" = ? ORDER BY "hashedVideoID"`,
|
||||
[`^(?:${hashPrefixes.join("|")})`, service]
|
||||
) as Promise<DBRating[]>;
|
||||
|
||||
return (hashPrefixes.every((hashPrefix) => hashPrefix.length === 4))
|
||||
? QueryCacher.getAndSplit(fetchFromDB, (prefix) => ratingHashKey(prefix, service), "hashedVideoID", hashPrefixes)
|
||||
: fetchFromDB(hashPrefixes);
|
||||
}
|
||||
53
src/routes/ratings/postClearCache.ts
Normal file
53
src/routes/ratings/postClearCache.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { Logger } from "../../utils/logger";
|
||||
import { HashedUserID, UserID } from "../../types/user.model";
|
||||
import { getHash } from "../../utils/getHash";
|
||||
import { getHashCache } from "../../utils/getHashCache";
|
||||
import { Request, Response } from "express";
|
||||
import { Service, VideoID } from "../../types/segments.model";
|
||||
import { QueryCacher } from "../../utils/queryCacher";
|
||||
import { isUserVIP } from "../../utils/isUserVIP";
|
||||
import { VideoIDHash } from "../../types/segments.model";
|
||||
import { getService } from "../..//utils/getService";
|
||||
|
||||
export async function postClearCache(req: Request, res: Response): Promise<Response> {
|
||||
const videoID = req.query.videoID as VideoID;
|
||||
const userID = req.query.userID as UserID;
|
||||
const service = getService(req.query.service as Service);
|
||||
|
||||
const invalidFields = [];
|
||||
if (typeof videoID !== "string") {
|
||||
invalidFields.push("videoID");
|
||||
}
|
||||
if (typeof userID !== "string") {
|
||||
invalidFields.push("userID");
|
||||
}
|
||||
|
||||
if (invalidFields.length !== 0) {
|
||||
// invalid request
|
||||
const fields = invalidFields.reduce((p, c, i) => p + (i !== 0 ? ", " : "") + c, "");
|
||||
return res.status(400).send(`No valid ${fields} field(s) provided`);
|
||||
}
|
||||
|
||||
// hash the userID as early as possible
|
||||
const hashedUserID: HashedUserID = await getHashCache(userID);
|
||||
// hash videoID
|
||||
const hashedVideoID: VideoIDHash = getHash(videoID, 1);
|
||||
|
||||
// Ensure user is a VIP
|
||||
if (!(await isUserVIP(hashedUserID))){
|
||||
Logger.warn(`Permission violation: User ${hashedUserID} attempted to clear cache for video ${videoID}.`);
|
||||
return res.status(403).json({ "message": "Not a VIP" });
|
||||
}
|
||||
|
||||
try {
|
||||
QueryCacher.clearRatingCache({
|
||||
hashedVideoID,
|
||||
service
|
||||
});
|
||||
return res.status(200).json({
|
||||
message: `Cache cleared on video ${videoID}`
|
||||
});
|
||||
} catch(err) {
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
65
src/routes/ratings/postRating.ts
Normal file
65
src/routes/ratings/postRating.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { db, privateDB } from "../../databases/databases";
|
||||
import { getHash } from "../../utils/getHash";
|
||||
import { getHashCache } from "../../utils/getHashCache";
|
||||
import { Logger } from "../../utils/logger";
|
||||
import { Request, Response } from "express";
|
||||
import { HashedUserID, UserID } from "../../types/user.model";
|
||||
import { HashedIP, IPAddress, VideoID } from "../../types/segments.model";
|
||||
import { getIP } from "../../utils/getIP";
|
||||
import { getService } from "../../utils/getService";
|
||||
import { RatingType, RatingTypes } from "../../types/ratings.model";
|
||||
import { config } from "../../config";
|
||||
import { QueryCacher } from "../../utils/queryCacher";
|
||||
|
||||
export async function postRating(req: Request, res: Response): Promise<Response> {
|
||||
const privateUserID = req.body.userID as UserID;
|
||||
const videoID = req.body.videoID as VideoID;
|
||||
const service = getService(req.query.service, req.body.service);
|
||||
const type = req.body.type as RatingType;
|
||||
const enabled = req.body.enabled ?? true;
|
||||
|
||||
if (privateUserID == undefined || videoID == undefined || service == undefined || type == undefined
|
||||
|| (typeof privateUserID !== "string") || (typeof videoID !== "string") || (typeof service !== "string")
|
||||
|| (typeof type !== "number") || (enabled && (typeof enabled !== "boolean")) || !RatingTypes.includes(type)) {
|
||||
//invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
const hashedIP: HashedIP = getHash(getIP(req) + config.globalSalt as IPAddress, 1);
|
||||
const hashedUserID: HashedUserID = await getHashCache(privateUserID);
|
||||
const hashedVideoID = getHash(videoID, 1);
|
||||
|
||||
try {
|
||||
// Check if this user has voted before
|
||||
const existingVote = await privateDB.prepare("get", `SELECT count(*) as "count" FROM "ratings" WHERE "videoID" = ? AND "service" = ? AND "type" = ? AND "userID" = ?`, [videoID, service, type, hashedUserID]);
|
||||
if (existingVote.count > 0 && !enabled) {
|
||||
// Undo the vote
|
||||
await privateDB.prepare("run", `DELETE FROM "ratings" WHERE "videoID" = ? AND "service" = ? AND "type" = ? AND "userID" = ?`, [videoID, service, type, hashedUserID]);
|
||||
await db.prepare("run", `UPDATE "ratings" SET "count" = "count" - 1 WHERE "videoID" = ? AND "service" = ? AND type = ?`, [videoID, service, type]);
|
||||
} else if (existingVote.count === 0 && enabled) {
|
||||
// Make sure there hasn't been another vote from this IP
|
||||
const existingIPVote = (await privateDB.prepare("get", `SELECT count(*) as "count" FROM "ratings" WHERE "videoID" = ? AND "service" = ? AND "type" = ? AND "hashedIP" = ?`, [videoID, service, type, hashedIP]))
|
||||
.count > 0;
|
||||
if (existingIPVote) { // if exisiting vote, exit early instead
|
||||
return res.sendStatus(200);
|
||||
}
|
||||
|
||||
// Create entry in privateDB
|
||||
await privateDB.prepare("run", `INSERT INTO "ratings" ("videoID", "service", "type", "userID", "timeSubmitted", "hashedIP") VALUES (?, ?, ?, ?, ?, ?)`, [videoID, service, type, hashedUserID, Date.now(), hashedIP]);
|
||||
|
||||
// Check if general rating already exists, if so increase it
|
||||
const rating = await db.prepare("get", `SELECT count(*) as "count" FROM "ratings" WHERE "videoID" = ? AND "service" = ? AND type = ?`, [videoID, service, type]);
|
||||
if (rating.count > 0) {
|
||||
await db.prepare("run", `UPDATE "ratings" SET "count" = "count" + 1 WHERE "videoID" = ? AND "service" = ? AND type = ?`, [videoID, service, type]);
|
||||
} else {
|
||||
await db.prepare("run", `INSERT INTO "ratings" ("videoID", "service", "type", "count", "hashedVideoID") VALUES (?, ?, ?, 1, ?)`, [videoID, service, type, hashedVideoID]);
|
||||
}
|
||||
}
|
||||
// clear rating cache
|
||||
QueryCacher.clearRatingCache({ hashedVideoID, service });
|
||||
return res.sendStatus(200);
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
@@ -32,11 +32,6 @@ export async function setUsername(req: Request, res: Response): Promise<Response
|
||||
// eslint-disable-next-line no-control-regex
|
||||
userName = userName.replace(/[\u0000-\u001F\u007F-\u009F]/g, "");
|
||||
|
||||
// check privateID against publicID
|
||||
if (!await checkPrivateUsername(userName, userID)) {
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
if (adminUserIDInput != undefined) {
|
||||
//this is the admin controlling the other users account, don't hash the controling account's ID
|
||||
adminUserIDInput = await getHashCache(adminUserIDInput);
|
||||
@@ -61,7 +56,7 @@ export async function setUsername(req: Request, res: Response): Promise<Response
|
||||
return res.sendStatus(200);
|
||||
}
|
||||
}
|
||||
catch (error) /* istanbul ignore next */ {
|
||||
catch (error) {
|
||||
Logger.error(error as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
@@ -88,17 +83,8 @@ export async function setUsername(req: Request, res: Response): Promise<Response
|
||||
await logUserNameChange(userID, userName, oldUserName, adminUserIDInput !== undefined);
|
||||
|
||||
return res.sendStatus(200);
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
|
||||
async function checkPrivateUsername(username: string, userID: string): Promise<boolean> {
|
||||
if (username == userID) return false;
|
||||
if (username.length <= config.minUserIDLength) return true; // don't check for cross matches <= 30 characters
|
||||
const userNameHash = await getHashCache(username);
|
||||
const userNameRow = await db.prepare("get", `SELECT "userID" FROM "userNames" WHERE "userID" = ? LIMIT 1`, [userNameHash]);
|
||||
if (userNameRow?.userID) return false;
|
||||
return true;
|
||||
}
|
||||
@@ -1,36 +1,28 @@
|
||||
import { db, privateDB } from "../databases/databases";
|
||||
import { db } from "../databases/databases";
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
import { Request, Response } from "express";
|
||||
import { config } from "../config";
|
||||
import { Category, HashedIP, Service, VideoID, VideoIDHash } from "../types/segments.model";
|
||||
import { Category, Service, VideoID, VideoIDHash } from "../types/segments.model";
|
||||
import { UserID } from "../types/user.model";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import { isUserVIP } from "../utils/isUserVIP";
|
||||
import { parseCategories } from "../utils/parseParams";
|
||||
|
||||
export async function shadowBanUser(req: Request, res: Response): Promise<Response> {
|
||||
const userID = req.query.userID as UserID;
|
||||
const hashedIP = req.query.hashedIP as HashedIP;
|
||||
const hashedIP = req.query.hashedIP as string;
|
||||
const adminUserIDInput = req.query.adminUserID as UserID;
|
||||
const type = Number.parseInt(req.query.type as string ?? "1");
|
||||
if (isNaN(type)) {
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
const enabled = req.query.enabled === undefined
|
||||
? true
|
||||
: req.query.enabled === "true";
|
||||
const lookForIPs = req.query.lookForIPs === "true";
|
||||
const banUsers = req.query.banUsers === undefined
|
||||
? true
|
||||
: req.query.banUsers === "true";
|
||||
|
||||
//if enabled is false and the old submissions should be made visible again
|
||||
const unHideOldSubmissions = req.query.unHideOldSubmissions !== "false";
|
||||
|
||||
const categories: Category[] = parseCategories(req, config.categoryList as Category[]);
|
||||
const categories: string[] = req.query.categories ? JSON.parse(req.query.categories as string) : config.categoryList;
|
||||
categories.filter((category) => typeof category === "string" && !(/[^a-z|_|-]/.test(category)));
|
||||
|
||||
if (adminUserIDInput == undefined || (userID == undefined && hashedIP == undefined || type <= 0)) {
|
||||
if (adminUserIDInput == undefined || (userID == undefined && hashedIP == undefined)) {
|
||||
//invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
@@ -45,111 +37,88 @@ export async function shadowBanUser(req: Request, res: Response): Promise<Respon
|
||||
}
|
||||
|
||||
if (userID) {
|
||||
const result = await banUser(userID, enabled, unHideOldSubmissions, type, categories);
|
||||
//check to see if this user is already shadowbanned
|
||||
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
|
||||
|
||||
if (enabled && lookForIPs) {
|
||||
const ipLoggingFixedTime = 1675295716000;
|
||||
const timeSubmitted = (await db.prepare("all", `SELECT "timeSubmitted" FROM "sponsorTimes" WHERE "timeSubmitted" > ? AND "userID" = ?`, [ipLoggingFixedTime, userID])) as { timeSubmitted: number }[];
|
||||
const ips = (await Promise.all(timeSubmitted.map((s) => {
|
||||
return privateDB.prepare("all", `SELECT "hashedIP" FROM "sponsorTimes" WHERE "timeSubmitted" = ?`, [s.timeSubmitted]) as Promise<{ hashedIP: HashedIP }[]>;
|
||||
}))).flat();
|
||||
if (enabled && row.userCount == 0) {
|
||||
//add them to the shadow ban list
|
||||
|
||||
await Promise.all([...new Set(ips.map((ip) => ip.hashedIP))].map((ip) => {
|
||||
return banIP(ip, enabled, unHideOldSubmissions, type, categories, true);
|
||||
}));
|
||||
}
|
||||
//add it to the table
|
||||
await db.prepare("run", `INSERT INTO "shadowBannedUsers" VALUES(?)`, [userID]);
|
||||
|
||||
if (result) {
|
||||
res.sendStatus(result);
|
||||
return;
|
||||
//find all previous submissions and hide them
|
||||
if (unHideOldSubmissions) {
|
||||
await unHideSubmissions(categories, userID);
|
||||
}
|
||||
} else if (!enabled && row.userCount > 0) {
|
||||
//remove them from the shadow ban list
|
||||
await db.prepare("run", `DELETE FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
|
||||
|
||||
//find all previous submissions and unhide them
|
||||
if (unHideOldSubmissions) {
|
||||
const segmentsToIgnore = (await db.prepare("all", `SELECT "UUID" FROM "sponsorTimes" st
|
||||
JOIN "lockCategories" ns on "st"."videoID" = "ns"."videoID" AND st.category = ns.category AND "st"."service" = "ns"."service" WHERE "st"."userID" = ?`
|
||||
, [userID])).map((item: {UUID: string}) => item.UUID);
|
||||
const allSegments = (await db.prepare("all", `SELECT "UUID" FROM "sponsorTimes" st WHERE "st"."userID" = ?`, [userID]))
|
||||
.map((item: {UUID: string}) => item.UUID);
|
||||
|
||||
await Promise.all(allSegments.filter((item: {uuid: string}) => {
|
||||
return segmentsToIgnore.indexOf(item) === -1;
|
||||
}).map(async (UUID: string) => {
|
||||
// collect list for unshadowbanning
|
||||
(await db.prepare("all", `SELECT "videoID", "hashedVideoID", "service", "votes", "views", "userID" FROM "sponsorTimes" WHERE "UUID" = ? AND "shadowHidden" = 1 AND "category" in (${categories.map((c) => `'${c}'`).join(",")})`, [UUID]))
|
||||
.forEach((videoInfo: {category: Category, videoID: VideoID, hashedVideoID: VideoIDHash, service: Service, userID: UserID}) => {
|
||||
QueryCacher.clearSegmentCache(videoInfo);
|
||||
}
|
||||
);
|
||||
|
||||
return db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = 0 WHERE "UUID" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})`, [UUID]);
|
||||
}));
|
||||
}
|
||||
// already shadowbanned
|
||||
} else if (enabled && row.userCount > 0) {
|
||||
// apply unHideOldSubmissions if applicable
|
||||
if (unHideOldSubmissions) {
|
||||
await unHideSubmissions(categories, userID);
|
||||
return res.sendStatus(200);
|
||||
}
|
||||
|
||||
// otherwise ban already exists, send 409
|
||||
return res.sendStatus(409);
|
||||
}
|
||||
} else if (hashedIP) {
|
||||
const result = await banIP(hashedIP, enabled, unHideOldSubmissions, type, categories, banUsers);
|
||||
if (result) {
|
||||
res.sendStatus(result);
|
||||
return;
|
||||
}
|
||||
//check to see if this user is already shadowbanned
|
||||
// let row = await privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedIPs WHERE hashedIP = ?", [hashedIP]);
|
||||
|
||||
// if (enabled && row.userCount == 0) {
|
||||
if (enabled) {
|
||||
//add them to the shadow ban list
|
||||
|
||||
//add it to the table
|
||||
// await privateDB.prepare('run', "INSERT INTO shadowBannedIPs VALUES(?)", [hashedIP]);
|
||||
|
||||
|
||||
//find all previous submissions and hide them
|
||||
if (unHideOldSubmissions) {
|
||||
await db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = 1 WHERE "timeSubmitted" IN
|
||||
(SELECT "privateDB"."timeSubmitted" FROM "sponsorTimes" LEFT JOIN "privateDB"."sponsorTimes" as "privateDB" ON "sponsorTimes"."timeSubmitted"="privateDB"."timeSubmitted"
|
||||
WHERE "privateDB"."hashedIP" = ?)`, [hashedIP]);
|
||||
}
|
||||
} /*else if (!enabled && row.userCount > 0) {
|
||||
// //remove them from the shadow ban list
|
||||
// await db.prepare('run', "DELETE FROM shadowBannedUsers WHERE userID = ?", [userID]);
|
||||
|
||||
// //find all previous submissions and unhide them
|
||||
// if (unHideOldSubmissions) {
|
||||
// await db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 0 WHERE userID = ?", [userID]);
|
||||
// }
|
||||
}*/
|
||||
}
|
||||
return res.sendStatus(200);
|
||||
}
|
||||
|
||||
export async function banUser(userID: UserID, enabled: boolean, unHideOldSubmissions: boolean, type: number, categories: Category[]): Promise<number> {
|
||||
//check to see if this user is already shadowbanned
|
||||
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
|
||||
|
||||
if (enabled && row.userCount == 0) {
|
||||
//add them to the shadow ban list
|
||||
|
||||
//add it to the table
|
||||
await db.prepare("run", `INSERT INTO "shadowBannedUsers" VALUES(?)`, [userID]);
|
||||
|
||||
//find all previous submissions and hide them
|
||||
if (unHideOldSubmissions) {
|
||||
await unHideSubmissionsByUser(categories, userID, type);
|
||||
}
|
||||
} else if (enabled && row.userCount > 0) {
|
||||
// apply unHideOldSubmissions if applicable
|
||||
if (unHideOldSubmissions) {
|
||||
await unHideSubmissionsByUser(categories, userID, type);
|
||||
} else {
|
||||
// otherwise ban already exists, send 409
|
||||
return 409;
|
||||
}
|
||||
} else if (!enabled && row.userCount > 0) {
|
||||
//find all previous submissions and unhide them
|
||||
if (unHideOldSubmissions) {
|
||||
await unHideSubmissionsByUser(categories, userID, 0);
|
||||
}
|
||||
|
||||
//remove them from the shadow ban list
|
||||
await db.prepare("run", `DELETE FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
|
||||
} else if (row.userCount == 0) { // already shadowbanned
|
||||
// already not shadowbanned
|
||||
return 400;
|
||||
}
|
||||
|
||||
return 200;
|
||||
}
|
||||
|
||||
export async function banIP(hashedIP: HashedIP, enabled: boolean, unHideOldSubmissions: boolean, type: number, categories: Category[], banUsers: boolean): Promise<number> {
|
||||
//check to see if this user is already shadowbanned
|
||||
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedIPs" WHERE "hashedIP" = ?`, [hashedIP]);
|
||||
|
||||
if (enabled) {
|
||||
if (row.userCount == 0) {
|
||||
await db.prepare("run", `INSERT INTO "shadowBannedIPs" VALUES(?)`, [hashedIP]);
|
||||
}
|
||||
|
||||
//find all previous submissions and hide them
|
||||
if (unHideOldSubmissions) {
|
||||
const users = await unHideSubmissionsByIP(categories, hashedIP, type);
|
||||
|
||||
if (banUsers) {
|
||||
await Promise.all([...users].map((user) => {
|
||||
return banUser(user, enabled, unHideOldSubmissions, type, categories);
|
||||
}));
|
||||
}
|
||||
} else if (row.userCount > 0) {
|
||||
// Nothing to do, and already added
|
||||
return 409;
|
||||
}
|
||||
} else if (!enabled) {
|
||||
if (row.userCount > 0) {
|
||||
//remove them from the shadow ban list
|
||||
await db.prepare("run", `DELETE FROM "shadowBannedIPs" WHERE "hashedIP" = ?`, [hashedIP]);
|
||||
}
|
||||
|
||||
//find all previous submissions and unhide them
|
||||
if (unHideOldSubmissions) {
|
||||
await unHideSubmissionsByIP(categories, hashedIP, 0);
|
||||
}
|
||||
}
|
||||
|
||||
return 200;
|
||||
}
|
||||
|
||||
async function unHideSubmissionsByUser(categories: string[], userID: UserID, type = 1) {
|
||||
await db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = '${type}' WHERE "userID" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})
|
||||
async function unHideSubmissions(categories: string[], userID: UserID) {
|
||||
await db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = 1 WHERE "userID" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})
|
||||
AND NOT EXISTS ( SELECT "videoID", "category" FROM "lockCategories" WHERE
|
||||
"sponsorTimes"."videoID" = "lockCategories"."videoID" AND "sponsorTimes"."service" = "lockCategories"."service" AND "sponsorTimes"."category" = "lockCategories"."category")`, [userID]);
|
||||
|
||||
@@ -159,23 +128,3 @@ async function unHideSubmissionsByUser(categories: string[], userID: UserID, typ
|
||||
QueryCacher.clearSegmentCache(videoInfo);
|
||||
});
|
||||
}
|
||||
|
||||
async function unHideSubmissionsByIP(categories: string[], hashedIP: HashedIP, type = 1): Promise<Set<UserID>> {
|
||||
const submissions = await privateDB.prepare("all", `SELECT "timeSubmitted" FROM "sponsorTimes" WHERE "hashedIP" = ?`, [hashedIP]) as { timeSubmitted: number }[];
|
||||
|
||||
const users: Set<UserID> = new Set();
|
||||
await Promise.all(submissions.map(async (submission) => {
|
||||
(await db.prepare("all", `SELECT "videoID", "hashedVideoID", "service", "votes", "views", "userID" FROM "sponsorTimes" WHERE "timeSubmitted" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})`, [submission.timeSubmitted]))
|
||||
.forEach((videoInfo: { category: Category, videoID: VideoID, hashedVideoID: VideoIDHash, service: Service, userID: UserID }) => {
|
||||
QueryCacher.clearSegmentCache(videoInfo);
|
||||
users.add(videoInfo.userID);
|
||||
}
|
||||
);
|
||||
|
||||
await db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = ${type} WHERE "timeSubmitted" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})
|
||||
AND NOT EXISTS ( SELECT "videoID", "category" FROM "lockCategories" WHERE
|
||||
"sponsorTimes"."videoID" = "lockCategories"."videoID" AND "sponsorTimes"."service" = "lockCategories"."service" AND "sponsorTimes"."category" = "lockCategories"."category")`, [submission.timeSubmitted]);
|
||||
}));
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import axios from "axios";
|
||||
import { Request, Response } from "express";
|
||||
import { config } from "../config";
|
||||
import { privateDB } from "../databases/databases";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { getPatreonIdentity, PatronStatus, refreshToken, TokenType } from "../utils/tokenUtils";
|
||||
|
||||
interface VerifyTokenRequest extends Request {
|
||||
query: {
|
||||
licenseKey: string;
|
||||
}
|
||||
}
|
||||
|
||||
export const validateLicenseKeyRegex = (token: string) =>
|
||||
new RegExp(/[A-Za-z0-9]{40}|[A-Za-z0-9-]{35}/).test(token);
|
||||
|
||||
export async function verifyTokenRequest(req: VerifyTokenRequest, res: Response): Promise<Response> {
|
||||
const { query: { licenseKey } } = req;
|
||||
|
||||
if (!licenseKey) {
|
||||
return res.status(400).send("Invalid request");
|
||||
} else if (!validateLicenseKeyRegex(licenseKey)) {
|
||||
// fast check for invalid licence key
|
||||
return res.status(200).send({
|
||||
allowed: false
|
||||
});
|
||||
}
|
||||
|
||||
const tokens = (await privateDB.prepare("get", `SELECT "accessToken", "refreshToken", "expiresIn" from "oauthLicenseKeys" WHERE "licenseKey" = ?`
|
||||
, [licenseKey])) as {accessToken: string, refreshToken: string, expiresIn: number};
|
||||
if (tokens) {
|
||||
const identity = await getPatreonIdentity(tokens.accessToken);
|
||||
|
||||
if (tokens.expiresIn < 15 * 24 * 60 * 60) {
|
||||
refreshToken(TokenType.patreon, licenseKey, tokens.refreshToken).catch((e) => Logger.error(`refresh token: ${e}`));
|
||||
}
|
||||
|
||||
/* istanbul ignore else */
|
||||
if (identity) {
|
||||
const membership = identity.included?.[0]?.attributes;
|
||||
const allowed = !!membership && ((membership.patron_status === PatronStatus.active && membership.currently_entitled_amount_cents > 0)
|
||||
|| (membership.patron_status === PatronStatus.former && membership.campaign_lifetime_support_cents > 300));
|
||||
|
||||
return res.status(200).send({
|
||||
allowed
|
||||
});
|
||||
} else {
|
||||
return res.status(500);
|
||||
}
|
||||
} else {
|
||||
// Check Local
|
||||
const result = await privateDB.prepare("get", `SELECT "licenseKey" from "licenseKeys" WHERE "licenseKey" = ?`, [licenseKey]);
|
||||
if (result) {
|
||||
return res.status(200).send({
|
||||
allowed: true
|
||||
});
|
||||
} else {
|
||||
// Gumroad
|
||||
return res.status(200).send({
|
||||
allowed: await checkAllGumroadProducts(licenseKey)
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
async function checkAllGumroadProducts(licenseKey: string): Promise<boolean> {
|
||||
for (const link of config.gumroad.productPermalinks) {
|
||||
try {
|
||||
const result = await axios.post("https://api.gumroad.com/v2/licenses/verify", null, {
|
||||
params: { product_permalink: link, license_key: licenseKey }
|
||||
});
|
||||
|
||||
const allowed = result.status === 200 && result.data?.success;
|
||||
if (allowed) return allowed;
|
||||
} catch (e) /* istanbul ignore next */ {
|
||||
Logger.error(`Gumroad fetch for ${link} failed: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -2,9 +2,9 @@ import { db } from "../databases/databases";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export async function viewedVideoSponsorTime(req: Request, res: Response): Promise<Response> {
|
||||
const UUID = req.query?.UUID;
|
||||
const UUID = req.query.UUID;
|
||||
|
||||
if (!UUID) {
|
||||
if (UUID == undefined) {
|
||||
//invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Logger } from "../utils/logger";
|
||||
import { isUserVIP } from "../utils/isUserVIP";
|
||||
import { isUserTempVIP } from "../utils/isUserTempVIP";
|
||||
import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi";
|
||||
import { APIVideoInfo } from "../types/youtubeApi.model";
|
||||
import { db, privateDB } from "../databases/databases";
|
||||
import { dispatchEvent, getVoteAuthor, getVoteAuthorRaw } from "../utils/webhookUtils";
|
||||
import { getFormattedTime } from "../utils/getFormattedTime";
|
||||
@@ -10,11 +11,9 @@ import { getIP } from "../utils/getIP";
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
import { config } from "../config";
|
||||
import { UserID } from "../types/user.model";
|
||||
import { DBSegment, Category, HashedIP, IPAddress, SegmentUUID, Service, VideoID, VideoIDHash, VideoDuration, ActionType, VoteType } from "../types/segments.model";
|
||||
import { DBSegment, Category, HashedIP, IPAddress, SegmentUUID, Service, VideoID, VideoIDHash, VideoDuration, ActionType } from "../types/segments.model";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import axios from "axios";
|
||||
import { getVideoDetails, videoDetails } from "../utils/getVideoDetails";
|
||||
import { deleteLockCategories } from "./deleteLockCategories";
|
||||
|
||||
const voteTypes = {
|
||||
normal: 0,
|
||||
@@ -37,7 +36,6 @@ interface FinalResponse {
|
||||
interface VoteData {
|
||||
UUID: string;
|
||||
nonAnonUserID: string;
|
||||
originalType: VoteType;
|
||||
voteTypeEnum: number;
|
||||
isTempVIP: boolean;
|
||||
isVIP: boolean;
|
||||
@@ -53,16 +51,20 @@ interface VoteData {
|
||||
finalResponse: FinalResponse;
|
||||
}
|
||||
|
||||
function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise<APIVideoInfo> {
|
||||
return config.newLeafURLs ? YouTubeAPI.listVideos(videoID, ignoreCache) : null;
|
||||
}
|
||||
|
||||
const videoDurationChanged = (segmentDuration: number, APIDuration: number) => (APIDuration > 0 && Math.abs(segmentDuration - APIDuration) > 2);
|
||||
|
||||
async function updateSegmentVideoDuration(UUID: SegmentUUID) {
|
||||
const { videoDuration, videoID, service } = await db.prepare("get", `select "videoDuration", "videoID", "service" from "sponsorTimes" where "UUID" = ?`, [UUID]);
|
||||
let apiVideoDetails: videoDetails = null;
|
||||
let apiVideoInfo: APIVideoInfo = null;
|
||||
if (service == Service.YouTube) {
|
||||
// don't use cache since we have no information about the video length
|
||||
apiVideoDetails = await getVideoDetails(videoID, true);
|
||||
apiVideoInfo = await getYouTubeVideoInfo(videoID);
|
||||
}
|
||||
const apiVideoDuration = apiVideoDetails?.duration as VideoDuration;
|
||||
const apiVideoDuration = apiVideoInfo?.data?.lengthSeconds as VideoDuration;
|
||||
if (videoDurationChanged(videoDuration, apiVideoDuration)) {
|
||||
Logger.info(`Video duration changed for ${videoID} from ${videoDuration} to ${apiVideoDuration}`);
|
||||
await db.prepare("run", `UPDATE "sponsorTimes" SET "videoDuration" = ? WHERE "UUID" = ?`, [apiVideoDuration, UUID]);
|
||||
@@ -71,12 +73,12 @@ async function updateSegmentVideoDuration(UUID: SegmentUUID) {
|
||||
|
||||
async function checkVideoDuration(UUID: SegmentUUID) {
|
||||
const { videoID, service } = await db.prepare("get", `select "videoID", "service" from "sponsorTimes" where "UUID" = ?`, [UUID]);
|
||||
let apiVideoDetails: videoDetails = null;
|
||||
let apiVideoInfo: APIVideoInfo = null;
|
||||
if (service == Service.YouTube) {
|
||||
// don't use cache since we have no information about the video length
|
||||
apiVideoDetails = await getVideoDetails(videoID, true);
|
||||
apiVideoInfo = await getYouTubeVideoInfo(videoID, true);
|
||||
}
|
||||
const apiVideoDuration = apiVideoDetails?.duration as VideoDuration;
|
||||
const apiVideoDuration = apiVideoInfo?.data?.lengthSeconds as VideoDuration;
|
||||
// if no videoDuration return early
|
||||
if (isNaN(apiVideoDuration)) return;
|
||||
// fetch latest submission
|
||||
@@ -96,11 +98,11 @@ async function checkVideoDuration(UUID: SegmentUUID) {
|
||||
AND "hidden" = 0 AND "shadowHidden" = 0 AND
|
||||
"actionType" != 'full' AND "votes" > -2`,
|
||||
[videoID, service, latestSubmission.timeSubmitted]);
|
||||
deleteLockCategories(videoID, null, null, service).catch((e) => Logger.error(`delete lock categories after vote: ${e}`));
|
||||
}
|
||||
}
|
||||
|
||||
async function sendWebhooks(voteData: VoteData) {
|
||||
Logger.error(`about to send webhook ${JSON.stringify(voteData)}`);
|
||||
const submissionInfoRow = await db.prepare("get", `SELECT "s"."videoID", "s"."userID", s."startTime", s."endTime", s."category", u."userName",
|
||||
(select count(1) from "sponsorTimes" where "userID" = s."userID") count,
|
||||
(select count(1) from "sponsorTimes" where "userID" = s."userID" and votes <= -2) disregarded
|
||||
@@ -109,11 +111,11 @@ async function sendWebhooks(voteData: VoteData) {
|
||||
|
||||
const userSubmissionCountRow = await db.prepare("get", `SELECT count(*) as "submissionCount" FROM "sponsorTimes" WHERE "userID" = ?`, [voteData.nonAnonUserID]);
|
||||
|
||||
Logger.error(`Sending webhook ${config.discordReportChannelWebhookURL}, ${submissionInfoRow}, ${userSubmissionCountRow}`)
|
||||
|
||||
if (submissionInfoRow !== undefined && userSubmissionCountRow != undefined) {
|
||||
let webhookURL: string = null;
|
||||
if (voteData.originalType === VoteType.Malicious) {
|
||||
webhookURL = config.discordMaliciousReportWebhookURL;
|
||||
} else if (voteData.voteTypeEnum === voteTypes.normal) {
|
||||
if (voteData.voteTypeEnum === voteTypes.normal) {
|
||||
switch (voteData.finalResponse.webhookType) {
|
||||
case VoteWebhookType.Normal:
|
||||
webhookURL = config.discordReportChannelWebhookURL;
|
||||
@@ -127,8 +129,7 @@ async function sendWebhooks(voteData: VoteData) {
|
||||
}
|
||||
|
||||
if (config.newLeafURLs !== null) {
|
||||
const videoID = submissionInfoRow.videoID;
|
||||
const { err, data } = await YouTubeAPI.listVideos(videoID);
|
||||
const { err, data } = await YouTubeAPI.listVideos(submissionInfoRow.videoID);
|
||||
if (err) return;
|
||||
|
||||
const isUpvote = voteData.incrementAmount > 0;
|
||||
@@ -140,8 +141,8 @@ async function sendWebhooks(voteData: VoteData) {
|
||||
"video": {
|
||||
"id": submissionInfoRow.videoID,
|
||||
"title": data?.title,
|
||||
"url": `https://www.youtube.com/watch?v=${videoID}`,
|
||||
"thumbnail": getMaxResThumbnail(videoID),
|
||||
"url": `https://www.youtube.com/watch?v=${submissionInfoRow.videoID}`,
|
||||
"thumbnail": getMaxResThumbnail(data) || null,
|
||||
},
|
||||
"submission": {
|
||||
"UUID": voteData.UUID,
|
||||
@@ -186,7 +187,7 @@ async function sendWebhooks(voteData: VoteData) {
|
||||
`${getVoteAuthor(userSubmissionCountRow.submissionCount, voteData.isTempVIP, voteData.isVIP, voteData.isOwnSubmission)}${voteData.row.locked ? " (Locked)" : ""}`,
|
||||
},
|
||||
"thumbnail": {
|
||||
"url": getMaxResThumbnail(videoID),
|
||||
"url": getMaxResThumbnail(data) || "",
|
||||
},
|
||||
}],
|
||||
})
|
||||
@@ -210,7 +211,7 @@ async function sendWebhooks(voteData: VoteData) {
|
||||
async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, isTempVIP: boolean, isOwnSubmission: boolean, category: Category
|
||||
, hashedIP: HashedIP, finalResponse: FinalResponse): Promise<{ status: number, message?: string }> {
|
||||
// Check if they've already made a vote
|
||||
const usersLastVoteInfo = await privateDB.prepare("get", `select count(*) as votes, category from "categoryVotes" where "UUID" = ? and "userID" = ? group by category`, [UUID, userID], { useReplica: true });
|
||||
const usersLastVoteInfo = await privateDB.prepare("get", `select count(*) as votes, category from "categoryVotes" where "UUID" = ? and "userID" = ? group by category`, [UUID, userID]);
|
||||
|
||||
if (usersLastVoteInfo?.category === category) {
|
||||
// Double vote, ignore
|
||||
@@ -218,17 +219,20 @@ async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, i
|
||||
}
|
||||
|
||||
const segmentInfo = (await db.prepare("get", `SELECT "category", "actionType", "videoID", "hashedVideoID", "service", "userID", "locked" FROM "sponsorTimes" WHERE "UUID" = ?`,
|
||||
[UUID], { useReplica: true })) as {category: Category, actionType: ActionType, videoID: VideoID, hashedVideoID: VideoIDHash, service: Service, userID: UserID, locked: number};
|
||||
[UUID])) as {category: Category, actionType: ActionType, videoID: VideoID, hashedVideoID: VideoIDHash, service: Service, userID: UserID, locked: number};
|
||||
|
||||
if (!config.categorySupport[category]?.includes(segmentInfo.actionType) || segmentInfo.actionType === ActionType.Full) {
|
||||
return { status: 400, message: `Not allowed to change to ${category} when for segment of type ${segmentInfo.actionType}` };
|
||||
if (segmentInfo.actionType === ActionType.Full) {
|
||||
return { status: 400, message: "Not allowed to change category of a full video segment" };
|
||||
}
|
||||
if (segmentInfo.actionType === ActionType.Poi || category === "poi_highlight") {
|
||||
return { status: 400, message: "Not allowed to change category for single point segments" };
|
||||
}
|
||||
if (!config.categoryList.includes(category)) {
|
||||
return { status: 400, message: "Category doesn't exist." };
|
||||
}
|
||||
|
||||
// Ignore vote if the next category is locked
|
||||
const nextCategoryLocked = await db.prepare("get", `SELECT "videoID", "category" FROM "lockCategories" WHERE "videoID" = ? AND "service" = ? AND "category" = ?`, [segmentInfo.videoID, segmentInfo.service, category], { useReplica: true });
|
||||
const nextCategoryLocked = await db.prepare("get", `SELECT "videoID", "category" FROM "lockCategories" WHERE "videoID" = ? AND "service" = ? AND "category" = ?`, [segmentInfo.videoID, segmentInfo.service, category]);
|
||||
if (nextCategoryLocked && !isVIP) {
|
||||
return { status: 200 };
|
||||
}
|
||||
@@ -238,13 +242,12 @@ async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, i
|
||||
return { status: 200 };
|
||||
}
|
||||
|
||||
const nextCategoryInfo = await db.prepare("get", `select votes from "categoryVotes" where "UUID" = ? and category = ?`, [UUID, category], { useReplica: true });
|
||||
const nextCategoryInfo = await db.prepare("get", `select votes from "categoryVotes" where "UUID" = ? and category = ?`, [UUID, category]);
|
||||
|
||||
const timeSubmitted = Date.now();
|
||||
|
||||
const voteAmount = (isVIP || isTempVIP) ? 500 : 1;
|
||||
const ableToVote = finalResponse.finalStatus === 200
|
||||
&& (await db.prepare("get", `SELECT "userID" FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID], { useReplica: true })) === undefined;
|
||||
const ableToVote = isVIP || isTempVIP || finalResponse.finalStatus === 200 || true;
|
||||
|
||||
if (ableToVote) {
|
||||
// Add the vote
|
||||
@@ -267,15 +270,15 @@ async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, i
|
||||
}
|
||||
|
||||
// See if the submissions category is ready to change
|
||||
const currentCategoryInfo = await db.prepare("get", `select votes from "categoryVotes" where "UUID" = ? and category = ?`, [UUID, segmentInfo.category], { useReplica: true });
|
||||
const currentCategoryInfo = await db.prepare("get", `select votes from "categoryVotes" where "UUID" = ? and category = ?`, [UUID, segmentInfo.category]);
|
||||
|
||||
const submissionInfo = await db.prepare("get", `SELECT "userID", "timeSubmitted", "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID], { useReplica: true });
|
||||
const submissionInfo = await db.prepare("get", `SELECT "userID", "timeSubmitted", "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
|
||||
const isSubmissionVIP = submissionInfo && await isUserVIP(submissionInfo.userID);
|
||||
const startingVotes = isSubmissionVIP ? 10000 : 1;
|
||||
|
||||
// Change this value from 1 in the future to make it harder to change categories
|
||||
// Done this way without ORs incase the value is zero
|
||||
const currentCategoryCount = currentCategoryInfo?.votes ?? startingVotes;
|
||||
const currentCategoryCount = (currentCategoryInfo === undefined || currentCategoryInfo === null) ? startingVotes : currentCategoryInfo.votes;
|
||||
|
||||
// Add submission as vote
|
||||
if (!currentCategoryInfo && submissionInfo) {
|
||||
@@ -287,7 +290,7 @@ async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, i
|
||||
|
||||
//TODO: In the future, raise this number from zero to make it harder to change categories
|
||||
// VIPs change it every time
|
||||
if (isVIP || isTempVIP || isOwnSubmission || nextCategoryCount - currentCategoryCount >= Math.max(Math.ceil(submissionInfo?.votes / 2), 2)) {
|
||||
if (nextCategoryCount - currentCategoryCount >= Math.max(Math.ceil(submissionInfo?.votes / 2), 2) || isVIP || isTempVIP || isOwnSubmission) {
|
||||
// Replace the category
|
||||
await db.prepare("run", `update "sponsorTimes" set "category" = ? where "UUID" = ?`, [category, UUID]);
|
||||
}
|
||||
@@ -307,7 +310,18 @@ export async function voteOnSponsorTime(req: Request, res: Response): Promise<Re
|
||||
const category = req.query.category as Category;
|
||||
const ip = getIP(req);
|
||||
|
||||
const result = await vote(ip, UUID, paramUserID, type, category);
|
||||
const logData = {
|
||||
extraLogging: req.query.extraLogging,
|
||||
startTime: Date.now(),
|
||||
lastTime: Date.now()
|
||||
};
|
||||
|
||||
const result = await vote(ip, UUID, paramUserID, type, category, logData);
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Done vote: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
const response = res.status(result.status);
|
||||
if (result.message) {
|
||||
@@ -319,18 +333,16 @@ export async function voteOnSponsorTime(req: Request, res: Response): Promise<Re
|
||||
}
|
||||
}
|
||||
|
||||
export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID, type: number, category?: Category): Promise<{ status: number, message?: string, json?: unknown }> {
|
||||
export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID, type: number, category?: Category, logData = {} as any): Promise<{ status: number, message?: string, json?: unknown }> {
|
||||
// missing key parameters
|
||||
if (!UUID || !paramUserID || !(type !== undefined || category)) {
|
||||
return { status: 400 };
|
||||
}
|
||||
// Ignore this vote, invalid
|
||||
if (paramUserID.length < config.minUserIDLength) {
|
||||
if (paramUserID.length < 30 && config.mode !== "test") {
|
||||
return { status: 200 };
|
||||
}
|
||||
|
||||
const originalType = type;
|
||||
|
||||
//hash the userID
|
||||
const nonAnonUserID = await getHashCache(paramUserID);
|
||||
const userID = await getHashCache(paramUserID + UUID);
|
||||
@@ -353,6 +365,11 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
|
||||
return { status: 404 };
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Got segment info: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
const isTempVIP = await isUserTempVIP(nonAnonUserID, segmentInfo.videoID);
|
||||
const isVIP = await isUserVIP(nonAnonUserID);
|
||||
|
||||
@@ -364,19 +381,6 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
|
||||
return { status: 400 };
|
||||
}
|
||||
|
||||
const MILLISECONDS_IN_HOUR = 3600000;
|
||||
const now = Date.now();
|
||||
const warnings = (await db.prepare("all", `SELECT "reason" FROM warnings WHERE "userID" = ? AND "issueTime" > ? AND enabled = 1`,
|
||||
[nonAnonUserID, Math.floor(now - (config.hoursAfterWarningExpires * MILLISECONDS_IN_HOUR))],
|
||||
));
|
||||
|
||||
if (warnings.length >= config.maxNumberOfActiveWarnings) {
|
||||
const warningReason = warnings[0]?.reason;
|
||||
return { status: 403, message: "Vote rejected due to a warning from a moderator. This means that we noticed you were making some common mistakes that are not malicious, and we just want to clarify the rules. " +
|
||||
"Could you please send a message in Discord or Matrix so we can further help you?" +
|
||||
`${(warningReason.length > 0 ? ` Warning reason: '${warningReason}'` : "")}` };
|
||||
}
|
||||
|
||||
// no type but has category, categoryVote
|
||||
if (!type && category) {
|
||||
return categoryVote(UUID, nonAnonUserID, isVIP, isTempVIP, isOwnSubmission, category, hashedIP, finalResponse);
|
||||
@@ -387,7 +391,7 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
|
||||
const isSegmentLocked = segmentInfo.locked;
|
||||
const isVideoLocked = async () => !!(await db.prepare("get", `SELECT "category" FROM "lockCategories" WHERE
|
||||
"videoID" = ? AND "service" = ? AND "category" = ? AND "actionType" = ?`,
|
||||
[segmentInfo.videoID, segmentInfo.service, segmentInfo.category, segmentInfo.actionType], { useReplica: true }));
|
||||
[segmentInfo.videoID, segmentInfo.service, segmentInfo.category, segmentInfo.actionType]));
|
||||
if (isSegmentLocked || await isVideoLocked()) {
|
||||
finalResponse.blockVote = true;
|
||||
finalResponse.webhookType = VoteWebhookType.Rejected;
|
||||
@@ -406,30 +410,53 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
|
||||
}
|
||||
}
|
||||
|
||||
const MILLISECONDS_IN_HOUR = 3600000;
|
||||
const now = Date.now();
|
||||
const warnings = (await db.prepare("all", `SELECT "reason" FROM warnings WHERE "userID" = ? AND "issueTime" > ? AND enabled = 1`,
|
||||
[nonAnonUserID, Math.floor(now - (config.hoursAfterWarningExpires * MILLISECONDS_IN_HOUR))],
|
||||
));
|
||||
|
||||
if (warnings.length >= config.maxNumberOfActiveWarnings) {
|
||||
const warningReason = warnings[0]?.reason;
|
||||
return { status: 403, message: "Vote rejected due to a warning from a moderator. This means that we noticed you were making some common mistakes that are not malicious, and we just want to clarify the rules. " +
|
||||
"Could you please send a message in Discord or Matrix so we can further help you?" +
|
||||
`${(warningReason.length > 0 ? ` Warning reason: '${warningReason}'` : "")}` };
|
||||
}
|
||||
|
||||
const voteTypeEnum = (type == 0 || type == 1 || type == 20) ? voteTypes.normal : voteTypes.incorrect;
|
||||
|
||||
// no restrictions on checkDuration
|
||||
// check duration of all submissions on this video
|
||||
if (type <= 0) {
|
||||
checkVideoDuration(UUID).catch((e) => Logger.error(`checkVideoDuration: ${e}`));
|
||||
checkVideoDuration(UUID);
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Main prep done: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
try {
|
||||
// check if vote has already happened
|
||||
const votesRow = await privateDB.prepare("get", `SELECT "type" FROM "votes" WHERE "userID" = ? AND "UUID" = ?`, [userID, UUID], { useReplica: true });
|
||||
const votesRow = await privateDB.prepare("get", `SELECT "type" FROM "votes" WHERE "userID" = ? AND "UUID" = ?`, [userID, UUID]);
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Got previous vote info: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
// -1 for downvote, 1 for upvote. Maybe more depending on reputation in the future
|
||||
// oldIncrementAmount will be zero if row is null
|
||||
let incrementAmount = 0;
|
||||
let oldIncrementAmount = 0;
|
||||
|
||||
if (type == VoteType.Upvote) {
|
||||
if (type == 1) {
|
||||
//upvote
|
||||
incrementAmount = 1;
|
||||
} else if (type === VoteType.Downvote || type === VoteType.Malicious) {
|
||||
} else if (type == 0) {
|
||||
//downvote
|
||||
incrementAmount = -1;
|
||||
} else if (type == VoteType.Undo) {
|
||||
} else if (type == 20) {
|
||||
//undo/cancel vote
|
||||
incrementAmount = 0;
|
||||
} else {
|
||||
@@ -437,13 +464,17 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
|
||||
return { status: 400 };
|
||||
}
|
||||
if (votesRow) {
|
||||
if (votesRow.type === VoteType.Upvote) {
|
||||
if (votesRow.type === 1) {
|
||||
//upvote
|
||||
oldIncrementAmount = 1;
|
||||
} else if (votesRow.type === VoteType.Downvote) {
|
||||
} else if (votesRow.type === 0) {
|
||||
//downvote
|
||||
oldIncrementAmount = -1;
|
||||
} else if (votesRow.type === VoteType.ExtraDownvote) {
|
||||
} else if (votesRow.type === 2) {
|
||||
//extra downvote
|
||||
oldIncrementAmount = -4;
|
||||
} else if (votesRow.type === VoteType.Undo) {
|
||||
} else if (votesRow.type === 20) {
|
||||
//undo/cancel vote
|
||||
oldIncrementAmount = 0;
|
||||
} else if (votesRow.type < 0) {
|
||||
//vip downvote
|
||||
@@ -464,29 +495,28 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
|
||||
type = incrementAmount;
|
||||
}
|
||||
|
||||
if (type === VoteType.Malicious) {
|
||||
incrementAmount = -Math.min(segmentInfo.votes + 2 - oldIncrementAmount, 5);
|
||||
type = incrementAmount;
|
||||
}
|
||||
|
||||
// Only change the database if they have made a submission before and haven't voted recently
|
||||
const userAbleToVote = (!(isOwnSubmission && incrementAmount > 0 && oldIncrementAmount >= 0)
|
||||
&& !(originalType === VoteType.Malicious && segmentInfo.actionType !== ActionType.Chapter)
|
||||
&& !finalResponse.blockVote
|
||||
&& finalResponse.finalStatus === 200
|
||||
&& (await db.prepare("get", `SELECT "userID" FROM "sponsorTimes" WHERE "userID" = ?`, [nonAnonUserID], { useReplica: true })) !== undefined
|
||||
&& (await db.prepare("get", `SELECT "userID" FROM "shadowBannedUsers" WHERE "userID" = ?`, [nonAnonUserID], { useReplica: true })) === undefined
|
||||
&& (await privateDB.prepare("get", `SELECT "UUID" FROM "votes" WHERE "UUID" = ? AND "hashedIP" = ? AND "userID" != ?`, [UUID, hashedIP, userID], { useReplica: true })) === undefined);
|
||||
&& (await db.prepare("get", `SELECT "userID" FROM "sponsorTimes" WHERE "userID" = ?`, [nonAnonUserID])) !== undefined
|
||||
&& (await db.prepare("get", `SELECT "userID" FROM "shadowBannedUsers" WHERE "userID" = ?`, [nonAnonUserID])) === undefined
|
||||
&& (await privateDB.prepare("get", `SELECT "UUID" FROM "votes" WHERE "UUID" = ? AND "hashedIP" = ? AND "userID" != ?`, [UUID, hashedIP, userID])) === undefined);
|
||||
|
||||
|
||||
const ableToVote = isVIP || isTempVIP || userAbleToVote;
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`About to run vote code ${ableToVote}: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
if (ableToVote) {
|
||||
//update the votes table
|
||||
if (votesRow) {
|
||||
await privateDB.prepare("run", `UPDATE "votes" SET "type" = ?, "originalType" = ? WHERE "userID" = ? AND "UUID" = ?`, [type, originalType, userID, UUID]);
|
||||
await privateDB.prepare("run", `UPDATE "votes" SET "type" = ? WHERE "userID" = ? AND "UUID" = ?`, [type, userID, UUID]);
|
||||
} else {
|
||||
await privateDB.prepare("run", `INSERT INTO "votes" ("UUID", "userID", "hashedIP", "type", "normalUserID", "originalType") VALUES(?, ?, ?, ?, ?, ?)`, [UUID, userID, hashedIP, type, nonAnonUserID, originalType]);
|
||||
await privateDB.prepare("run", `INSERT INTO "votes" VALUES(?, ?, ?, ?, ?)`, [UUID, userID, hashedIP, type, nonAnonUserID]);
|
||||
}
|
||||
|
||||
// update the vote count on this sponsorTime
|
||||
@@ -508,13 +538,23 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
|
||||
await db.prepare("run", 'UPDATE "sponsorTimes" SET "locked" = 0 WHERE "UUID" = ?', [UUID]);
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Did vote stuff: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
QueryCacher.clearSegmentCache(segmentInfo);
|
||||
}
|
||||
|
||||
if (logData.extraLogging) {
|
||||
Logger.error(`Ready to send webhook ${incrementAmount - oldIncrementAmount !== 0}: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
|
||||
logData.lastTime = Date.now();
|
||||
}
|
||||
|
||||
if (incrementAmount - oldIncrementAmount !== 0) {
|
||||
sendWebhooks({
|
||||
UUID,
|
||||
nonAnonUserID,
|
||||
originalType,
|
||||
voteTypeEnum,
|
||||
isTempVIP,
|
||||
isVIP,
|
||||
@@ -524,7 +564,7 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
|
||||
incrementAmount,
|
||||
oldIncrementAmount,
|
||||
finalResponse
|
||||
}).catch((e) => Logger.error(`Sending vote webhook: ${e}`));
|
||||
});
|
||||
}
|
||||
return { status: finalResponse.finalStatus, message: finalResponse.finalMessage ?? undefined };
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { Service, VideoID, VideoIDHash } from "./segments.model";
|
||||
import { UserID } from "./user.model";
|
||||
|
||||
export type BrandingUUID = string & { readonly __brandingUUID: unique symbol };
|
||||
|
||||
export interface BrandingDBSubmission {
|
||||
shadowHidden: number,
|
||||
UUID: BrandingUUID,
|
||||
videoID: VideoID,
|
||||
hashedVideoID: VideoIDHash
|
||||
}
|
||||
|
||||
export interface TitleDBResult extends BrandingDBSubmission {
|
||||
title: string,
|
||||
original: number,
|
||||
votes: number,
|
||||
locked: number
|
||||
}
|
||||
|
||||
export interface TitleResult {
|
||||
title: string,
|
||||
original: boolean,
|
||||
votes: number,
|
||||
locked: boolean,
|
||||
UUID: BrandingUUID
|
||||
}
|
||||
|
||||
export interface ThumbnailDBResult extends BrandingDBSubmission {
|
||||
timestamp?: number,
|
||||
original: number,
|
||||
votes: number,
|
||||
locked: number
|
||||
}
|
||||
|
||||
export interface ThumbnailResult {
|
||||
timestamp?: number,
|
||||
original: boolean,
|
||||
votes: number,
|
||||
locked: boolean,
|
||||
UUID: BrandingUUID
|
||||
}
|
||||
|
||||
export interface BrandingResult {
|
||||
titles: TitleResult[],
|
||||
thumbnails: ThumbnailResult[]
|
||||
}
|
||||
|
||||
export interface BrandingHashDBResult {
|
||||
titles: TitleDBResult[],
|
||||
thumbnails: ThumbnailDBResult[]
|
||||
}
|
||||
|
||||
export interface OriginalThumbnailSubmission {
|
||||
original: true;
|
||||
}
|
||||
|
||||
export interface TimeThumbnailSubmission {
|
||||
timestamp: number;
|
||||
original: false;
|
||||
}
|
||||
|
||||
export type ThumbnailSubmission = OriginalThumbnailSubmission | TimeThumbnailSubmission;
|
||||
|
||||
export interface TitleSubmission {
|
||||
title: string;
|
||||
original: boolean;
|
||||
}
|
||||
|
||||
export interface BrandingSubmission {
|
||||
title: TitleSubmission;
|
||||
thumbnail: ThumbnailSubmission;
|
||||
videoID: VideoID;
|
||||
userID: UserID;
|
||||
service: Service;
|
||||
}
|
||||
@@ -3,36 +3,10 @@ import * as redis from "redis";
|
||||
|
||||
interface RedisConfig extends redis.RedisClientOptions {
|
||||
enabled: boolean;
|
||||
expiryTime: number;
|
||||
getTimeout: number;
|
||||
maxConnections: number;
|
||||
maxWriteConnections: number;
|
||||
stopWritingAfterResponseTime: number;
|
||||
responseTimePause: number;
|
||||
disableHashCache: boolean;
|
||||
}
|
||||
|
||||
interface RedisReadOnlyConfig extends redis.RedisClientOptions {
|
||||
interface CustomPostgresConfig extends PoolConfig {
|
||||
enabled: boolean;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
export interface CustomPostgresConfig extends PoolConfig {
|
||||
enabled: boolean;
|
||||
maxTries: number;
|
||||
}
|
||||
|
||||
export interface CustomWritePostgresConfig extends CustomPostgresConfig {
|
||||
maxActiveRequests: number;
|
||||
timeout: number;
|
||||
highLoadThreshold: number;
|
||||
}
|
||||
|
||||
export interface CustomPostgresReadOnlyConfig extends CustomPostgresConfig {
|
||||
weight: number;
|
||||
readTimeout: number;
|
||||
fallbackOnFail: boolean;
|
||||
stopRetryThreshold: number;
|
||||
}
|
||||
|
||||
export interface SBSConfig {
|
||||
@@ -46,13 +20,9 @@ export interface SBSConfig {
|
||||
discordFailedReportChannelWebhookURL?: string;
|
||||
discordFirstTimeSubmissionsWebhookURL?: string;
|
||||
discordCompletelyIncorrectReportWebhookURL?: string;
|
||||
discordMaliciousReportWebhookURL?: string;
|
||||
neuralBlockURL?: string;
|
||||
discordNeuralBlockRejectWebhookURL?: string;
|
||||
minReputationToSubmitChapter: number;
|
||||
minReputationToSubmitFiller: number;
|
||||
userCounterURL?: string;
|
||||
userCounterRatio: number;
|
||||
proxySubmission?: string;
|
||||
behindProxy: string | boolean;
|
||||
db: string;
|
||||
@@ -72,30 +42,18 @@ export interface SBSConfig {
|
||||
rateLimit: {
|
||||
vote: RateLimitConfig;
|
||||
view: RateLimitConfig;
|
||||
rate: RateLimitConfig;
|
||||
};
|
||||
mysql?: any;
|
||||
privateMysql?: any;
|
||||
minimumPrefix?: string;
|
||||
maximumPrefix?: string;
|
||||
redis?: RedisConfig;
|
||||
redisRead?: RedisReadOnlyConfig;
|
||||
redisRateLimit: boolean;
|
||||
maxRewardTimePerSegmentInSeconds?: number;
|
||||
postgres?: CustomWritePostgresConfig;
|
||||
postgresReadOnly?: CustomPostgresReadOnlyConfig;
|
||||
postgres?: CustomPostgresConfig;
|
||||
dumpDatabase?: DumpDatabase;
|
||||
diskCacheURL: string;
|
||||
crons: CronJobOptions;
|
||||
patreon: {
|
||||
clientId: string,
|
||||
clientSecret: string,
|
||||
minPrice: number,
|
||||
redirectUri: string
|
||||
}
|
||||
gumroad: {
|
||||
productPermalinks: string[],
|
||||
},
|
||||
minUserIDLength: number
|
||||
}
|
||||
|
||||
export interface WebhookConfig {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user