821 Commits

Author SHA1 Message Date
Ajay
1eedc9fa09 Remove old test 2025-10-03 15:13:31 -04:00
Ajay
c1fc6519b4 Remove username restriction 2025-10-03 15:09:02 -04:00
Ajay
2d5d3637fd Fix errors 2025-09-30 23:02:16 -04:00
Ajay
99ed7698c4 Handle trimmed UUID duplicates 2025-09-30 22:52:32 -04:00
Ajay Ramachandran
c0ee5206a2 Merge pull request #613 from ajayyy/dependabot/npm_and_yarn/tar-fs-2.1.4
Bump tar-fs from 2.1.3 to 2.1.4
2025-09-26 23:58:45 -04:00
dependabot[bot]
9c65f3ca34 Bump tar-fs from 2.1.3 to 2.1.4
Bumps [tar-fs](https://github.com/mafintosh/tar-fs) from 2.1.3 to 2.1.4.
- [Commits](https://github.com/mafintosh/tar-fs/compare/v2.1.3...v2.1.4)

---
updated-dependencies:
- dependency-name: tar-fs
  dependency-version: 2.1.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-26 19:54:27 +00:00
Ajay Ramachandran
c2c92cd168 Merge pull request #610 from mini-bomba/warning-history
Keep a history of warnings in the public database
2025-09-19 02:15:59 -04:00
Ajay Ramachandran
b4ea2018d5 Merge pull request #596 from ajayyy/dependabot/npm_and_yarn/multi-456de2e4f1
Bump serialize-javascript and mocha
2025-09-18 16:08:32 -04:00
dependabot[bot]
da448af4cf Bump serialize-javascript and mocha
Bumps [serialize-javascript](https://github.com/yahoo/serialize-javascript) to 6.0.2 and updates ancestor dependency [mocha](https://github.com/mochajs/mocha). These dependencies need to be updated together.


Updates `serialize-javascript` from 6.0.0 to 6.0.2
- [Release notes](https://github.com/yahoo/serialize-javascript/releases)
- [Commits](https://github.com/yahoo/serialize-javascript/compare/v6.0.0...v6.0.2)

Updates `mocha` from 10.1.0 to 10.8.2
- [Release notes](https://github.com/mochajs/mocha/releases)
- [Changelog](https://github.com/mochajs/mocha/blob/main/CHANGELOG.md)
- [Commits](https://github.com/mochajs/mocha/compare/v10.1.0...v10.8.2)

---
updated-dependencies:
- dependency-name: serialize-javascript
  dependency-type: indirect
- dependency-name: mocha
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-18 19:34:12 +00:00
Ajay Ramachandran
33a7934f33 Merge pull request #607 from ajayyy/dependabot/npm_and_yarn/form-data-4.0.4
Bump form-data from 4.0.0 to 4.0.4
2025-09-18 15:32:47 -04:00
Ajay Ramachandran
a2cad19167 Merge pull request #612 from ajayyy/dependabot/npm_and_yarn/multi-e981fcb12d
Bump path-to-regexp and express
2025-09-18 15:32:39 -04:00
dependabot[bot]
721720a60d Bump path-to-regexp and express
Bumps [path-to-regexp](https://github.com/pillarjs/path-to-regexp) to 1.9.0 and updates ancestor dependency [express](https://github.com/expressjs/express). These dependencies need to be updated together.


Updates `path-to-regexp` from 1.8.0 to 1.9.0
- [Release notes](https://github.com/pillarjs/path-to-regexp/releases)
- [Changelog](https://github.com/pillarjs/path-to-regexp/blob/master/History.md)
- [Commits](https://github.com/pillarjs/path-to-regexp/compare/v1.8.0...v1.9.0)

Updates `express` from 4.21.1 to 4.21.2
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/4.21.2/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.21.1...4.21.2)

---
updated-dependencies:
- dependency-name: path-to-regexp
  dependency-version: 1.9.0
  dependency-type: indirect
- dependency-name: express
  dependency-version: 4.21.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-13 13:49:39 +00:00
Ajay Ramachandran
220fe52013 Merge pull request #611 from ajayyy/dependabot/npm_and_yarn/axios-1.12.1
Bump axios from 1.8.4 to 1.12.1
2025-09-13 09:48:30 -04:00
dependabot[bot]
07c0f5cfbd Bump axios from 1.8.4 to 1.12.1
Bumps [axios](https://github.com/axios/axios) from 1.8.4 to 1.12.1.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.8.4...v1.12.1)

---
updated-dependencies:
- dependency-name: axios
  dependency-version: 1.12.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-13 12:38:31 +00:00
mini-bomba
899000309f make eslint scream about promises, then fix all lints
also rewrite a bunch of test suites from using done callbacks to using
async functions - it's way too easy to forget about a .catch() clause
2025-09-11 01:14:40 +02:00
mini-bomba
5664ff4f58 fix missed awaits for db.prepare in test cases 2025-09-10 23:24:44 +02:00
mini-bomba
c942eea640 autogenerate userids for the postwarning test suite 2025-09-10 22:59:54 +02:00
mini-bomba
b09e552d1d add disableTime column to the warnings table 2025-09-10 22:50:43 +02:00
mini-bomba
3e74a0da58 Remove warning expiry, save warning history 2025-09-10 18:54:56 +02:00
mini-bomba
1b99a8534c type IDatabase::prepare with overloads 2025-09-10 17:08:39 +02:00
Ajay
3711286ef2 Fix old xss prevention only removing first less than symbol 2025-07-30 01:26:02 -04:00
Ajay
74b9b123a8 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2025-07-25 02:15:29 -04:00
Ajay
367cb24478 Add hook category 2025-07-25 02:15:27 -04:00
dependabot[bot]
41c91b8b03 Bump form-data from 4.0.0 to 4.0.4
Bumps [form-data](https://github.com/form-data/form-data) from 4.0.0 to 4.0.4.
- [Release notes](https://github.com/form-data/form-data/releases)
- [Changelog](https://github.com/form-data/form-data/blob/master/CHANGELOG.md)
- [Commits](https://github.com/form-data/form-data/compare/v4.0.0...v4.0.4)

---
updated-dependencies:
- dependency-name: form-data
  dependency-version: 4.0.4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-21 23:11:19 +00:00
Ajay Ramachandran
40c4ec7437 Merge pull request #606 from ajayyy/dependabot/npm_and_yarn/tar-fs-2.1.3
Bump tar-fs from 2.1.2 to 2.1.3
2025-06-03 14:40:36 -04:00
dependabot[bot]
70ce320737 Bump tar-fs from 2.1.2 to 2.1.3
Bumps [tar-fs](https://github.com/mafintosh/tar-fs) from 2.1.2 to 2.1.3.
- [Commits](https://github.com/mafintosh/tar-fs/commits)

---
updated-dependencies:
- dependency-name: tar-fs
  dependency-version: 2.1.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-03 09:19:22 +00:00
Ajay Ramachandran
0bfc9b30f5 Merge pull request #605 from mini-bomba/fix/banned-webhooks
don't send dearrow webhooks for banned users
2025-05-29 12:09:59 -04:00
mini-bomba
bce5385864 shortcircuit the new user check for banned users 2025-05-26 16:41:55 +02:00
mini-bomba
f71c4ceba9 don't send dearrow webhooks for banned users 2025-05-25 22:46:23 +02:00
Ajay
69ca711bb3 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2025-04-28 19:17:55 -04:00
Ajay
e519986027 Fix dearrow hiding 2025-04-28 19:17:54 -04:00
Ajay Ramachandran
c0e7401a73 Merge pull request #604 from mini-bomba/limit-usernames
Limit username creation
2025-04-28 19:04:03 -04:00
Ajay
314461c9f0 Fix old user check 2025-04-28 19:03:24 -04:00
mini-bomba
655789e62d Limit username creation 2025-04-29 00:10:20 +02:00
Ajay
339ba127eb Fix log 2025-04-28 02:59:15 -04:00
Ajay
da393da9e9 Fix log 2025-04-28 02:56:36 -04:00
Ajay
aa2c7bf6ea Fix log 2025-04-28 02:41:34 -04:00
Ajay
c82708aae8 Fix log 2025-04-28 02:40:57 -04:00
Ajay
26c575d37a Add log 2025-04-28 02:32:17 -04:00
Ajay Ramachandran
1b3b1b1cb3 Merge pull request #603 from mini-bomba/request-validator-rule-names
Add request validator rule names
2025-04-26 01:46:42 -04:00
mini-bomba
9bc4bf8c7b Add request validator rule names 2025-04-26 02:10:33 +02:00
Ajay
cbc38c5ac8 Add another logging webhook 2025-04-25 17:43:01 -04:00
Ajay Ramachandran
e7f3753077 Merge pull request #602 from mini-bomba/request-validator
Create an engine for rule-based request validation
2025-04-25 17:37:25 -04:00
mini-bomba
f44d3cd92c rephrase old rejection logs 2025-04-25 21:52:39 +02:00
mini-bomba
4db4e9458e hook up extra functions to the request validator 2025-04-25 21:52:39 +02:00
mini-bomba
b2cd048909 load request validator rules from env as json 2025-04-25 21:11:30 +02:00
mini-bomba
5c249fb02b test cases for the request validator engine 2025-04-25 21:11:30 +02:00
mini-bomba
f7e5394a18 create a request validator engine 2025-04-25 21:11:30 +02:00
Ajay
161db6df0c Don't error if failing to parse vanced ua 2025-04-25 13:51:46 -04:00
Ajay
920d288f0b Add title to webhook 2025-04-25 13:00:34 -04:00
Ajay
0d005c23bf Add another validity filter 2025-04-25 12:55:44 -04:00
Ajay
9f745d3a8b Move permission check 2025-04-21 23:50:46 -04:00
Ajay
39f8dc6c22 Fix revanced ua 2025-04-21 20:14:43 -04:00
Ajay
08ba5c21b1 Fix validity check 2025-04-21 19:39:46 -04:00
Ajay
cfd61dc8dd Validity check 2025-04-21 19:26:42 -04:00
Ajay
039fb3ac7a More logs 2025-04-21 12:39:14 -04:00
Ajay
fccebfa487 Fixed webhook again 2025-04-21 11:27:16 -04:00
Ajay
6130ac8150 Change color for dearrow webhook 2025-04-21 11:20:08 -04:00
Ajay
7e681d2cd5 Fix webhook newlines 2025-04-21 11:15:30 -04:00
Ajay
707b36d161 Fix user agent parser lower casing 2025-04-21 11:10:47 -04:00
Ajay
b849328fae More logging 2025-04-21 10:53:49 -04:00
Ajay
3d596f4528 Save user agent for dearrow 2025-04-17 01:05:34 -04:00
Ajay
ed5a397a30 Improve permission check 2025-04-15 02:01:41 -04:00
Ajay
300642fd4f Fix innertube failure handling 2025-04-12 00:44:10 -04:00
Ajay
46580322fc Fix dearrow old submitter check 2025-04-11 02:44:19 -04:00
Ajay
318152dac6 ua 2025-04-11 02:41:17 -04:00
Ajay
8111d34b30 Fix dearrow threshold not configurable 2025-04-10 16:51:46 -04:00
Ajay
ac78dee210 Fix undefined error 2025-04-10 14:38:08 -04:00
Ajay
d18a4a13f2 Check dearrow vote history for new submitters 2025-04-10 12:47:32 -04:00
Ajay
8d40d61efc Allow max users without a submitter threshold 2025-04-10 02:35:22 -04:00
Ajay
74f6224091 Add new user limit per 5 mins 2025-04-10 02:26:09 -04:00
Ajay
9b55dc5d4d Add new config option 2025-04-08 16:52:16 -04:00
Ajay
8cd2138989 Use config for old submitter check 2025-04-08 16:50:04 -04:00
Ajay
e40af45c73 Fix query 2025-04-08 16:43:01 -04:00
Ajay
5de1fe4388 Fix post config url 2025-04-08 16:26:51 -04:00
Ajay
2ef3d68af0 Await promise not being awaited 2025-04-08 16:02:29 -04:00
Ajay
f67244663e Use alias for getting server config 2025-04-08 15:56:23 -04:00
Ajay
00064d5a7c Fix config fetching 2025-04-08 15:46:14 -04:00
Ajay
ac26aed21c Add endpoints for config setting 2025-04-08 15:18:32 -04:00
Ajay
2aa3589312 Add ability to set config 2025-04-08 15:15:39 -04:00
Ajay
82af8f200b Add better ua parsing 2025-04-08 14:21:24 -04:00
Ajay
69cb33aad0 Add logs 2025-04-08 13:23:24 -04:00
Ajay
3817d7fdba Better submission error message 2025-04-08 13:21:01 -04:00
Ajay
34a6a83e44 Change dearrow permission requirements 2025-04-07 19:28:52 -04:00
Ajay
0967373cb2 Rename func 2025-04-07 00:57:48 -04:00
Ajay
b7794b57d0 Fix can vote checks 2025-04-07 00:57:08 -04:00
Ajay
550339db41 Add permission check in more places 2025-04-07 00:36:01 -04:00
Ajay
b69f050b44 Old submitter only 2025-04-07 00:29:53 -04:00
Ajay Ramachandran
59a986f32f Merge pull request #600 from ajayyy/dependabot/npm_and_yarn/multi-b9f445934c
Bump semver and nodemon
2025-03-29 15:07:03 -04:00
dependabot[bot]
7088a1688d Bump semver and nodemon
Bumps [semver](https://github.com/npm/node-semver) to 7.7.1 and updates ancestor dependencies [semver](https://github.com/npm/node-semver) and [nodemon](https://github.com/remy/nodemon). These dependencies need to be updated together.


Updates `semver` from 7.3.7 to 7.7.1
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/main/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v7.3.7...v7.7.1)

Updates `semver` from 6.3.0 to 7.7.1
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/main/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v7.3.7...v7.7.1)

Updates `nodemon` from 2.0.20 to 3.1.9
- [Release notes](https://github.com/remy/nodemon/releases)
- [Commits](https://github.com/remy/nodemon/compare/v2.0.20...v3.1.9)

---
updated-dependencies:
- dependency-name: semver
  dependency-type: indirect
- dependency-name: semver
  dependency-type: indirect
- dependency-name: nodemon
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-29 04:55:45 +00:00
Ajay Ramachandran
f07f94fb09 Merge pull request #598 from ajayyy/dependabot/npm_and_yarn/tar-fs-2.1.2
Bump tar-fs from 2.1.1 to 2.1.2
2025-03-29 00:54:48 -04:00
Ajay Ramachandran
a7758a2608 Merge pull request #599 from ajayyy/dependabot/npm_and_yarn/axios-1.8.4
Bump axios from 1.7.7 to 1.8.4
2025-03-29 00:54:40 -04:00
dependabot[bot]
fd5bc43281 Bump axios from 1.7.7 to 1.8.4
Bumps [axios](https://github.com/axios/axios) from 1.7.7 to 1.8.4.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.7.7...v1.8.4)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-29 04:40:49 +00:00
dependabot[bot]
3633d0fbb4 Bump tar-fs from 2.1.1 to 2.1.2
Bumps [tar-fs](https://github.com/mafintosh/tar-fs) from 2.1.1 to 2.1.2.
- [Commits](https://github.com/mafintosh/tar-fs/compare/v2.1.1...v2.1.2)

---
updated-dependencies:
- dependency-name: tar-fs
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-28 22:28:04 +00:00
Ajay
aae56887da Update gitignore 2025-03-12 02:46:05 -04:00
Ajay
4fe7cebcb3 Add caching for 5 length skip skip segment query 2025-03-12 02:45:59 -04:00
Ajay
31e678fdc2 Store titles for casual vote submissions
When an uploader changes the title, it will reset the casual votes
2025-02-17 03:16:57 -05:00
Ajay
d44ce3c2dc Add casual votes table export 2025-02-16 14:43:55 -05:00
Ajay
5f9b4c8acc Make casual downvotes apply to all categories 2025-02-13 04:03:38 -05:00
Ajay
d608125b41 Add endpoint for casual submission count 2025-02-12 03:52:03 -05:00
Ajay
fb3abb3216 Fix index for casual votes 2025-02-06 03:01:22 -05:00
Ajay
ccde64e90f Change casual submission to allow submitting multiple categories 2025-02-06 02:57:09 -05:00
Ajay
4abf57b0ce Save casual mode status in db 2025-02-06 02:51:13 -05:00
Ajay
07435b9af1 Add casual mode endpoint 2025-02-05 03:38:55 -05:00
Ajay Ramachandran
ab9cab8ff5 Merge pull request #582 from hanydd/dev_join
Change reduce to join function for simplicity
2025-02-03 20:55:55 -05:00
Ajay Ramachandran
311c653ea2 Merge pull request #592 from Choromanski/feature/node-deprecation
Upgraded github actions dependencies
2025-02-03 20:54:48 -05:00
Ajay Ramachandran
e92d47e1a4 Merge pull request #593 from ajayyy/dependabot/npm_and_yarn/multi-9f37c16f8f
Bump cookie and express
2025-02-03 20:54:22 -05:00
Ajay Ramachandran
3734b88cb5 Merge pull request #595 from mchangrh/patch-1
bump & lock rsync dockerfile
2025-01-18 12:54:45 -05:00
Michael M. Chang
00086d9001 bump & lock rsync dockerfile 2025-01-18 06:45:09 -08:00
Ajay
a37a552b17 Fix video labels keys not clearing properly 2025-01-18 03:32:55 -05:00
Ajay
fa29cfd3c6 Add endpoint to get segment ID 2025-01-18 02:56:57 -05:00
Ajay
be9d97ae2b Add option to trim UUIDs in skip segments endpoint 2025-01-18 02:09:46 -05:00
Ajay
06f83cd8d4 Allow voting and viewing with partial UUID 2025-01-18 02:04:27 -05:00
Ajay
80b1019783 Allow video labels cashing with prefix of 4 2025-01-18 00:22:17 -05:00
Ajay
2455d2cd7e Make hasStartSegment result optional 2025-01-17 23:59:17 -05:00
Ajay
e2a9976cd0 Add hasStartSegment to video label 2025-01-17 23:30:32 -05:00
Ajay
bba06511ce Remove unnecessary parts of video labels request 2025-01-17 04:38:08 -05:00
Ajay
043268dc10 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-12-04 14:49:36 -05:00
Ajay
003fe77e72 Change backup retention 2024-12-04 14:49:34 -05:00
Ajay Ramachandran
efe59c5098 Merge pull request #594 from mini-bomba/dearrow_locked_vip_downvotes
Send a different message for VIP downvotes on locked titles
2024-11-14 19:56:02 -05:00
Ajay Ramachandran
7ef6452eb5 Double quote 2024-11-14 19:49:25 -05:00
mini-bomba
9c01b711a5 Send a different message for VIP downvotes on locked titles 2024-11-14 22:30:14 +01:00
Ajay
b2981fe782 Don't allow multiple downvotes on one submission 2024-11-10 15:21:40 -05:00
Ajay
405805ff89 Add check against missing api video detail failing to fetch 2024-11-07 02:24:39 -05:00
Ajay
01c306287a Fix axios error handling 2024-11-06 21:23:15 -05:00
Ajay
826d49ba1f Add support for floatie proxy 2024-11-04 15:04:43 -05:00
Ajay
b03057c5bf Fix redis cache metrics generation 2024-10-30 02:35:59 -04:00
Ajay
54e03a389b Remove string from metrics 2024-10-30 02:32:33 -04:00
Ajay
93f7161724 Only uploaded warned info for upvotes 2024-10-27 02:17:34 -04:00
dependabot[bot]
efa6c10d56 Bump cookie and express
Bumps [cookie](https://github.com/jshttp/cookie) to 0.7.1 and updates ancestor dependency [express](https://github.com/expressjs/express). These dependencies need to be updated together.


Updates `cookie` from 0.6.0 to 0.7.1
- [Release notes](https://github.com/jshttp/cookie/releases)
- [Commits](https://github.com/jshttp/cookie/compare/v0.6.0...v0.7.1)

Updates `express` from 4.21.0 to 4.21.1
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/4.21.1/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.21.0...4.21.1)

---
updated-dependencies:
- dependency-name: cookie
  dependency-type: indirect
- dependency-name: express
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-10-19 12:03:41 +00:00
Ajay
e9c0c44528 Add new webhook for was warned 2024-10-18 03:08:24 -04:00
Brian Choromanski
4dfbb9039d Upgraded more actions dependencies 2024-10-08 21:17:01 -04:00
Brian Choromanski
05c5cf57e4 Upgraded actions dependencies 2024-10-08 21:10:10 -04:00
Ajay
566eabdc31 Add metrics endpoint 2024-10-02 20:06:57 -04:00
Ajay Ramachandran
f26db7238a Merge pull request #591 from ajayyy/dependabot/npm_and_yarn/multi-d66d039ac5
Bump serve-static and express
2024-09-17 02:30:27 -04:00
dependabot[bot]
fb05ec51d3 Bump serve-static and express
Bumps [serve-static](https://github.com/expressjs/serve-static) to 1.16.2 and updates ancestor dependency [express](https://github.com/expressjs/express). These dependencies need to be updated together.


Updates `serve-static` from 1.15.0 to 1.16.2
- [Release notes](https://github.com/expressjs/serve-static/releases)
- [Changelog](https://github.com/expressjs/serve-static/blob/v1.16.2/HISTORY.md)
- [Commits](https://github.com/expressjs/serve-static/compare/v1.15.0...v1.16.2)

Updates `express` from 4.19.2 to 4.21.0
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/4.21.0/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.19.2...4.21.0)

---
updated-dependencies:
- dependency-name: serve-static
  dependency-type: indirect
- dependency-name: express
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-17 06:18:07 +00:00
Ajay
eeb9f1b02f Log more when redis increment fails 2024-09-15 04:30:44 -04:00
Ajay
8ba68e1b4c One less call when dealing with lru cache for ttl result and ensure reset keys cleared 2024-09-14 18:02:22 -04:00
Ajay
17059fdbe6 One less call when dealing with lru cache 2024-09-14 17:52:50 -04:00
Ajay
6e5f4f7610 Fix active requests list not getting deleted 2024-09-14 17:33:17 -04:00
Ajay
c313590d36 persona's revenge 2024-09-13 21:51:06 -04:00
Ajay
4508ad11f2 Fix error when submitter ip not found 2024-09-13 14:37:37 -04:00
Ajay
dc5158257e Fix errors when postgres returns undefined and trying to save to redis 2024-09-13 14:36:52 -04:00
Ajay
6edd71194b Log redis stats on high db load 2024-09-13 14:29:32 -04:00
Ajay
7678be1e24 Add max redis response time for reads 2024-09-13 04:06:50 -04:00
Ajay
d28ac39d4f Allow newly used header 2024-09-07 23:31:16 -04:00
Ajay
5fd6b5eb8b Fix canSubmitOriginal query on postgres 2024-09-01 19:29:08 -04:00
Ajay
0e1a38c4d4 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-09-01 19:01:00 -04:00
Ajay
c496be5651 Disable innertube tests while they are broken 2024-09-01 19:00:59 -04:00
Ajay Ramachandran
15a9c3a4eb Merge pull request #583 from ajayyy/dependabot/npm_and_yarn/braces-3.0.3
Bump braces from 3.0.2 to 3.0.3
2024-09-01 18:57:32 -04:00
Ajay Ramachandran
f1ebd56526 Merge pull request #590 from ajayyy/dependabot/npm_and_yarn/axios-1.7.7
Bump axios from 1.6.0 to 1.7.7
2024-09-01 18:57:18 -04:00
Ajay
258749ac31 Add more strict requirements for voting for original thumbnails 2024-09-01 18:56:29 -04:00
dependabot[bot]
ccccb1af3c Bump axios from 1.6.0 to 1.7.7
Bumps [axios](https://github.com/axios/axios) from 1.6.0 to 1.7.7.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.6.0...v1.7.7)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-01 22:43:59 +00:00
Ajay
13b8a988db update dep 2024-09-01 18:43:28 -04:00
Ajay
803fc18554 Verify old submissions right after someone votes on it 2024-08-16 00:36:42 -04:00
Ajay
59373cf346 Fix rejected server-side rendered ads issue not rejecting 2024-08-14 23:42:47 -04:00
Ajay
05fd6abe91 Use env vars in workflow 2024-08-12 01:04:12 -04:00
Ajay
090e185765 Add support for poToken and visitor data
Fixes api requests

https://github.com/iv-org/invidious/pull/4789
2024-08-12 00:33:11 -04:00
Ajay
d2df5cef98 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-08-11 13:49:48 -04:00
Ajay
214946897d Hardcode nn-block reputation 2024-08-11 13:49:46 -04:00
Ajay Ramachandran
8da5de4d7b Merge pull request #588 from mini-bomba/dearrow-locked-titles-downvotes
postBranding.ts webhook changes
2024-08-04 09:38:24 +02:00
mini-bomba
380ec8d0ca Reformat SQL code in postBranding.ts webhook code 2024-08-03 22:01:46 +02:00
mini-bomba
72086b0195 Send webhook messages when a locked title is downvoted
also take downvotes & verification into consideration when comparing
titles in webhook code
2024-08-03 21:56:31 +02:00
mini-bomba
61dcfeb69f Don't send to #dearrow-locked-titles when downvoting unlocked title
voteType passed to sendWebhooks() function to avoid confusion in the
future should someone forget about the if statement
2024-08-03 21:39:21 +02:00
Ajay Ramachandran
19d6d85aa6 Merge pull request #589 from mini-bomba/tests-fix
fix postgres+redis tests
2024-08-03 21:32:18 +02:00
mini-bomba
814ceb56f1 fix postgres+redis tests
made on request
https://discord.com/channels/603643120093233162/607338052221665320/1269373542550470730
2024-08-03 21:23:44 +02:00
Ajay Ramachandran
195cc14d25 Merge pull request #585 from mini-bomba/unrelated_chapter_suggestions
Don't show completely unrelated chapter suggestions
2024-08-03 21:19:59 +02:00
Ajay Ramachandran
9427bf4f3d Merge pull request #586 from TristanWasTaken/db-schema
docs: fix typos in DatabaseSchema.md
2024-08-03 08:00:47 +02:00
mini-bomba
3f026409cd Don't show completely unrelated chapter suggestions
Chapter suggestions should be at least slightly related to what the user
has already typed.
This change stops the server from sending suggestions that postgresql
deems to be "less than 10% similar"

Also modified tests to reflect this change.
2024-07-29 02:26:53 +02:00
Ajay
d75b9ddcaa Show failure reason in webook 2024-07-24 13:42:40 -04:00
Ajay
2fb3d05055 private video? 2024-07-24 13:06:19 -04:00
Ajay
165ed8a6e0 Fix original thumbnail votes being shown because of fetch all 2024-07-09 19:49:37 -04:00
Ajay
495b8031e3 Add better logging for failed reputation call 2024-06-30 09:40:25 -04:00
HanYaodong
374ddc74bd Use join function for simplicity 2024-06-25 21:33:47 +08:00
Ajay
738f863581 Don't send server-side render error for title submissions 2024-06-25 14:36:05 +05:30
Tristan
8b5e69f36f docs: fix typos in DatabaseSchema.md 2024-06-24 03:14:05 +02:00
Ajay
10e37824d8 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-06-21 15:43:30 +05:30
Ajay
428343e7d8 Require a vote for original to show 2024-06-21 15:43:26 +05:30
Ajay Ramachandran
4e69ac60bc Merge pull request #584 from TristanWasTaken/db
docs: update DatabaseSchema.md
2024-06-21 09:00:52 +05:30
Tristan
3b03792903 docs: fix userFeatures md list 2024-06-21 03:17:31 +02:00
Tristan
1a0b6ab097 Update DatabaseSchema.md 2024-06-21 03:15:07 +02:00
Tristan
8e5084cd72 docs: update private schemas 2024-06-21 03:11:28 +02:00
Tristan
96feaf3cbe docs: update public schemas 2024-06-21 03:08:38 +02:00
Tristan
d08cfee5b4 docs: update private indexes 2024-06-21 01:35:38 +02:00
Tristan
96dd9eceb3 docs: update public indexes 2024-06-21 01:34:25 +02:00
Tristan
4422104294 docs: format lists 2024-06-21 01:34:15 +02:00
Tristan
4ad553478b chore: fix misleading/unclear migration comments 2024-06-21 00:50:10 +02:00
dependabot[bot]
47323156c1 Bump braces from 3.0.2 to 3.0.3
Bumps [braces](https://github.com/micromatch/braces) from 3.0.2 to 3.0.3.
- [Changelog](https://github.com/micromatch/braces/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/braces/compare/3.0.2...3.0.3)

---
updated-dependencies:
- dependency-name: braces
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-16 11:24:49 +00:00
Ajay
a181d52fb2 Fix types 2024-06-12 12:01:40 +05:30
Ajay
ee9ed6af1f Add server-side ads check for dearrow submissions 2024-06-12 11:57:59 +05:30
Ajay
ec1e6d63a4 Add protection against server-side ad injection (SSAP) 2024-06-12 09:55:41 +05:30
Ajay
5c10e071dc Change how video duration check works for submissions 2024-05-27 13:54:02 -04:00
Ajay
8eb6f5b2ea Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-05-07 15:37:59 -04:00
Ajay
bdfe4938d2 Fix vote webhook not working 2024-05-07 15:37:57 -04:00
Ajay Ramachandran
bcf29e4047 Merge pull request #579 from ajayyy/dependabot/npm_and_yarn/express-4.19.2
Bump express from 4.18.2 to 4.19.2
2024-05-05 01:28:41 -04:00
Ajay Ramachandran
622c3f27d6 Merge pull request #581 from mini-bomba/videoduration-inconsistency
Make returned video duration in getBranding.ts consistent
2024-05-05 01:28:22 -04:00
mini-bomba
7c1abd9747 Make returned video duration in getBranding.ts consistent
Instead of picking the first segment returned by the db (i.e. possibly
random), sort segments by submission time and use the oldest visible
segment with a non-zero video duration.
2024-05-04 21:56:03 +02:00
Ajay
709485e0e9 Increase frequency of docker forgets 2024-04-27 00:42:55 -04:00
Ajay
f841d8173b Fix ttl cache key not properly cleared 2024-04-22 00:53:09 -04:00
Ajay
b2f7e1b39b Fix locked check for thumbnail downvotes 2024-04-21 23:13:10 -04:00
Ajay
47ea6ae8d3 Only check request time for readiness if cache has filled up 2024-04-21 13:38:32 -04:00
Ajay
063607fe30 Add etags for branding as well 2024-04-20 13:16:34 -04:00
Ajay
4b795da5a0 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-04-20 00:02:16 -04:00
Ajay
8043bd9006 Make max response time configurable 2024-04-20 00:02:15 -04:00
Ajay Ramachandran
bd8f4b7539 Merge pull request #577 from SuperStormer/master
cosmetic fix for lock reason
2024-04-19 21:22:57 -04:00
Ajay
0f97ce4a49 Make redis readiness check recoverable 2024-04-19 21:20:40 -04:00
Ajay
cfd7c3d8c4 Add more to ready check 2024-04-19 20:24:42 -04:00
Ajay
af7d8428ab Improve ready check 2024-04-19 20:05:52 -04:00
Ajay
7c51586664 Add error server 2024-04-16 03:01:44 -04:00
Ajay
2251ddc251 Add ready endpoint 2024-04-16 01:13:56 -04:00
Ajay
07d4dde4f6 Add connections to status 2024-04-16 00:13:51 -04:00
Ajay
b934b7a937 Use innertube when possible 2024-04-14 01:26:03 -04:00
Ajay
f2cf2e2aac Add db stats to logs 2024-04-13 03:00:26 -04:00
Ajay
2887a8505c Improve logging and fix ip fetch error breaking skip segments 2024-04-13 01:54:59 -04:00
Ajay
e289fe9075 Add ttl cache 2024-04-12 01:29:23 -04:00
Ajay
2cd9401a51 Fix etag tests 2024-04-11 18:12:02 -04:00
Ajay
47bea9ee6e Trigger usage of cache key when checking ttl 2024-04-11 17:57:53 -04:00
Ajay
0602fdd651 Use cache for ttl if possible
Also fixes etag when compression enabled
2024-04-11 17:54:32 -04:00
Ajay
7c77bf566e Remove quotes when processing etag 2024-04-11 17:07:13 -04:00
Ajay
1009fff9e9 Fix caching issues with one specific key form
.c regex was any character plus a c instead of intenced dot
2024-04-11 17:04:17 -04:00
Ajay
f43e59250f Add quotes to etag 2024-04-11 14:11:04 -04:00
Ajay
dc2115ef20 Change status timeout 2024-04-09 13:29:18 -04:00
dependabot[bot]
55c3e4f01f Bump express from 4.18.2 to 4.19.2
Bumps [express](https://github.com/expressjs/express) from 4.18.2 to 4.19.2.
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.18.2...4.19.2)

---
updated-dependencies:
- dependency-name: express
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-28 17:17:43 +00:00
Ajay
af31f511a5 Add tests for fetch all 2024-03-24 13:52:33 -04:00
Ajay
0d9cce0512 Fix wrong comparison with votes filtering 2024-03-24 13:42:39 -04:00
Ajay
c19d6fe97a Only send low voted segments when asked for 2024-03-22 18:37:39 -04:00
Ajay
47c109f012 Fix act as vip unlocking segments 2024-03-21 19:35:13 -04:00
Ajay
a921085da6 Fix vip downvotes unlocking 2024-03-21 19:28:05 -04:00
Ajay
d5ebd8ec1a Improve self downvoting for dearrow 2024-03-20 13:47:23 -04:00
Ajay
a7f10f7727 Attempt to fix docker build error 2024-03-17 13:40:53 -04:00
Ajay
1c234846db Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-03-17 13:20:25 -04:00
Ajay
bc1ca098e7 Fix bug causing people to accidentally super downvote 2024-03-17 13:20:23 -04:00
Ajay Ramachandran
cf21ebc2de Merge pull request #578 from ajayyy/dependabot/npm_and_yarn/follow-redirects-1.15.6
Bump follow-redirects from 1.15.4 to 1.15.6
2024-03-16 21:07:40 -04:00
dependabot[bot]
2426a6ee03 Bump follow-redirects from 1.15.4 to 1.15.6
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.4 to 1.15.6.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.4...v1.15.6)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-16 23:28:16 +00:00
SuperStormer
ba65c28459 Update postSkipSegments.ts 2024-03-15 02:20:24 -04:00
Ajay
591b342855 Add default user count, update url 2024-03-06 00:47:51 -05:00
Ajay Ramachandran
8d8388386e Merge pull request #571 from ajayyy/dependabot/npm_and_yarn/follow-redirects-1.15.4
Bump follow-redirects from 1.15.1 to 1.15.4
2024-02-27 03:49:44 -05:00
Ajay
a54bf556ed Revert "Fix usercounter behind cloudflare"
This reverts commit 9bcceb7e5b.
2024-02-27 03:49:03 -05:00
Ajay
f1c5b8a359 Merge branches 'master' and 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-02-27 03:33:44 -05:00
Ajay
9bcceb7e5b Fix usercounter behind cloudflare 2024-02-27 03:33:38 -05:00
Ajay Ramachandran
da0cf0dedc Merge pull request #575 from ajayyy/dependabot/npm_and_yarn/axios-1.6.0
Bump axios from 1.1.3 to 1.6.0
2024-02-20 17:16:53 -05:00
dependabot[bot]
1cefdf4dac Bump axios from 1.1.3 to 1.6.0
Bumps [axios](https://github.com/axios/axios) from 1.1.3 to 1.6.0.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.1.3...v1.6.0)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-20 21:00:34 +00:00
Ajay
aec2aa4457 Fix keys not properly clearing 2024-02-16 22:14:09 -05:00
Ajay
3f29e11449 Fix submission and vote locks 2024-02-16 14:24:28 -05:00
Ajay
6d11e1c601 Support dragonfly with in memory cache 2024-02-09 18:16:28 -05:00
Ajay
9fa248037a Add to cache when calling set 2024-02-09 17:28:59 -05:00
Ajay
02a640d857 Use broadcast mode for redis 2024-02-09 15:34:36 -05:00
Ajay
17b002649e Add logging when too many active connections 2024-02-09 14:54:14 -05:00
Ajay
a74189b287 Fix cache invalidation with compression enabled 2024-02-09 14:19:56 -05:00
Ajay
09997d82ed Fix chrome extension user fetcher 2024-02-09 13:47:59 -05:00
Ajay
bf644d6899 Don't use broadcast mode for redis 2024-02-09 12:09:03 -05:00
Ajay
5929460239 Remove weighted randomness and change weight calculation 2024-02-09 12:08:52 -05:00
Ajay
09dd10ad6f Fix memory cache invalidation not invalidating every item 2024-02-09 00:34:12 -05:00
Ajay
af5e8cd68d Fix uncached misses tracking 2024-02-08 22:15:28 -05:00
Ajay
bd766ab430 Remove unused import 2024-02-08 22:12:53 -05:00
Ajay
bf1fe1ff61 Allow toggling redis compression and disable by default 2024-02-08 21:58:10 -05:00
Ajay
db225f8a84 Reuse running redis connections and handle redis race condition 2024-02-08 21:30:27 -05:00
Ajay
9364a7e654 Show general last invalidation message 2024-02-08 21:15:28 -05:00
Ajay
f3fffa56c9 Don't allow downvoting locked segments 2024-02-08 15:47:25 -05:00
Ajay
c478546128 Count invalidation only on successful delete 2024-02-08 15:12:48 -05:00
Ajay
e61f964d17 Add ttl to in memory cache cache 2024-02-08 14:37:01 -05:00
Ajay
5f8ef25d88 Use broadcast mode for client tracking and add new memory cache stat 2024-02-08 14:30:32 -05:00
Ajay
b76cfdf798 Allow more things to be cached 2024-02-08 03:40:41 -05:00
Ajay
3c6000f2da Rename config for clientCacheSize 2024-02-08 03:26:06 -05:00
Ajay
9944d70f6b Use size for lru limit instead of length 2024-02-08 03:23:55 -05:00
Ajay
27069cb5c2 Change what gets saved in memory cache 2024-02-08 03:08:02 -05:00
Ajay
8aa03c81a7 Improve cache miss calculation 2024-02-08 03:06:30 -05:00
Ajay
e8879f66b1 Add redis in memory cache stats 2024-02-08 02:58:51 -05:00
Ajay
acdbd3787b More specific on what should be client cached 2024-02-08 01:04:48 -05:00
Ajay
1f7156eb29 Don't crash if redis message invalid 2024-02-08 00:34:37 -05:00
Ajay
7405053b44 Reuse running reputation requests 2024-02-07 23:40:59 -05:00
Ajay
a929f69452 Fix same ip being fetched multiple times from postgres 2024-02-07 23:36:45 -05:00
Ajay
8574ec3a0c Fix is number check 2024-02-07 22:28:28 -05:00
Ajay
1475c91327 Clear cache again after setting up client tracking 2024-02-06 15:32:40 -05:00
Ajay
5b1b362bf0 Handle reconnects with client-side caching
Also upgrades redis to fix a library bug
2024-02-06 00:52:42 -05:00
Ajay
14da10bd8a Add client-side caching 2024-02-05 13:11:44 -05:00
Ajay
547632341a Add back redis compression optionally 2024-02-04 23:17:28 -05:00
Ajay
c54c25c73b Disable query cache for segment groups 2024-02-04 22:53:12 -05:00
Ajay
121cc7f481 Fix duplicate behavior with submitting full video labels 2024-01-31 13:05:47 -05:00
Ajay
e041b9c930 Don't throw 409 if only one segment was successfully submitted 2024-01-31 12:59:01 -05:00
Ajay
59d9ed390f Fix titles and thumbnails being unlocked 2024-01-28 22:05:04 -05:00
Ajay
4477ab7ca6 Remove bad test 2024-01-21 19:55:16 -05:00
Ajay
25ec9b0291 Revert adding redis compression
This reverts commit fce311377f and 2ad51842cc
2024-01-21 19:49:36 -05:00
Ajay
c3e00ac8b1 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2024-01-21 19:46:18 -05:00
Ajay
2c9079f565 No more verification through sb submissions 2024-01-21 19:46:16 -05:00
Ajay Ramachandran
aee84a4b6e Merge pull request #572 from SashaXser/master
Promise.resolve and Using "forEach" instead of "map"
2024-01-20 00:08:55 -05:00
SashaXser
a8010b553d Merge branch 'master' into master 2024-01-20 07:07:03 +04:00
SashaXser
5b95aa8aba Resolve conflicts 2024-01-20 06:59:12 +04:00
Ajay
fce311377f Switch to lz4 compression 2024-01-19 15:16:50 -05:00
Ajay
dcb479f3d2 Fallback to allowing taking a lock if redis fails 2024-01-19 14:35:32 -05:00
Ajay
2ad51842cc Compress redis values 2024-01-19 14:34:18 -05:00
SashaXser
ea60947092 format fix 2024-01-19 14:31:03 +04:00
SashaXser
14b6f84f94 2 things
Consider using "forEach" instead of "map" as its return value is not being used here.
Replace this trivial promise with "Promise.resolve".
2024-01-19 08:50:45 +04:00
Ajay
8e13ec60d6 Fix other get missing throw 2024-01-18 11:57:50 -05:00
Ajay
c9f7275942 Only use redis timeout when db not under load 2024-01-18 09:22:00 -05:00
Ajay
d607d8b179 Don't fallback to db when too many redis connections 2024-01-15 14:07:34 -05:00
dependabot[bot]
5974b51391 Bump follow-redirects from 1.15.1 to 1.15.4
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.1 to 1.15.4.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.1...v1.15.4)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-10 02:08:26 +00:00
Ajay
7aaf000d99 Fix index for hashed video id dearrow fetching 2024-01-09 15:31:56 -05:00
Ajay
0edf0b9e1c Don't handle shadowhide on high load 2024-01-03 11:37:58 -05:00
Ajay
84fd7c170f Add test for VIP downvote without removing 2024-01-03 01:18:57 -05:00
Ajay
b04e0dcd97 DeArrow downvotes 2024-01-03 01:13:35 -05:00
Ajay
33dad0a5e4 Add option to submit without locking
Also fixes voting for an existing thumbnail not unlocking other thumbnails
2024-01-02 19:12:55 -05:00
Ajay
ad439fd368 Make sure latest dump is not deleted 2023-12-28 19:10:12 -05:00
Ajay
21bb893a47 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2023-12-28 18:23:45 -05:00
Ajay
211ecf700b Reject on dump failure to trigger a retry 2023-12-28 18:23:41 -05:00
Ajay Ramachandran
951d678640 Merge pull request #569 from mchangrh/fix-shadowban
clean up shadowban code, exclude long running categories query
2023-12-21 20:36:28 -05:00
Michael C
15f19df8a4 clean up shadowban code, exclude long running categories query when possible 2023-12-21 18:37:24 -05:00
Ajay Ramachandran
4a4d5776a1 Merge pull request #568 from ajayyy/revert-566-dependabot/npm_and_yarn/axios-1.6.0
Revert "Bump axios from 1.1.3 to 1.6.0"
2023-12-06 00:17:05 -05:00
Ajay Ramachandran
b3a28f7df3 Revert "Bump axios from 1.1.3 to 1.6.0" 2023-12-06 00:16:55 -05:00
Ajay Ramachandran
f763139664 Merge pull request #566 from ajayyy/dependabot/npm_and_yarn/axios-1.6.0
Bump axios from 1.1.3 to 1.6.0
2023-11-11 10:50:35 -05:00
dependabot[bot]
da482054a4 Bump axios from 1.1.3 to 1.6.0
Bumps [axios](https://github.com/axios/axios) from 1.1.3 to 1.6.0.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.1.3...v1.6.0)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-11 08:17:36 +00:00
Ajay
134e89af00 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2023-11-06 16:07:46 -05:00
Ajay
5cc80f9066 Use dearrow thumbnails in webhooks 2023-11-06 16:07:44 -05:00
Ajay Ramachandran
e1043aba05 Merge pull request #565 from mchangrh/ajay-has-good-tests
non-blocking coverage tests
2023-11-04 18:18:35 -04:00
Michael C
c0abedf67f non-blocking coverage tests 2023-11-04 18:03:05 -04:00
Ajay Ramachandran
d99b7dc2c6 Merge pull request #563 from ajayyy/dependabot/npm_and_yarn/babel/traverse-7.23.2
Bump @babel/traverse from 7.18.6 to 7.23.2
2023-11-02 15:31:11 -04:00
Ajay
579e2b90a3 Make chapters easier to submit 2023-10-29 10:51:37 -04:00
Ajay
3708d293dc Add warning when locked title probably outdated 2023-10-27 00:39:36 -04:00
dependabot[bot]
077a9ecc50 Bump @babel/traverse from 7.18.6 to 7.23.2
Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.18.6 to 7.23.2.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse)

---
updated-dependencies:
- dependency-name: "@babel/traverse"
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-18 05:31:40 +00:00
Ajay Ramachandran
5714f51ac0 Merge pull request #561 from mchangrh/test-helpers
long overdue test helpers (partial)
2023-10-15 02:18:31 -04:00
Michael C
68bb39c409 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into test-helpers 2023-10-15 00:31:09 -04:00
Ajay
9dd8b28812 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2023-10-02 19:56:12 -04:00
Ajay
a659048afe Hide downvotes titles 2023-10-02 19:56:08 -04:00
Michael C
3c6803fb62 getViewsForUser 2023-09-30 21:20:42 -04:00
Michael C
467443a03f fix typings for getSubmissionUUID, update getStatus 2023-09-30 19:08:23 -04:00
Michael C
d8b93dec00 getLockCategories sort categories 2023-09-29 00:45:43 -04:00
Michael C
26b3ea6a50 use partialDeepEquals for getLockCategories 2023-09-29 00:40:20 -04:00
Michael C
f72b1abf41 getLockCategories
- add insertLock
2023-09-28 23:44:14 -04:00
Michael C
53e5dcb2f0 addUserAsVIP
- add genAnonUser
2023-09-28 20:45:02 -04:00
Michael C
73e5ade529 generate random title 2023-09-28 03:57:06 -04:00
Michael C
31e1f5bc3c original as bool not string 2023-09-28 03:51:15 -04:00
Michael C
df40047a4b getUserInfo
- add info property to User
- add insertWarning, Ban
- add insertTitle, TitleVote, Thumbnail, ThumbnailVote
- simplified insertSegments with destructuring
2023-09-28 03:45:28 -04:00
Michael C
ad9344c92f getChapterNames fix length 2023-09-27 23:57:53 -04:00
Michael C
726983bb9b getChapterNames
- remove identifier from segmentGen
- add multiGenRandomValue
- add videoInfo query
2023-09-27 23:53:18 -04:00
Michael C
7364499f11 lockCategoriesHTTP
- highLoad
- compact getUserID
- add genRandomValue method
2023-09-27 23:19:25 -04:00
Michael C
5e3ec895d8 add videoID for segment inserter 2023-09-27 22:25:18 -04:00
Michael C
a9ef3815e2 add segment generator
- getIsUserVIP
- postClearCache
- update boilerplate
2023-09-27 22:21:42 -04:00
Michael C
964634dc51 update addFeatures
- add case_boilerplate
- add grantFeature query
2023-09-27 21:03:53 -04:00
Ajay Ramachandran
1e8970859f Merge pull request #559 from mini-bomba/✝️ℹ️🅿️
Replace "warning" with "tip" in responses from postWarning.ts
2023-09-27 20:40:34 -04:00
Michael C
4438ce7db6 add genUser frameworks, start fixing tests
transformative:
- getUserID
- redisTest
- reputation

mocha test reconfig:
- etag
- getIP
- userCounter
- validateVideoIDs
2023-09-27 20:18:35 -04:00
Ajay
86ea0f582b Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2023-09-27 20:09:16 -04:00
Ajay
e329bccca5 Remove shuffling for thumbnails 2023-09-27 20:09:15 -04:00
Ajay Ramachandran
1275afa25b Merge pull request #560 from mchangrh/no-empty-warnings
disallow empty new warnings
2023-09-27 15:17:25 -04:00
Michael C
1b5a079bbd disallow empty new warnings 2023-09-27 15:09:35 -04:00
Ajay
ad666ff487 Don't allow random time after 90% of video if no endcard submitted 2023-09-24 16:53:55 -04:00
mini-bomba
7196155d3a Replace "Warning reason" with "Tip message" 2023-09-16 10:00:33 +02:00
mini-bomba
934ce79728 Replace "warning" with "tip" in responses from postWarning.ts 2023-09-12 23:40:39 +02:00
Ajay
65e7d24b7d Fix get branding by hash rong query 2023-09-09 19:07:50 -04:00
Ajay
d08c423c6a Verify old submissions when adding dearrow feature 2023-09-06 10:53:14 -04:00
Ajay
8361f602c7 Less arm 2023-09-04 02:52:04 -04:00
Ajay Ramachandran
1e3a50b884 Merge pull request #558 from mini-bomba/dearrow-bans
Fix Dearrow bans + some bug fixes
2023-09-04 02:43:39 -04:00
mini-bomba
55150cb301 do user & IP queries asynchronously in checkbanStatus()
Co-authored-by: Kendell R <KTibow@users.noreply.github.com>
2023-08-31 14:59:22 +02:00
mini-bomba
2015cf1488 DB migration: Hide any visible dearrow submissions from banned users 2023-08-29 16:38:41 +02:00
mini-bomba
141f105b79 fix dearrow bans 2023-08-29 16:38:41 +02:00
mini-bomba
c2a3630d49 create an isUserBanned utility function 2023-08-29 16:38:41 +02:00
mini-bomba
c77e71e66a it's called a ✝️ℹ️🅿️, not warning 2023-08-29 13:48:50 +02:00
Ajay
345c740fdc Fix local key regex 2023-08-22 12:00:59 -04:00
Ajay
d84276a86a Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2023-08-21 17:48:17 -04:00
Ajay
16c7ad5531 Return 404 for non existent feature flag 2023-08-21 17:48:13 -04:00
Ajay Ramachandran
7cb0a0705c Merge pull request #555 from mchangrh/shadowban-stats
show stats to shadowhidden users
2023-08-15 20:00:09 -04:00
Michael C
4600b8a599 show stats to shadowhidden users 2023-08-15 19:45:17 -04:00
Ajay
e9e1fd5228 Require time when generating key 2023-08-06 13:42:33 -04:00
Ajay
48fa55cc7a Add feature flag endpoint 2023-08-05 23:01:24 -04:00
Ajay
ecfc2c14c8 Remove minimum submission duration for mutes 2023-08-05 13:59:02 -04:00
Ajay
f58da275eb Fix group by not working on postgres 2023-08-04 14:36:08 -04:00
Ajay
0723503a98 Add DeArrow submitter feature 2023-08-04 14:17:41 -04:00
Ajay
9d1af3bdff Verify old submissions when you become verified 2023-08-04 14:15:46 -04:00
Ajay
b3cec20215 Better handling of verification for self downvotes 2023-08-04 13:53:23 -04:00
Ajay
b02134c016 Don't send angle brackets 2023-08-04 13:15:43 -04:00
Ajay
c3c8f38423 Rename var to be more clear 2023-08-03 01:50:50 -04:00
Ajay
1dbb393e4d Fix type error in tests 2023-08-03 01:16:57 -04:00
Ajay
dfa4578d28 Better token generation 2023-08-03 00:58:01 -04:00
Ajay
99cb22a5e6 Also clear branding cache when clearing segment cache 2023-07-29 18:44:52 -04:00
Ajay
665b91eb65 Revert distinct selection change as it seems to be misbehaving 2023-07-27 03:04:46 -04:00
Ajay Ramachandran
e942ac5e22 Merge pull request #549 from mini-bomba/voting-requirements
Make voting requirements more strict
2023-07-26 16:06:18 -04:00
Ajay Ramachandran
83b561d943 Merge pull request #548 from mchangrh/restic-update
change container to do chmod in builder
2023-07-26 16:03:49 -04:00
Ajay
f0b0217c78 Fix distinct query on postgres 2023-07-26 16:02:21 -04:00
Ajay
d23e9b9940 Only show one title/thumbnail per userID 2023-07-26 15:19:22 -04:00
Ajay
4b214767a0 Add buildx 2023-07-25 11:49:33 -04:00
Ajay
8c687934c2 build arm images 2023-07-25 11:36:59 -04:00
Ajay
f63fa09605 Handle exceptions, and prevent crashing from unhandled exceptions 2023-07-24 21:25:18 -04:00
Ajay
4e93a007c2 Remove unnecessary call in userInfo 2023-07-24 14:55:31 -04:00
Ajay
2fc31655ff Add different max for private db connection 2023-07-24 13:56:09 -04:00
Ajay
79515ccc8b Add unlocking to long title error 2023-07-23 23:45:02 -04:00
Ajay
b6f29b8b6d Fix shadow ban test 2023-07-23 23:35:50 -04:00
Ajay
a52ecf2d37 Add more unlock calls 2023-07-23 23:32:38 -04:00
Ajay
8d518b184b Change default lock timeout 2023-07-23 23:30:17 -04:00
Ajay
3924a65e02 Don't use locks when redis disabled 2023-07-23 23:28:41 -04:00
Ajay
a4de94bede Remove leftover timeout 2023-07-23 23:28:26 -04:00
Ajay
8bcc781da7 Add locks to different write operations 2023-07-23 23:21:50 -04:00
Ajay
b2081fe155 Add unique constraint for titles 2023-07-23 22:53:14 -04:00
Ajay
ea80a413ba Add postgres private db stats 2023-07-23 14:26:25 -04:00
Ajay
528f24a431 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2023-07-23 14:01:50 -04:00
Ajay
0463165f1a Add timing trace to set username 2023-07-23 14:01:49 -04:00
Ajay Ramachandran
38b7ddfd07 Merge pull request #553 from ajayyy/dependabot/npm_and_yarn/word-wrap-1.2.4
Bump word-wrap from 1.2.3 to 1.2.4
2023-07-19 01:08:16 -04:00
dependabot[bot]
79bac69c41 Bump word-wrap from 1.2.3 to 1.2.4
Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
- [Commits](https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4)

---
updated-dependencies:
- dependency-name: word-wrap
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-19 03:10:24 +00:00
Ajay
85fc0477ad Fix type check for warning duplicate 2023-07-17 23:38:52 -04:00
Ajay
a5501b9655 Fix user info not checking warning type 2023-07-17 22:53:12 -04:00
Ajay
e9fcf6b445 Add seperate type for dearrow warning
Also add dearrow warning reason as option for user info
2023-07-17 22:42:29 -04:00
Ajay
808066a5ed Look at -1 votes for branding sb segments 2023-07-17 19:36:58 -04:00
Ajay
93f4cfd82d Add option to return userID in branding call 2023-07-16 15:35:22 -04:00
Ajay
d030de83bd Add leaderboard for dearrow 2023-07-07 14:32:45 -04:00
Ajay
d1d2b011f8 Add max title length 2023-07-06 16:36:37 -04:00
Ajay
d2f8e3aee4 Fix shadow hide video branding logic 2023-07-06 14:53:48 -04:00
Ajay
2e29666781 Remove mysql code 2023-07-05 01:25:38 -04:00
Ajay
8b418c8851 Add hiding dearrow submissions in ban code 2023-07-05 01:23:48 -04:00
Ajay
5f80562772 Make dearrow verification easier to get 2023-06-28 22:12:32 -04:00
Ajay
69db87f5e1 Fix 0 second submissions not allowed 2023-06-23 23:05:52 -04:00
Ajay
fa6919a1d0 Add branding stats 2023-06-14 19:50:26 -04:00
Ajay
633f128e90 Fix voting on an existing submission not working. 2023-06-13 00:12:16 -04:00
Ajay
9f7fa53b14 Fix sort order 2023-06-12 11:51:17 -04:00
Ajay
bbb7102e37 Derank original submissions 2023-06-12 11:41:57 -04:00
Ajay
3bb8d5b58b Add verification where new users start with lower votes 2023-06-10 12:35:43 -04:00
Ajay
1cacb2dd69 Fix random time calculator for starting empty segment 2023-06-08 18:22:26 -04:00
Ajay
fe185234cf Add fallback video duration when finding random timestamp 2023-06-08 18:05:40 -04:00
Ajay
ef3e48ec24 Send video duration if known 2023-06-08 15:28:37 -04:00
mini-bomba
777944665d Make voting requirements more strict
This aims to reduce the amount of false votes by users with no valid segments of the category they're voting for.
New tests included, one modified to work under new requirements.
Also merged userAbleToVote and ableToVote in voteOnSponsorTime.ts to skip unnecessary queries for VIPs.
2023-06-08 16:50:31 +02:00
Ajay
0932f63398 Await in post branding test case 2023-06-08 04:01:23 -04:00
Ajay
5834643ba0 Add random timestamp generation to get branding 2023-06-08 03:39:44 -04:00
Ajay
8e5be402e1 Fix VIP title and thumbnail unlock unlocking everything 2023-05-31 14:28:01 -04:00
Michael C
e253c7bb47 change container to do chmod in builder 2023-05-23 19:39:16 -04:00
Ajay
9129cee9f0 Fix tests 2023-05-21 20:12:17 -04:00
Ajay
39fcdb1d95 Allow more chapter names to appear in suggestions 2023-05-21 20:03:53 -04:00
Ajay
8d1025e17d Add title and thumbnails to user stats 2023-05-09 23:53:18 -04:00
Ajay
6f0abddd3e Reenable locks 2023-04-28 14:15:18 -04:00
Ajay
a1b5c38e5a Disable lock tests for now 2023-04-17 19:38:31 -04:00
Ajay
8db898fab5 Add pool status to branding header 2023-04-10 18:21:52 -04:00
Ajay
940cacfb0a Add pool details to postgres stats 2023-04-07 15:55:29 -04:00
Ajay
69a54f64b4 More specific redis error 2023-04-07 14:39:38 -04:00
Ajay
9600f56830 Fix 500 in tracing 2023-04-07 14:38:57 -04:00
Ajay
4e59526b4d Add missing semicolon 2023-04-07 14:31:15 -04:00
Ajay
42f2eb5eae Add traces to branding endpoint 2023-04-07 14:31:08 -04:00
Ajay
e1a607ba39 Add sb server host as response header 2023-04-07 12:47:08 -04:00
Ajay
8a236d66ed Fix video labels hash key error 2023-04-05 18:02:47 -04:00
Ajay
4a10faaea3 Add cb tables to db dump 2023-03-31 17:57:56 -04:00
Ajay
589b7d4e3e Disable branding locks for now 2023-03-31 15:08:28 -04:00
Ajay
a52feee25e Fix unlocking all submissions 2023-03-31 15:07:34 -04:00
Ajay Ramachandran
d6a12a5e99 Merge pull request #545 from ajayyy/clickbait
Clear query cache for branding
2023-03-29 00:33:27 -04:00
Ajay
4696ce8d01 Clear query cache for branding 2023-03-29 00:32:29 -04:00
Ajay Ramachandran
bffc10e38f Merge pull request #534 from ajayyy/clickbait
Clickbait
2023-03-27 00:54:52 -04:00
Ajay
dde12bcc43 Fix wrong branch for github workflow 2023-03-19 00:41:29 -04:00
Ajay
7921bc4582 Remove chapters free test 2023-03-19 00:25:59 -04:00
Ajay
0b830610e9 Fix chapters duplicate check 2023-03-19 00:25:22 -04:00
Ajay
b6e9f92da8 Free chapters 2023-03-18 19:15:50 -04:00
Ajay
d4c4dbffcc Change video label cache to 3 chars 2023-03-18 00:36:05 -04:00
Ajay Ramachandran
5c549b5295 Merge pull request #544 from mchangrh/token-test
increase coverage for tokenUtils
2023-03-12 18:50:11 -04:00
Michael C
acae9da06c increase coverage for tokenUtils 2023-03-12 16:30:08 -04:00
Ajay Ramachandran
1f939116a4 Merge pull request #543 from mchangrh/unban-fix
fix unban query hitting limit, use number as type
2023-02-25 14:11:17 -05:00
Michael C
8495a9d6c0 fix unban query hitting limit, use number as type 2023-02-25 00:04:15 -05:00
Ajay Ramachandran
d76ee7cd22 Merge pull request #541 from mchangrh/etagTest
add etag and other tests
2023-02-22 01:38:41 -05:00
Michael C
436e75e3e6 add explicit test checks in reset 2023-02-22 01:15:49 -05:00
Michael C
7ba654e476 remove tests for maxNumberOfActiveWarnings 2023-02-22 00:35:58 -05:00
Ajay Ramachandran
f4286b15a1 Merge pull request #542 from mchangrh/warning-webhook
add warning webhook
2023-02-22 00:12:30 -05:00
Michael C
76ce1017ea add warning webhook 2023-02-22 00:08:27 -05:00
Michael C
780555e9df add ignores for getTotalStats 2023-02-21 20:16:25 -05:00
Michael C
79b7b6ea4c add highLoad tests 2023-02-21 20:10:01 -05:00
Michael C
80de71a68f add misc 400 tests 2023-02-21 20:09:57 -05:00
Michael C
4b8bc418ba clean up getCWSUsers 2023-02-21 20:09:38 -05:00
Michael C
f4537160de split postSkipSegments into stubbed 400 2023-02-21 20:09:13 -05:00
Michael C
900fa9f64e add test ignores 2023-02-21 17:00:53 -05:00
Michael C
e6f54f11f0 decompose postSkipSegments more 2023-02-21 17:00:23 -05:00
Michael C
6296761fe4 postSkipSegments improvements
- fix 80% check from same user
- split test cases into multiple files for easier viewing
2023-02-21 03:25:46 -05:00
Michael C
820a7eb02f simplify postWarning 2023-02-21 03:25:02 -05:00
Michael C
c6795a783d fix getCWS util 2023-02-21 03:24:32 -05:00
Michael C
37a1c7e88d used shared random gen for tests 2023-02-21 03:24:07 -05:00
Michael C
31a460e750 fix countcontributingusers 2023-02-20 22:56:38 -05:00
Michael C
1bda331b0c add new CWS user parsing method 2023-02-20 22:22:33 -05:00
Michael C
72fb4eb6ec add more tests for coverage 2023-02-20 22:22:33 -05:00
Michael C
d04230a1c4 reset postgres and redis between test runs 2023-02-20 22:22:33 -05:00
Michael C
f70a26009c add ignore clauses to tests 2023-02-20 22:22:33 -05:00
Michael C
c84eb839a0 clean up immediate cache after every run
run after codecov

confirm cache deletion

remove cache cleanup
2023-02-20 22:22:32 -05:00
Ajay Ramachandran
df279cf48a Adjust ip logging fix threshold 2023-02-20 18:57:19 -05:00
Michael C
cdc080b58b skip etag tests if no redis 2023-02-20 16:03:46 -05:00
Michael C
c586c9a7e7 add etag tests
- add shadowban self test
- add init and -it to docker runs
2023-02-20 15:56:08 -05:00
Ajay Ramachandran
81b0c27180 Merge pull request #540 from mchangrh/workflow
simplify workflows, use cache
2023-02-18 22:33:00 -05:00
Michael C
bff05dccaa simplify workflows, use cache 2023-02-18 03:12:50 -05:00
Ajay Ramachandran
9c438602f8 Add codecov config 2023-02-18 02:42:08 -05:00
Ajay
19ebca86c9 Fix video branding not being awaited 2023-02-18 02:33:22 -05:00
Ajay Ramachandran
f48fb6c3f6 Merge pull request #539 from mchangrh/nyc
run nyc for codecov
2023-02-18 00:48:39 -05:00
Michael C
4a90ba8992 run sqlite and postgres coverage 2023-02-18 00:36:45 -05:00
Michael C
efc911a229 fix codecov 2023-02-18 00:30:21 -05:00
Ajay Ramachandran
2e3f4f8c70 Add codecov 2023-02-18 00:16:18 -05:00
Ajay Ramachandran
b95b6d8efe Merge pull request #538 from mchangrh/less-tempvip-perms
give less permissions to tempVIPs
2023-02-18 00:10:04 -05:00
Ajay Ramachandran
7985d131ef Merge pull request #537 from mchangrh/lenientSetUsername
make privateIDUsername check more lenient #532
2023-02-18 00:09:37 -05:00
Michael C
a384079562 more lenient privateIDUsername checks
- disallow username = privateID
- disallow username = other privateID on username table if length > minLength
2023-02-17 22:28:23 -05:00
Ajay
46c372a764 Unlock other segments when vip votes for new segment 2023-02-14 22:10:46 -05:00
Michael M. Chang
3281954019 Update src/routes/postSkipSegments.ts
Co-authored-by: mini-bomba <55105495+mini-bomba@users.noreply.github.com>
2023-02-08 12:21:58 -05:00
Michael C
aece615992 give less permissions to tempVIPs 2023-02-08 01:54:20 -05:00
Ajay
6448fbfbd8 Fix logger calls where this will be wrong 2023-02-05 13:27:18 -05:00
Ajay
c5426e5fc4 Fix reputation test 2023-02-04 18:43:08 -05:00
Ajay
3894d453a5 Improve performance of reputation query 2023-02-04 18:22:31 -05:00
Ajay
280e6684af Fix reputation using wrong date 2023-02-04 18:22:19 -05:00
Ajay
7361c7056b Print active db requests in redis errors 2023-02-04 15:12:22 -05:00
Ajay
2d751a0b21 Log response time limits 2023-02-04 14:13:49 -05:00
Ajay
399bda869f Add more detailed redis error message 2023-02-04 14:07:09 -05:00
Ajay Ramachandran
663bd96130 Fix forget sh file missing 2023-02-03 20:06:14 -05:00
Ajay
5b3f4b476e Update redis config 2023-02-03 12:31:30 -05:00
Michael C
b855eea349 make privateIDUsername check more lenient #532 2023-01-29 16:10:59 -05:00
Ajay
51d25cfc68 Ban users submitting from banned IPs 2023-01-29 13:53:08 -05:00
Ajay
f8f02d86d5 Fix shadow hidden requiring type 1 2023-01-29 13:15:05 -05:00
Ajay
cb7492628c Names for docker compose ci 2023-01-28 14:48:20 -05:00
Ajay
e69b61fb4c Fix shadow ban exiting early 2023-01-28 14:42:16 -05:00
Ajay
5c1b502a15 Fix ban users var not used 2023-01-28 14:04:14 -05:00
Ajay
d5c544f1ee Allow auto banning ips 2023-01-28 14:00:12 -05:00
Ajay
5426ae826e Add IP banning 2023-01-28 13:09:04 -05:00
Ajay Ramachandran
7911819cab Merge pull request #536 from mchangrh/sharedParser
use shared parseParams helper
2023-01-28 12:20:50 -05:00
Ajay Ramachandran
d8e0eac61b Use includes and check in sql usage 2023-01-28 12:18:34 -05:00
Michael C
74c0ba37e2 remove debug statements, fix shadowBanUser tests 2023-01-28 02:54:01 -05:00
Michael C
a64b8f99b7 use shared parseParams helper 2023-01-28 02:40:09 -05:00
Ajay
9cf2e1f0e9 Fix private db table removal and original title type 2023-01-28 02:31:49 -05:00
Ajay
10e9aef8cc use await in get branding test 2023-01-28 02:20:16 -05:00
Ajay Ramachandran
d07aac3a33 Merge branch 'master' into clickbait 2023-01-28 02:13:42 -05:00
Ajay
b91114165e use seperate queries 2023-01-28 02:12:33 -05:00
Ajay
36f1d15605 Add tests for get branding and fix issues
Also improve deep partial equals
2023-01-28 01:53:59 -05:00
dependabot[bot]
894cd48182 Bump luxon from 1.28.0 to 1.28.1 (#535)
Bumps [luxon](https://github.com/moment/luxon) from 1.28.0 to 1.28.1.
- [Release notes](https://github.com/moment/luxon/releases)
- [Changelog](https://github.com/moment/luxon/blob/master/CHANGELOG.md)
- [Commits](https://github.com/moment/luxon/compare/1.28.0...1.28.1)

---
updated-dependencies:
- dependency-name: luxon
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-28 01:22:05 -05:00
Ajay Ramachandran
1641a41b00 Merge pull request #533 from mchangrh/cache-control
add ETag to skipSegments byHash
2023-01-28 01:16:32 -05:00
Ajay
4d8ce40ef4 Add missing import 2023-01-27 22:42:46 -05:00
Ajay
07c683e8f0 Add vote/submission for titles and thumbnails 2023-01-27 22:36:29 -05:00
Ajay
d0a9168531 remove temp server outage error 2023-01-22 18:59:51 -05:00
Ajay
2ed23d7fcb Fix duplicate chapter issue
Fix https://github.com/ajayyy/SponsorBlockServer/issues/521
2023-01-21 21:52:39 -05:00
Michael C
e7a43d79ab optimize skipSegments, add eTag
- moved skipSegments parameter parsing to new file
- added oldGetVideoSponsorTimes to getSkipSegments.ts
2023-01-01 04:59:57 -05:00
Michael C
b792354ffb lock redis, postgres versions, no persistence in redis 2023-01-01 02:51:44 -05:00
Michael C
a613b68c66 add ETag to skipSegments byHash 2023-01-01 02:50:49 -05:00
Ajay
66c2be6012 remove hash and extra segment params 2022-12-30 15:39:45 -05:00
Ajay
2a7083b9ef Remove hash from result to save bandwidth 2022-12-30 15:07:59 -05:00
Ajay Ramachandran
928eef637a Merge pull request #532 from mchangrh/fix-privateIDUsername
fix privateIDUsername
2022-12-30 01:07:08 -05:00
Michael C
be03367557 fix privateIDUsername 2022-12-30 01:04:23 -05:00
Ajay Ramachandran
fd288dd330 Merge pull request #531 from ajayyy/dependabot/npm_and_yarn/json5-2.2.2
Bump json5 from 2.2.1 to 2.2.2
2022-12-30 00:47:01 -05:00
dependabot[bot]
0c00f7323d Bump json5 from 2.2.1 to 2.2.2
Bumps [json5](https://github.com/json5/json5) from 2.2.1 to 2.2.2.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v2.2.1...v2.2.2)

---
updated-dependencies:
- dependency-name: json5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-12-30 05:45:16 +00:00
Ajay Ramachandran
5a6ba891f9 Merge pull request #530 from mchangrh/privateIDUsername
add privateID username check
2022-12-30 00:44:51 -05:00
Michael C
90e5446078 add privateID username check
- bump AGPL to package-lock
2022-12-30 00:41:45 -05:00
Ajay Ramachandran
dc0bde0e36 Merge pull request #529 from mchangrh/sanitizeVideoID
Sanitize videoID and minimum UserID length
2022-12-27 17:10:27 -05:00
Michael C
7c2feb80bc videoID validation and userID min length 2022-12-27 01:45:50 -05:00
Ajay Ramachandran
fc607d0cb7 Specify only in package.json 2022-12-26 23:43:01 -05:00
Ajay Ramachandran
3fbcadc3a0 Update license in package.json 2022-12-26 23:24:46 -05:00
Ajay
7f7a3a37ec Relicense project to AGPL 2022-12-26 23:18:43 -05:00
Ajay
cc24a4902f Initial get branding 2022-12-23 16:56:27 -05:00
Ajay Ramachandran
d738e89f20 Merge pull request #528 from mchangrh/bumpInnertube
bump innertube clientVersion
2022-12-18 00:07:13 -05:00
Michael C
b591b7194e Merge branch 'bumpInnerTube' into sanitizeVideoID 2022-12-18 00:03:33 -05:00
Michael C
fc5b5ca72c use node 18 across all tests 2022-12-18 00:01:32 -05:00
Michael C
8d7b010a12 append missing number to version 2022-12-17 23:58:19 -05:00
Michael C
fc73f491fe bump innertube clientVersion 2022-12-17 23:56:36 -05:00
Michael C
2683c61995 add minUserIDLength config option 2022-12-17 23:35:13 -05:00
Ajay
cff2325aef use keep alive in disk cache and user counter 2022-12-05 17:06:00 -05:00
Ajay
d7d5618985 update sqlite 2022-12-05 17:04:08 -05:00
Ajay
4e3753d32c Only call user counter some of the time 2022-12-05 16:47:11 -05:00
Ajay
1202c264aa Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2022-12-04 19:54:46 -05:00
Ajay
89e122210e Remove extra hash 2022-12-04 19:54:44 -05:00
Ajay Ramachandran
aed0e38d2f Merge pull request #524 from mchangrh/submitPrivateVideo
add innertube tests for private videos
2022-12-04 14:59:28 -05:00
Ajay Ramachandran
665ad6fe50 Merge pull request #526 from mchangrh/bump-dependencies
update dependencies, finally bump to node 18
2022-12-04 14:59:13 -05:00
Ajay
992c65a39d Fix sqlite tests 2022-11-21 17:06:04 -05:00
Ajay
b6e62aa68f Add postgres request time stats 2022-11-21 16:48:16 -05:00
Michael C
1f844bf56a Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into submitPrivateVideo 2022-11-21 14:40:46 -05:00
Michael C
fa5f3b8a50 update dependencies, finally bump to node 18 2022-11-21 14:36:11 -05:00
Ajay
30ac91c537 Don't refetch reputation if under high db load 2022-11-20 19:17:47 -05:00
Ajay
e252411fe1 No time saved for chapter 2022-11-20 17:30:13 -05:00
Ajay
91fc56f59a Wait for redis to connect before starting server 2022-11-20 01:20:05 -05:00
Ajay
0cd808a2d9 Add high load checks to leaderboard pages 2022-11-20 00:50:32 -05:00
Ajay
87e38c8bc4 Show total stats if not under high load 2022-11-20 00:47:41 -05:00
Ajay
df76b5f053 Add max queue to redis 2022-11-20 00:23:22 -05:00
Ajay
71d30c0b51 change redis max response time default 2022-11-19 23:59:50 -05:00
Ajay
238ccc83d9 Stop writing if response time exceeds value 2022-11-19 23:58:55 -05:00
Ajay
9bd6e9df4f Add error catching in segment by hash 2022-11-19 23:35:46 -05:00
Ajay
7bdcb10994 Fix redis set limiting 2022-11-19 23:32:09 -05:00
Ajay
849ca52ef8 Allow disabling hash cache 2022-11-19 20:05:59 -05:00
Ajay
9e2e1343da Add timeout for all postgres requests 2022-11-15 14:19:15 -05:00
Ajay
4139bf8f8c lower active connections on error 2022-11-13 23:21:46 -05:00
Ajay
1fffd2e6ac Remove set limitation code 2022-11-13 17:01:32 -05:00
Ajay
a417299d3e Only limit connections for reads 2022-11-12 15:44:09 -05:00
Ajay
d3d53d0758 Allow no max redis connections 2022-11-12 15:35:07 -05:00
Ajay
517c9512e4 Make default have no max requests 2022-11-12 15:31:21 -05:00
Ajay
ed5e3373a5 Add max active postgres requests 2022-11-12 15:29:55 -05:00
Ajay
6c18579a78 Added back mention of video to lock message 2022-11-12 12:45:35 -05:00
Ajay
e6e8c8e5a1 Added suggestion to refresh for locks 2022-11-12 12:43:16 -05:00
Ajay
50743070de Clarify locked category error 2022-11-12 12:41:00 -05:00
Michael C
7fb68937d0 add innertube tests for private videos 2022-11-09 14:39:02 -05:00
Ajay
90e68caaf7 Add active connection limit to setEx as well 2022-11-08 22:09:03 -05:00
Ajay
0ead3892ba Fix write process time not being used 2022-11-08 00:01:44 -05:00
Ajay
2700b5b530 Add avg read and write for redis and write requests 2022-11-07 23:51:41 -05:00
Ajay
e1a5ca64f0 Add seperate config for stopping write redis connections 2022-11-07 23:04:18 -05:00
Ajay
98f202f6a9 Add max connection check to redis set 2022-11-07 22:51:26 -05:00
Ajay
ee436d982c Fix csv download not being blocked 2022-11-07 16:30:16 -05:00
Ajay
dc8c35695d Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2022-11-07 16:24:44 -05:00
Ajay
9b509e7289 Disable csv downloads 2022-11-07 16:24:43 -05:00
Ajay Ramachandran
eee44e611b Only create blank config if it doesn't exist 2022-11-01 14:21:33 -04:00
Ajay
5139c7aaf0 Fix tests 2022-10-30 17:07:25 -04:00
Ajay
2254e7f869 Fix license validation failing 2022-10-30 17:05:10 -04:00
Ajay
68d9d3cbde Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2022-10-29 21:04:01 -04:00
Ajay
571230db56 Stop spamming redis if it slows down 2022-10-29 21:03:34 -04:00
Ajay Ramachandran
9c5db6a958 Merge pull request #520 from mchangrh/update-actions
Update Github Actions
2022-10-28 17:08:20 -04:00
Ajay Ramachandran
6b1ecbe90e Merge pull request #463 from mchangrh/fullVideoLabels
Full Video Labels endpoint
2022-10-28 17:08:05 -04:00
Michael C
d83d620893 update actions 2022-10-28 17:00:01 -04:00
Michael C
db71af480d clear full video labels 2022-10-28 16:53:04 -04:00
Michael C
80c018c9d5 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into fullVideoLabels 2022-10-28 16:49:50 -04:00
Michael C
cc6c5980a1 videoLabelsHashKey 2022-10-28 16:49:10 -04:00
Ajay Ramachandran
9d7236282c Merge pull request #504 from mchangrh/more-coverage
More test coverage, more tests
2022-10-28 16:45:22 -04:00
Michael C
7f92ac961d clear label cache 2022-10-28 16:42:56 -04:00
Ajay
96db571a5e Fix request rate limit option not working 2022-10-27 20:00:04 -04:00
Ajay
ccd1321d24 Allow disabling redis rate limit 2022-10-27 16:50:35 -04:00
Michael C
19289a149b test against new chapters access 2022-10-27 01:47:12 -04:00
Michael C
622511c8fd Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into more-coverage 2022-10-27 01:38:08 -04:00
Ajay
c2acc6227b Don't kill program if can't connect to read server 2022-10-27 01:31:41 -04:00
Ajay
176f2ce7b9 Kill if db can't connect 2022-10-27 01:30:59 -04:00
Michael C
9286f16e7b add ingores to tokenUtils 2022-10-27 01:19:42 -04:00
Ajay
9e3d059d10 Stop postgres retries when over a threshold 2022-10-26 22:58:35 -04:00
Ajay
13ae4681cb Fix hashing empty value for patreon sign in 2022-10-26 12:56:40 -04:00
Ajay
ee56a8dea4 Last pool fail when timeout 2022-10-26 12:49:39 -04:00
Ajay
94eb37cb1c Count active postgres and redis requests 2022-10-26 01:31:29 -04:00
Ajay Ramachandran
0ced78d798 Merge pull request #515 from PeterDaveHello/patch-1
Leave no apk cache in the Docker image
2022-10-23 11:03:13 -04:00
Peter Dave Hello
f1005fe779 Leave no apk cache in the Docker image
This will make the Docker image tidier
2022-10-23 20:19:06 +08:00
Ajay
1e2437b993 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2022-10-22 13:32:49 -04:00
Ajay
a6275b3607 Add message about server outage 2022-10-22 13:32:48 -04:00
Ajay Ramachandran
ba27a8a056 Merge pull request #514 from Choromanski/feature/getTopUsers-fix-minutesSaved-calculation
Fixed minutesSaved typo
2022-10-22 10:19:27 -04:00
Brian Choromanski
10397fbde2 Fixed minutesSaved typo 2022-10-21 17:27:34 -04:00
Ajay
b5434ae234 expand chapter free access 2022-10-18 16:50:21 -04:00
Ajay Ramachandran
b52ca8b2a6 Merge pull request #513 from mchangrh/tokenValidation
add additional token validation
2022-10-13 09:53:29 -04:00
Michael C
e799821ad9 add additional token validation 2022-10-13 00:59:34 -04:00
Ajay
415bb31e36 Revert "Add concurrent request limit" 2022-10-11 11:59:53 -04:00
Ajay Ramachandran
eb3d733a34 Merge pull request #510 from mini-bomba/misc-fixes
Some fixes for voteOnSponsorTime.ts
2022-10-11 00:10:41 -04:00
Ajay
9386f25f9f Add read only redis ability 2022-10-09 16:10:46 -04:00
mini-bomba
ceaf9ec6f6 Fix linter warning 2022-10-08 09:09:19 +02:00
mini-bomba
d229003f6e Unlock the video on duration change detected when voting 2022-10-08 09:08:40 +02:00
mini-bomba
1becebdcd5 Actually pass the ignoreCache param, as the comment suggests 2022-10-08 09:04:37 +02:00
Ajay
b417241ca0 make permission reason not optional 2022-10-07 12:05:11 -04:00
Ajay
ee3d94e7b7 Add clearer chapter permission error 2022-10-07 12:04:44 -04:00
Ajay
b6da103c3d switch to just lower vote min 2022-10-05 23:15:01 -04:00
Ajay
52a7d7e791 allow locked to be in top list and chapter 2022-10-05 23:08:16 -04:00
Ajay
b63572ec43 Add chapter to top users 2022-10-05 22:00:12 -04:00
Ajay Ramachandran
66d5622393 Merge pull request #508 from mini-bomba/searchsegments-description
Make /searchSegments return the segment description
2022-10-01 09:53:29 -04:00
Ajay Ramachandran
b7fcd9ea39 Merge pull request #509 from mini-bomba/status-startTimes
Use different startTime variables for each processTime check
2022-10-01 09:53:07 -04:00
mini-bomba
c4af2449c3 Use different startTime variables for each processTime check
This should make `processTime` and `redisProcessTime` values from /api/status more accurate
2022-10-01 15:50:47 +02:00
mini-bomba
eb5458427d Make /searchSegments return the segment description 2022-10-01 13:46:27 +02:00
Michael C
95dd36a782 getUserInfo and free chapters tests 2022-09-30 22:58:49 -04:00
Michael C
67eb165b53 getSearchSegments tests 2022-09-30 22:58:37 -04:00
Michael C
d163b1d436 shadowban tests 2022-09-30 22:58:20 -04:00
Michael C
715d41fbb2 getStatus, token tests and mocks 2022-09-30 22:58:08 -04:00
Michael C
0b9e7029c5 minor optimizations 2022-09-30 22:57:33 -04:00
Michael C
9ef0eafac1 add istanbul exclusions 2022-09-30 22:56:59 -04:00
Michael C
d80be9e7b3 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into more-coverage 2022-09-30 19:36:58 -04:00
Michael C
968ffe785f Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into fullVideoLabels 2022-09-30 19:21:54 -04:00
Ajay Ramachandran
847f1bbabb Merge pull request #499 from mchangrh/getStatus-redis
add redis process time to getStatus
2022-09-29 16:52:16 -04:00
Ajay Ramachandran
ada32217d9 Merge pull request #503 from mchangrh/innerTubeDuration
add innerTube API, types and tests
2022-09-29 16:45:55 -04:00
Michael C
a8ddae131d Merge branch 'master' of github.com:ajayyy/SponsorBlockServer into more-coverage 2022-09-29 15:39:36 -04:00
Ajay Ramachandran
54e53f098e Merge pull request #506 from mini-bomba/userstats-chapters
Add Chapters to /userStats, ignore Chapters for time saved calcs
2022-09-28 12:27:11 -04:00
mini-bomba
ed251a047a Add a test case for getUserInfo.ts ignoring chapters for time saved calc 2022-09-28 18:18:41 +02:00
mini-bomba
601a17c969 Ignore chapters for saved time calculations in getUserInfo.ts 2022-09-28 18:07:39 +02:00
mini-bomba
771fa18731 Modify getUserStats test cases to include chapter counts 2022-09-28 17:59:04 +02:00
mini-bomba
27f7b6d3c7 Add chapter category & action type to getUserStats.ts
This also fixes chapters not being counted in the segment counts.
2022-09-28 17:58:18 +02:00
Michael C
55aa33aa6e add DiskCache to getPlayerData 2022-09-26 15:58:33 -04:00
Michael C
07926ada57 switch test videoID, remove useless import 2022-09-26 15:44:04 -04:00
Ajay
ea05284b1d Allow manual dispatch of generate sqlite base 2022-09-26 15:23:01 -04:00
Ajay Ramachandran
230191ece9 Merge pull request #473 from mchangrh/gha_b2-sync
add b2 syncing for sqlite base
2022-09-26 15:19:07 -04:00
Ajay
28448f99d9 Lock s3cmd-sync version 2022-09-26 15:17:38 -04:00
Michael C
c34de1baa4 add 4xx tests 2022-09-25 03:31:25 -04:00
Michael C
a469f2f382 add uniform parsing and catching for arrays, remove redundant check 2022-09-25 03:30:33 -04:00
Michael C
506b6570f3 add ignore next to catch errors 2022-09-25 03:29:31 -04:00
Michael C
8562dc2240 lint fix 2022-09-25 02:05:51 -04:00
Michael C
005ae2c9fb add ignores for impossible cases 2022-09-25 02:04:51 -04:00
Michael C
9ca087206e add token tests 2022-09-25 02:04:30 -04:00
Michael C
c0952c15c8 fix getTotalStats userCount 2022-09-24 23:08:36 -04:00
Michael C
47616711ce move patreon mock 2022-09-24 22:52:55 -04:00
Michael C
7457b51aa4 add getByHash tests, remove redundant check
- `{}` always returns true so the early exit is never taken
2022-09-24 22:51:52 -04:00
Michael C
a00048aaac add getIP test cases, misc others 2022-09-24 22:51:20 -04:00
Michael C
6499381b4f add coverage reports to PostgreSQL tests 2022-09-24 22:49:53 -04:00
Michael C
0a102c15fd add lockCategory tests and typo tweak 2022-09-24 22:48:48 -04:00
Michael C
e0be4744be fix tokenUtils tests, skip if not configured 2022-09-24 22:48:23 -04:00
Michael C
dd7656d143 add lockCategories tests, getUserInfo 2022-09-24 22:47:40 -04:00
Michael C
f683ed4f29 add userCounter mocks and rearrange webhook path 2022-09-24 22:47:18 -04:00
Michael C
3f470a72f5 add additional/missing tests 2022-09-24 22:46:35 -04:00
Michael C
f5bafa2868 add nyc output to gitignore 2022-09-24 22:46:16 -04:00
Michael C
b652102c42 move mocks to subfolder 2022-09-24 22:45:23 -04:00
Ajay Ramachandran
55db24ab74 Merge pull request #505 from mchangrh/tokenValidateRegex
add fast fails for local and gumroad license keys
2022-09-24 21:09:16 -04:00
Michael C
551e103158 add tregex for both patreon and gumroad 2022-09-24 20:13:35 -04:00
Michael C
8fc01ba138 add fast fails for local and gumroad license keys 2022-09-22 20:30:10 -04:00
Ajay
1c1496afbc Change free chapter to use historical rep 2022-09-22 14:50:48 -04:00
Ajay
7007ab05e1 Handle errors from redis store in request rate limit 2022-09-22 11:12:47 -04:00
Ajay
30bac658ed Remove old permission workaround 2022-09-21 21:52:55 -04:00
Ajay
f6f83fcbe4 Add concurrent request limit 2022-09-20 23:41:36 -04:00
Ajay
f6c68ec29c Add another option to get chapters submitting permission 2022-09-19 11:56:55 -04:00
Michael C
62a9b0eddd add innerTube as primary videoInfo endpoint
- drop videoInfo.genreUrl since it's always empty
- bump ts target to ES2021 for Promise.any
- fix mocks to return err: false
- get maxResThumbnail from static endpoint
2022-09-15 17:02:33 -04:00
Michael C
3c09033267 add innerTube API, types and tests 2022-09-14 00:33:52 -04:00
Ajay
2ecf4b3a9b Fix category votes to use category support to judge when not allowed 2022-09-12 10:59:26 -04:00
Ajay
94ca291460 Don't cut off early if last retry 2022-09-11 12:22:57 -04:00
Michael C
0e3eeece01 return -1 for unknown dbVersion 2022-09-08 16:38:05 -04:00
Michael C
00dae6d6a1 switch to reused promiseOrTimeout 2022-09-08 16:34:39 -04:00
Ajay
e84957a2c8 commit missing file 2022-09-08 15:04:33 -04:00
Ajay
1e66a2e57a Add option to disable fallback after failure 2022-09-08 15:02:56 -04:00
Michael C
9be9d05dbe add redis process time and add timeout clause 2022-09-07 23:43:14 -04:00
Ajay
072324f0ab Add permission request to image build action 2022-09-07 22:35:32 -04:00
Ajay
c1e5f0e117 Fix void being used in wrong context 2022-09-07 22:15:44 -04:00
Ajay
ae95f7e3ea Only give up on replica for last retry 2022-09-07 22:10:48 -04:00
Ajay
bd7dfc63ff Add eslint rules for dealing with promises 2022-09-07 20:01:11 -04:00
Ajay Ramachandran
0ca134dc8f Merge pull request #500 from mchangrh/fix-tests
fix tests
2022-09-07 12:03:05 -04:00
Michael C
d1d7675a8c test fixes
test fixes
- fix timeout in redis (by @ajayyy)
- allow "errors" in tempVIP test
- remove duplicate warning in postSkipSegments
- remove duplicate VIP in tempVIP
- run tests against different user once tempVIP removed
- fix typo in getHashCache fetching

syntax and wording
- use standard syntax in redisTest
- fix spacing in getLockReason
- typo in npm script name

test cases
- add getHashCache test case
- add more tests to redisTest

configuration
- update config to use redis timeout
- update docker-compose to use newest pinned version

Co-Authored-By: Ajay Ramachandran <dev@ajay.app>
2022-09-07 02:16:23 -04:00
Ajay
252e2305f2 Fix undefined redis timeout breaking redis 2022-09-07 01:39:26 -04:00
Ajay
9c72e20d1b test for changing chapter category 2022-09-07 01:31:38 -04:00
Ajay
ec41102f07 Better chapter name error and increase min size 2022-09-04 22:36:26 -04:00
Ajay
08ab7e816d Restrict changing chapters category 2022-09-02 17:48:47 -04:00
Ajay
f103a02a34 Don't check 80% for chapters 2022-09-02 17:24:10 -04:00
Ajay
b413795e45 Change chapter name suggestion requirements 2022-09-02 15:23:08 -04:00
Ajay
6a61747573 Allow chapter submission 2022-09-02 14:55:20 -04:00
Ajay
420317a18c rename access to license 2022-09-02 13:54:09 -04:00
Ajay
af2ef3d6a5 Add product link 2022-09-02 02:15:22 -04:00
Ajay Ramachandran
9f2d13780c Merge pull request #501 from ajayyy/chapter-auth
Chapter auth
2022-09-02 02:06:45 -04:00
Ajay
acec7e58e7 Add free chapters access 2022-09-01 03:21:14 -04:00
Ajay
7060c0ab0d Add access token system 2022-08-31 01:55:38 -04:00
Ajay Ramachandran
ab6fcb8943 delete unused directory 2022-08-26 20:49:31 -04:00
Ajay
cbf352173a throw error if query fails 2022-08-25 21:14:25 -04:00
Ajay
027ff694a0 Make redis timeout configurable 2022-08-25 20:44:16 -04:00
Ajay
9da1fc523a Parse float instead of int 2022-08-25 15:08:54 -04:00
Ajay
44d541bafe Don't use replica for is vip 2022-08-22 11:59:08 -04:00
Ajay
dad205e729 don't scan ratings dir for tests 2022-08-22 11:07:30 -04:00
Ajay
8dbfe17ee4 remove ratings tests 2022-08-22 11:04:33 -04:00
Ajay
38a418a37a Remove ratings code 2022-08-22 10:56:22 -04:00
Ajay
6be2f96f26 Make max tries configurable 2022-08-20 17:57:40 -04:00
Ajay
47a6a13bdb Remove unused statement timeout with pgbouncer 2022-08-20 01:56:13 -04:00
Ajay
525a23abfb Add max connections and idle timeout 2022-08-19 18:45:02 -04:00
Ajay
4f637daeaa best way to deal with annoyance 2022-08-19 15:48:03 -04:00
Ajay
9559628273 Fix error 2022-08-19 15:45:23 -04:00
Ajay
5a43f46ac0 Configurable expiry time 2022-08-19 15:40:32 -04:00
Ajay
c3d30b18e2 Increase postgres read timeout and make it configurable 2022-08-15 17:32:07 -04:00
Ajay
7cb58b946a Remove submission restriction for ci.json 2022-08-15 12:03:44 -04:00
Ajay
9306729fdc Remove submission restrictions for tests 2022-08-15 11:43:51 -04:00
Ajay
1ae4c9a349 Add hostname to status 2022-08-12 15:34:40 -04:00
Ajay
be204fe873 Lower postgres read timeout, raise statment timeout 2022-08-12 15:31:19 -04:00
Ajay
6804e7d7a8 Add logging for permission rejections 2022-08-12 15:26:20 -04:00
Ajay
f4c104215b Lower requirements 2022-08-12 15:11:50 -04:00
Ajay
479890fc0d Add default expiry to query cache
Resolves #461
2022-08-11 21:37:13 -04:00
Ajay
877c3b7107 Change submission requirements 2022-08-09 22:01:09 -04:00
Ajay
cd35a58f83 Fix typo 2022-07-31 21:08:23 -04:00
Ajay
cb1cc10278 Extend restriction to all categories 2022-07-31 21:05:39 -04:00
Ajay
6239e53091 Fix flaky test 2022-07-29 12:06:38 -04:00
Ajay
ef93c692e5 fix reputation query typo 2022-07-29 11:57:55 -04:00
Ajay
ee49689110 Ignore full in all reputation cases
Closes #490
2022-07-29 11:55:48 -04:00
Ajay
04eabd5141 Fix error 2022-07-29 11:49:08 -04:00
Ajay
da1ed70c66 adjust permissions and use parrallel processing 2022-07-29 11:47:28 -04:00
Ajay
186f07b20c change filler rules 2022-07-29 11:29:39 -04:00
Ajay
5e49ce22b2 new chat link 2022-07-28 16:59:23 -04:00
Ajay
af7634b498 Fix ad feature auth logic 2022-07-28 13:55:43 -04:00
Ajay
b9354e44ae Fix missing semicolon 2022-07-28 13:10:21 -04:00
Ajay
17a790b6d9 More accurate spam number 2022-07-28 13:00:58 -04:00
Ajay
46805f4830 Require permission for filler submissions 2022-07-28 12:22:49 -04:00
Ajay
954c3db649 Change postgres timeout values 2022-07-24 15:41:09 -04:00
Ajay
23add072f3 Wait for any successful query instead of just most recent 2022-07-24 15:40:40 -04:00
Ajay
db2f9e11f7 Remove warning about disapearing degments bug 2022-07-23 14:12:06 -04:00
Ajay
2983bdb616 Add warning about segments not appearing 2022-07-22 21:06:21 -04:00
Ajay
597b26ba7c Clear cache when submission rejected 2022-07-22 21:05:38 -04:00
Ajay
f93c197d05 Add timeout to shadowhiddenn ip 2022-07-22 20:56:29 -04:00
Ajay
9764c01428 Add timeout for replica requests on non replica too 2022-07-22 20:00:38 -04:00
Ajay
ad7080d801 Force replica if failed using normal
alternates now
2022-07-22 19:03:46 -04:00
Ajay
071aae5cf7 Add timeout for write too 2022-07-22 17:31:17 -04:00
Ajay
10491da7c2 Raise timeout 2022-07-22 17:27:32 -04:00
Ajay
b616ac990b Add statement timeout for read 2022-07-22 16:39:31 -04:00
Ajay
603bad4967 Add another warning test 2022-07-21 14:19:41 -04:00
Ajay
ddb73af515 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer 2022-07-21 00:15:42 -04:00
Ajay
c1d345441c Pin github actions 2022-07-21 00:15:40 -04:00
Ajay Ramachandran
e050a6eec3 Merge pull request #484 from mini-bomba/fix/requiredSegments-hidden
Fix (shadow)hidden segments not being sent when requested via requiredSegments + test cases
2022-07-20 20:04:24 -04:00
mini-bomba
b3c05bc606 Merge branch 'master' into fix/requiredSegments-hidden
# Conflicts:
#	src/routes/getSkipSegments.ts
2022-07-21 00:54:14 +02:00
Ajay
3203271fdf Allow removing your own warning 2022-07-20 18:52:27 -04:00
Ajay
6e1df18c38 Allow updating warning messages 2022-07-20 17:20:19 -04:00
Ajay
96a75a8335 Add retry logic to postgres requests
Maybe solves https://github.com/ajayyy/SponsorBlockServer/issues/487
2022-07-20 14:42:04 -04:00
Ajay
dd47f87616 Add more things to read from replica 2022-07-20 01:21:13 -04:00
Ajay
f1ed8eff84 Fix useReplica change breaking voting 2022-07-20 00:43:59 -04:00
Ajay
1e441c3ebf Only use read replica for shorter queries
Help with https://github.com/ajayyy/SponsorBlockServer/issues/487
2022-07-20 00:40:07 -04:00
Ajay
f4b66d30ec Use pool query since this should catch idle errors
https://github.com/brianc/node-postgres/issues/1324#issuecomment-623311914

Helps with https://github.com/ajayyy/SponsorBlockServer/issues/487
2022-07-20 00:31:51 -04:00
Ajay
288f7d45e7 Revert "Don't cache empty arrays"
This reverts commit 9ab939456b.
2022-07-20 00:23:02 -04:00
mini-bomba
4ac70d2d7e add test cases for getting (shadow)hidden segments with requiredSegments 2022-07-16 15:07:22 +02:00
mini-bomba
0f3efc6fb2 send hidden segments when requested via requiredSegments 2022-07-16 15:07:22 +02:00
Ajay
f2904da653 Fix type error 2022-07-15 00:26:22 -04:00
Ajay
b11f260377 Log error from reputation in build segment groups
Maybe help with #483
2022-07-15 00:23:55 -04:00
Ajay
9ab939456b Don't cache empty arrays
Maybe help with #483
2022-07-15 00:21:08 -04:00
Ajay
5c089dab13 don't crash from reputation 2022-07-14 17:51:26 -04:00
Ajay Ramachandran
bba1c7f965 Merge pull request #482 from mini-bomba/misc/voteOnSponsorTime
Misc changes to voteOnSponsorTime
2022-07-14 17:07:25 -04:00
mini-bomba
55a8b5d514 voteOnSponsorTime: add test cases for categoryVote as warned/banned user 2022-07-14 21:31:43 +02:00
mini-bomba
9c0f0d8e4f voteOnSponsorTime: simplify currentCategoryCount computation in categoryVote 2022-07-14 20:28:45 +02:00
mini-bomba
f24a1415da voteOnSponsorTime: check for VIP/ownSubmission before doing math in categoryVote 2022-07-14 20:24:22 +02:00
mini-bomba
70c98e0819 voteOnSponsorTime: add ban check to categoryVote 2022-07-14 20:22:44 +02:00
mini-bomba
39ad5fb62a voteOnSponsorTime: move warning check before call to categoryVote 2022-07-14 20:13:47 +02:00
Ajay Ramachandran
356edb1f4b Merge pull request #481 from mchangrh/update-deps
update dependencies, use native redis typings
2022-07-13 12:20:03 -04:00
Michael C
5b60243b22 update packages, use native redis typings 2022-07-13 00:29:40 -04:00
Ajay Ramachandran
9f5ac2d9b9 Merge pull request #477 from mchangrh/coverage-nyc
add instanbul/nyc test coverage
2022-07-12 23:14:35 -04:00
Ajay Ramachandran
972cb96259 Merge pull request #476 from mchangrh/fullvideo-revive-nonvip
add tests for #454
2022-07-12 23:14:03 -04:00
Ajay
c2b0ecd6f6 Add ability to add manually choose who can submit chapters 2022-07-06 00:11:45 -04:00
Ajay
47f460bb2c Fix non-sequencial reputation in getSkipSegments 2022-07-05 20:11:30 -04:00
Ajay
adca0256a0 Fix voting insert with postgres 2022-07-05 19:30:45 -04:00
Ajay
7d396f3782 Do more things in parallel in getSkipSegments 2022-07-05 19:23:02 -04:00
Ajay
8ed695bcdc Fix canSubmitChapter being filtered out 2022-07-04 23:45:52 -04:00
Ajay
f8c297ddfb Add canSubmitChapter and fix all userInfo functions running 2022-07-04 23:44:50 -04:00
Ajay
0f3df8db1b make temp vip as powerful as vip for submitting 2022-07-04 16:21:02 -04:00
Ajay
f9de547b95 Add malicious vote type for chapters 2022-07-04 16:18:58 -04:00
Ajay
cc953884d9 Don't count chapter for time saved 2022-07-04 01:10:52 -04:00
Ajay
ebee00322a remove client error listener completely 2022-06-30 18:11:02 -04:00
Ajay
a99da61039 Fetch user count right away 2022-06-30 17:56:06 -04:00
Ajay
edff48d258 Don't release client on client error 2022-06-30 17:50:15 -04:00
Ajay
3844404637 ctch client connection errors 2022-06-30 02:00:59 -04:00
Ajay
5057c86707 Fix read only db used by default 2022-06-30 01:38:58 -04:00
Ajay
b1b40d410f Prevent errors from double calling release 2022-06-30 01:37:50 -04:00
Ajay
de60415f55 more generous reputation 2022-06-28 18:14:12 -04:00
Michael C
931e3b8b11 add instanbul/nyc test coverage 2022-06-28 15:19:42 -04:00
Michael C
8560c3f673 add tests for #454 2022-06-28 15:02:09 -04:00
Ajay
54db2c8c10 Release client on error 2022-06-27 19:47:29 -04:00
Ajay
c6868fa839 Disable ssl 2022-06-27 19:35:50 -04:00
Ajay
86e61c778c Fix fail calculation 2022-06-25 12:30:16 -04:00
Ajay
e615d7c032 Fix warnings 2022-06-25 12:03:30 -04:00
Ajay
08003bc2f2 Switch postgres instances if there is a failure 2022-06-25 12:02:01 -04:00
Ajay
1a232600a1 Add option to cycle between multiple postgres instances 2022-06-25 01:41:45 -04:00
Ajay
a8d0336cae Don't crash on postgres errors 2022-06-24 17:20:48 -04:00
Ajay
e1d6fdfefb Remove service from index 2022-06-24 02:21:37 -04:00
Ajay
f8ef145bb8 fix collation index 2022-06-24 01:29:07 -04:00
Ajay
a187180388 Add new index 2022-06-24 01:24:55 -04:00
Ajay
749fa4bb95 Fix not all db config vars being used 2022-06-14 16:22:59 -04:00
Ajay
5c43750835 Allow ssl 2022-06-10 16:40:48 -04:00
Ajay Ramachandran
8ec44aff1a more cache time 2022-06-01 14:24:58 -04:00
Ajay Ramachandran
046a535ebc less server 2022-06-01 13:53:10 -04:00
Michael C
b7995832bc add b2 syncing for sqlite base 2022-05-26 21:19:27 -04:00
Michael C
6a826b63c9 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into fullVideoLabels 2022-05-09 02:42:18 -04:00
Michael C
65a661ca4d fix naming regression, simplify findCategory 2022-03-31 14:19:06 -04:00
Michael M. Chang
2fb7f4faa6 consistent function naming
Co-authored-by: Ajay Ramachandran <dev@ajay.app>
2022-03-31 14:05:52 -04:00
Michael C
ed560425a0 removed logging, fixed labelByHash test cases 2022-03-31 14:05:07 -04:00
Michael C
267320bc56 add filler and exclusive_access to category enum 2022-03-31 03:47:25 -04:00
Michael C
e6bf20937d endpoint + tests for getVideoLabels 2022-03-31 03:47:06 -04:00
252 changed files with 21038 additions and 8538 deletions

View File

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

3
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,3 @@
- [ ] 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
***

View File

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

View File

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

16
.github/workflows/error-server.yml vendored Normal file
View File

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

View File

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

View File

@@ -6,6 +6,7 @@ on:
- master
paths:
- databases/**
workflow_dispatch:
jobs:
make-base-db:
@@ -13,16 +14,28 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- run: npm install
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
cache: npm
- run: npm ci
- 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@v2
- uses: actions/upload-artifact@v4
with:
name: SponsorTimesDB.db
path: databases/sponsorTimes.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'

View File

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

View File

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

121
.github/workflows/test.yaml vendored Normal file
View File

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

6
.gitignore vendored
View File

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

14
.nycrc.json Normal file
View File

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

View File

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

View File

@@ -1,16 +1,16 @@
FROM node:16-alpine as builder
FROM node:18-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:16-alpine as app
FROM node:18-alpine as app
WORKDIR /usr/src/app
RUN apk add git postgresql-client
RUN apk add --no-cache git postgresql-client
COPY --from=builder ./node_modules ./node_modules
COPY --from=builder ./dist ./dist
COPY ./.git ./.git
COPY ./.git/ ./.git
COPY entrypoint.sh .
COPY databases/*.sql databases/
EXPOSE 8080
CMD ./entrypoint.sh
CMD ./entrypoint.sh

674
LICENSE
View File

@@ -1,21 +1,661 @@
MIT License
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2019 Ajay Ramachandran
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.
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:
Preamble
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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 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.
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/>.

27
LICENSE.old Normal file
View File

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

View File

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

24
ci.json
View File

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

9
codecov.yml Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,11 +0,0 @@
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;
}

View File

@@ -1,7 +0,0 @@
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;
}

View File

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

View File

@@ -1,15 +0,0 @@
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';
}

View File

@@ -1,317 +0,0 @@
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
}
}

View File

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

8249
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,49 +5,59 @@
"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 --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",
"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",
"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": "MIT",
"license": "AGPL-3.0-only",
"dependencies": {
"axios": "^0.24.0",
"better-sqlite3": "^7.4.5",
"cron": "^1.8.2",
"express": "^4.17.1",
"axios": "^1.12.1",
"better-sqlite3": "^11.2.1",
"cron": "^2.1.0",
"express": "^4.21.2",
"express-promise-router": "^4.1.1",
"express-rate-limit": "^6.3.0",
"express-rate-limit": "^6.7.0",
"form-data": "^4.0.4",
"lodash": "^4.17.21",
"pg": "^8.7.1",
"lru-cache": "^10.2.0",
"lz4-napi": "^2.2.0",
"pg": "^8.8.0",
"rate-limit-redis": "^3.0.1",
"redis": "^4.0.6",
"sync-mysql": "^3.0.1"
"redis": "^4.6.13",
"seedrandom": "^3.0.5"
},
"devDependencies": {
"@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",
"@istanbuljs/nyc-config-typescript": "^1.0.2",
"@types/better-sqlite3": "^7.6.2",
"@types/cron": "^2.0.0",
"@types/express": "^4.17.14",
"@types/lodash": "^4.14.189",
"@types/mocha": "^10.0.0",
"@types/node": "^18.11.9",
"@types/pg": "^8.6.5",
"@types/seedrandom": "^3.0.5",
"@types/sinon": "^10.0.13",
"@typescript-eslint/eslint-plugin": "^5.44.0",
"@typescript-eslint/parser": "^5.44.0",
"axios-mock-adapter": "^1.21.2",
"eslint": "^8.28.0",
"mocha": "^10.8.2",
"nodemon": "^3.1.9",
"nyc": "^15.1.0",
"sinon": "^14.0.2",
"ts-mock-imports": "^1.3.8",
"ts-node": "^10.4.0",
"typescript": "^4.5.2"
"ts-node": "^10.9.1",
"typescript": "^4.9.3"
},
"engines": {
"node": ">=10"
"node": ">=18"
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,8 +1,10 @@
import { Logger } from "../utils/logger";
import { IDatabase, QueryType } from "./IDatabase";
import { Client, Pool, PoolClient, types } from "pg";
import { IDatabase, QueryOption, QueryType } from "./IDatabase";
import { Client, Pool, QueryResult, 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) {
@@ -14,13 +16,77 @@ 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;
constructor(private config: Record<string, any>) {}
private poolRead: Pool;
private lastPoolReadFail = 0;
activePostgresRequests = 0;
readResponseTime: number[] = [];
writeResponseTime: number[] = [];
failedResponseTime: number[] = [];
maxStoredTimes = 200;
constructor(private config: DatabaseConfig) {}
async init(): Promise<void> {
this.pool = new Pool(this.config.postgres);
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}`);
}
}
if (!this.config.readOnly) {
if (this.config.createDbIfNotExists) {
@@ -43,7 +109,7 @@ export class Postgres implements IDatabase {
}
}
async prepare(type: QueryType, query: string, params?: any[]): Promise<any[]> {
async prepare(type: QueryType, query: string, params?: any[], options: QueryOption = {}): Promise<any> {
// Convert query to use numbered parameters
let count = 1;
for (let char = 0; char < query.length; char++) {
@@ -55,31 +121,86 @@ export class Postgres implements IDatabase {
Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`);
let client: PoolClient;
try {
client = await this.pool.connect();
const queryResult = await client.query({ text: query, values: params });
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": {
break;
}
}
} catch (err) {
Logger.error(`prepare (postgres): ${err}`);
} finally {
client?.release();
if (this.config.postgres.maxActiveRequests && this.isReadQuery(type)
&& this.activePostgresRequests > this.config.postgres.maxActiveRequests) {
throw new Error("Too many active postgres requests");
}
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;
}
}
} 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;
}
}
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;
}
}
private isReadQuery(type: string): boolean {
return type === "get" || type === "all";
}
private async createDB() {
@@ -98,7 +219,7 @@ export class Postgres implements IDatabase {
);
}
client.end();
client.end().catch(err => Logger.error(`closing db (postgres): ${err}`));
}
private async upgradeDB(fileNamePrefix: string, schemaFolder: string) {
@@ -134,4 +255,36 @@ export class Postgres implements IDatabase {
return result;
}
private updateResponseTime(type: string, start: number, customArray?: number[]): void {
const responseTime = Date.now() - start;
const array = customArray ?? (this.isReadQuery(type) ?
this.readResponseTime : this.writeResponseTime);
array.push(responseTime);
if (array.length > this.maxStoredTimes) array.shift();
}
getStats(): PostgresStats {
return {
activeRequests: this.activePostgresRequests,
avgReadTime: this.readResponseTime.length > 0 ? this.readResponseTime.reduce((a, b) => a + b, 0) / this.readResponseTime.length : 0,
avgWriteTime: this.writeResponseTime.length > 0 ? this.writeResponseTime.reduce((a, b) => a + b, 0) / this.writeResponseTime.length : 0,
avgFailedTime: this.failedResponseTime.length > 0 ? this.failedResponseTime.reduce((a, b) => a + b, 0) / this.failedResponseTime.length : 0,
pool: {
total: this.pool.totalCount,
idle: this.pool.idleCount,
waiting: this.pool.waitingCount
}
};
}
highLoad() {
return this.activePostgresRequests > this.config.postgres.highLoadThreshold;
}
shouldUseRedisTimeout() {
return this.activePostgresRequests < this.config.postgres.redisTimeoutThreshold;
}
}

View File

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

View File

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

View File

@@ -4,15 +4,27 @@ import { createServer } from "./app";
import { Logger } from "./utils/logger";
import { startAllCrons } from "./cronjob";
import { getCommit } from "./utils/getCommit";
import { connectionPromise } from "./utils/redis";
async function init() {
process.on("unhandledRejection", (error: any) => {
// eslint-disable-next-line no-console
console.dir(error?.stack);
process.exit(1);
});
await initDb();
process.on("uncaughtExceptions", (error: any) => {
// eslint-disable-next-line no-console
console.dir(error?.stack);
});
try {
await initDb();
await connectionPromise;
} catch (e) {
Logger.error(`Init Db: ${e}`);
process.exit(1);
}
// 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.
@@ -27,4 +39,4 @@ async function init() {
}).setTimeout(15000);
}
init();
init().catch((err) => Logger.error(`Index.js: ${err}`));

View File

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

53
src/middleware/etag.ts Normal file
View File

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

View File

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

View File

@@ -1,9 +1,9 @@
import { getIP } from "../utils/getIP";
import { getHash } from "../utils/getHash";
import { getHashCache } from "../utils/getHashCache";
import rateLimit, { RateLimitRequestHandler } from "express-rate-limit";
import rateLimit from "express-rate-limit";
import { RateLimitConfig } from "../types/config.model";
import { Request } from "express";
import { Request, RequestHandler } from "express";
import { isUserVIP } from "../utils/isUserVIP";
import { UserID } from "../types/user.model";
import RedisStore, { RedisReply } from "rate-limit-redis";
@@ -11,26 +11,32 @@ import redis from "../utils/redis";
import { config } from "../config";
import { Logger } from "../utils/logger";
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,
});
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();
}
}

View File

@@ -2,13 +2,20 @@ 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") {
axios.post(`${config.userCounterURL}/api/v1/addIP?hashedIP=${getHash(getIP(req), 1)}`)
.catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
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}`));
}
}
next();

81
src/routes/addFeature.ts Normal file
View File

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

View File

@@ -1,7 +1,5 @@
import { VideoID } from "../types/segments.model";
import { YouTubeAPI } from "../utils/youtubeApi";
import { APIVideoInfo } from "../types/youtubeApi.model";
import { config } from "../config";
import { getVideoDetails } from "../utils/getVideoDetails";
import { getHashCache } from "../utils/getHashCache";
import { privateDB } from "../databases/databases";
import { Request, Response } from "express";
@@ -20,15 +18,11 @@ 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 getYouTubeVideoInfo(videoID);
const videoInfo = await getVideoDetails(videoID);
return {
id: videoInfo?.data?.authorId,
name: videoInfo?.data?.author
id: videoInfo?.authorId,
name: videoInfo?.authorName
};
};

View File

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

View File

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

View File

@@ -5,7 +5,7 @@ import { config } from "../config";
import util from "util";
import fs from "fs";
import path from "path";
import { ChildProcess, exec, ExecOptions, spawn } from "child_process";
import { exec, ExecOptions } 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,6 +75,7 @@ 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();
@@ -95,10 +96,12 @@ function removeOutdatedDumps(exportPath: string): Promise<void> {
for (const tableName in tableFiles) {
const files = tableFiles[tableName].sort((a, b) => b.timestamp - a.timestamp);
for (let i = 2; i < files.length; i++) {
// remove old file
await unlink(files[i].file).catch((error: any) => {
Logger.error(`[dumpDatabase] Garbage collection failed ${error}`);
});
if (!latestDumpFiles.some((file) => file.fileName === files[i].file.match(/[^/]+$/)[0])) {
// remove old file
await unlink(files[i].file).catch((error: any) => {
Logger.error(`[dumpDatabase] Garbage collection failed ${error}`);
});
}
}
}
resolve();
@@ -123,7 +126,7 @@ export default async function dumpDatabase(req: Request, res: Response, showPage
if (showPage) {
res.send(`${styleHeader}
<h1>SponsorBlock database dumps</h1>${licenseHeader}
<h3>How this works</h3>
<s><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.
@@ -134,6 +137,11 @@ 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>
@@ -158,18 +166,23 @@ export default async function dumpDatabase(req: Request, res: Response, showPage
<hr/>
${updateQueued ? `Update queued.` : ``} Last updated: ${lastUpdate ? new Date(lastUpdate).toUTCString() : `Unknown`}`);
} else {
res.send({
dbVersion: await getDbVersion(),
lastUpdated: lastUpdate,
updateQueued,
links: latestDumpFiles.map((item:any) => {
return {
table: item.tableName,
url: `/database/${item.tableName}.csv`,
size: item.fileSize,
};
}),
});
try {
res.send({
dbVersion: await getDbVersion(),
lastUpdated: lastUpdate,
updateQueued,
links: latestDumpFiles.map((item:any) => {
return {
table: item.tableName,
url: `/database/${item.tableName}.csv`,
size: item.fileSize,
};
}),
});
} catch (e) {
Logger.error(e as string);
res.sendStatus(500);
}
}
await queueDump();
@@ -223,16 +236,16 @@ async function queueDump(): Promise<void> {
const fileName = `${table.name}_${startTime}.csv`;
const file = `${appExportPath}/${fileName}`;
await new Promise<string>((resolve) => {
await new Promise<string>((resolve, reject) => {
exec(`psql -c "\\copy (SELECT * FROM \\"${table.name}\\"${table.order ? ` ORDER BY \\"${table.order}\\"` : ``})`
+ ` TO '${file}' WITH (FORMAT CSV, HEADER true);"`, credentials, (error, stdout, stderr) => {
if (error) {
Logger.error(`[dumpDatabase] Failed to dump ${table.name} to ${file} due to ${stderr}`);
reject(`[dumpDatabase] Failed to dump ${table.name} to ${file} due to ${stderr}`);
}
resolve(error ? stderr : stdout);
});
})
});
dumpFiles.push({
fileName,
@@ -242,10 +255,10 @@ async function queueDump(): Promise<void> {
latestDumpFiles = [...dumpFiles];
lastUpdate = startTime;
updateQueued = false;
} catch(e) {
Logger.error(e as string);
} finally {
updateQueued = false;
updateRunning = false;
}
}

View File

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

377
src/routes/getBranding.ts Normal file
View File

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

View File

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

View File

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

35
src/routes/getConfig.ts Normal file
View File

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

View File

@@ -1,13 +1,23 @@
import { db } from "../databases/databases";
import { Request, Response } from "express";
import { Logger } from "../utils/logger";
export async function getDaysSavedFormatted(req: Request, res: Response): Promise<Response> {
const row = await db.prepare("get", 'SELECT SUM(("endTime" - "startTime") / 60 / 60 / 24 * "views") as "daysSaved" from "sponsorTimes" where "shadowHidden" != 1', []);
try {
const row = await db.prepare("get", 'SELECT SUM(("endTime" - "startTime") / 60 / 60 / 24 * "views") as "daysSaved" from "sponsorTimes" where "shadowHidden" != 1', []);
if (row !== undefined) {
//send this result
return res.send({
daysSaved: row.daysSaved.toFixed(2),
});
if (row !== undefined) {
//send this result
return res.send({
daysSaved: row.daysSaved?.toFixed(2) ?? "0",
});
} else {
return res.send({
daysSaved: 0
});
}
} catch (err) {
Logger.error(err as string);
return res.sendStatus(500);
}
}

View File

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

View File

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

View File

@@ -3,17 +3,12 @@ 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[] = 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 actionTypes: ActionType[] = parseActionTypes(req, [ActionType.Skip, ActionType.Mute]);
if (!videoID || !Array.isArray(actionTypes)) {
//invalid request
return res.sendStatus(400);
@@ -33,7 +28,7 @@ export async function getLockCategories(req: Request, res: Response): Promise<Re
categories,
actionTypes
});
} catch (err) {
} catch (err) /* istanbul ignore next */{
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -3,6 +3,7 @@ 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,
@@ -44,13 +45,12 @@ 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[] = 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 actionTypes: ActionType[] = parseActionTypes(req, [ActionType.Skip, ActionType.Mute]);
if (!Array.isArray(actionTypes)) {
//invalid request
return res.sendStatus(400);
}
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) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -2,9 +2,8 @@ import { db } from "../databases/databases";
import { Logger } from "../utils/logger";
import { Request, Response } from "express";
import { Category, VideoID, ActionType } from "../types/segments.model";
import { config } from "../config";
import { filterInvalidCategoryActionType, parseActionTypes, parseCategories } from "../utils/parseParams";
const categorySupportList = config.categorySupport;
interface lockArray {
category: Category;
locked: number,
@@ -13,61 +12,19 @@ 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;
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 = (categories.length === 0 )
? possibleCategories
: categories.filter(x =>
possibleCategories.includes(x));
const actionTypes = parseActionTypes(req, [ActionType.Skip, ActionType.Mute]);
const categories = parseCategories(req, []);
if (!videoID || !Array.isArray(actionTypes)) {
//invalid request
return res.sendStatus(400);
}
// 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(", "));
// only take valid categories
const searchCategories = filterInvalidCategoryActionType(categories, actionTypes);
try {
// Get existing lock categories markers
@@ -115,7 +72,7 @@ export async function getLockReason(req: Request, res: Response): Promise<Respon
}
return res.send(results);
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return res.sendStatus(500);
}

106
src/routes/getMetrics.ts Normal file
View File

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

26
src/routes/getReady.ts Normal file
View File

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

View File

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

View File

@@ -2,6 +2,8 @@ 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;
@@ -14,7 +16,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" FROM "sponsorTimes"
`SELECT "UUID", "timeSubmitted", "startTime", "endTime", "category", "actionType", "votes", "views", "locked", "hidden", "shadowHidden", "userID", "description" FROM "sponsorTimes"
WHERE "videoID" = ? AND "service" = ? ORDER BY "timeSubmitted"`,
[videoID, service]
) as Promise<DBSegment[]>;
@@ -73,25 +75,13 @@ async function handleGetSegments(req: Request, res: Response): Promise<searchSeg
return false;
}
// Default to sponsor
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]
: [];
const categories: Category[] = parseCategories(req, []);
if (!Array.isArray(categories)) {
res.status(400).send("Categories parameter does not match format requirements.");
return false;
}
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];
const actionTypes: ActionType[] = parseActionTypes(req, [ActionType.Skip]);
if (!Array.isArray(actionTypes)) {
res.status(400).send("actionTypes parameter does not match format requirements.");
return false;
@@ -128,12 +118,7 @@ async function handleGetSegments(req: Request, res: Response): Promise<searchSeg
const segments = await getSegmentsFromDBByVideoID(videoID, service);
if (segments === null || segments === undefined) {
res.sendStatus(500);
return false;
}
if (segments.length === 0) {
if (!segments?.length) {
res.sendStatus(404);
return false;
}
@@ -155,6 +140,7 @@ 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]) {
@@ -187,6 +173,7 @@ async function endpoint(req: Request, res: Response): Promise<Response> {
return res.send(segmentResponse);
}
} catch (err) {
/* istanbul ignore next */
if (err instanceof SyntaxError) {
return res.status(400).send("Invalid array in parameters");
} else return res.sendStatus(500);

View File

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

View File

@@ -7,7 +7,7 @@ const isValidSegmentUUID = (str: string): boolean => /^([a-f0-9]{64}|[a-f0-9]{8}
async function getSegmentFromDBByUUID(UUID: SegmentUUID): Promise<DBSegment> {
try {
return await db.prepare("get", `SELECT * FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
} catch (err) {
} catch (err) /* istanbul ignore next */ {
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 (UUIDs.length > 10) UUIDs = UUIDs.slice(0, 10);
if (!Array.isArray(UUIDs) || !UUIDs) {
if (!Array.isArray(UUIDs) || !UUIDs?.length) {
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) {
} catch (err) /* istanbul ignore next */ {
if (err instanceof SyntaxError) { // catch JSON.parse error
return res.status(400).send("UUIDs parameter does not match format requirements.");
} else return res.sendStatus(500);

View File

@@ -2,7 +2,7 @@ import { Request, Response } from "express";
import { partition } from "lodash";
import { config } from "../config";
import { db, privateDB } from "../databases/databases";
import { skipSegmentsHashKey, skipSegmentsKey, skipSegmentGroupsKey, shadowHiddenIPKey } from "../utils/redisKeys";
import { skipSegmentsHashKey, skipSegmentsKey, skipSegmentGroupsKey, shadowHiddenIPKey, skipSegmentsLargerHashKey } from "../utils/redisKeys";
import { SBRecord } from "../types/lib.model";
import { ActionType, Category, DBSegment, HashedIP, IPAddress, OverlappingSegmentGroup, Segment, SegmentCache, SegmentUUID, Service, VideoData, VideoID, VideoIDHash, Visibility, VotableObject } from "../types/segments.model";
import { getHashCache } from "../utils/getHashCache";
@@ -11,36 +11,76 @@ import { Logger } from "../utils/logger";
import { QueryCacher } from "../utils/queryCacher";
import { getReputation } from "../utils/reputation";
import { getService } from "../utils/getService";
import { promiseOrTimeout } from "../utils/promise";
import { parseSkipSegments } from "../utils/parseSkipSegments";
import { getEtag } from "../middleware/etag";
import { shuffleArray } from "../utils/array";
import { Postgres } from "../databases/Postgres";
import { getRedisStats } from "../utils/redis";
async function prepareCategorySegments(req: Request, videoID: VideoID, service: Service, segments: DBSegment[], cache: SegmentCache = { shadowHiddenSegmentIPs: {} }, useCache: boolean): Promise<Segment[]> {
const shouldFilter: boolean[] = await Promise.all(segments.map(async (segment) => {
if (segment.votes < -1 && !segment.required) {
if (segment.required) {
return true; //required - always send
}
if (segment.hidden
|| segment.votes < -1
|| segment.shadowHidden === Visibility.MORE_HIDDEN) {
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.HIDDEN) {
if (segment.shadowHidden === Visibility.VISIBLE) {
return true;
}
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]) as Promise<{ hashedIP: HashedIP }[]>;
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = await QueryCacher.get(fetchData, shadowHiddenIPKey(videoID, segment.timeSubmitted, service));
[videoID, segment.timeSubmitted, service], { useReplica: true }) as Promise<{ hashedIP: HashedIP }[]>;
try {
if (db.highLoad() || privateDB.highLoad()) {
Logger.error("High load, not handling shadowhide");
if (db instanceof Postgres && privateDB instanceof Postgres) {
Logger.error(`Postgres stats: ${JSON.stringify(db.getStats())}`);
Logger.error(`Postgres private stats: ${JSON.stringify(privateDB.getStats())}`);
}
Logger.error(`Redis stats: ${JSON.stringify(getRedisStats())}`);
return false;
}
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = promiseOrTimeout(QueryCacher.get(fetchData, shadowHiddenIPKey(videoID, segment.timeSubmitted, service)), 150);
} catch (e) {
// give up on shadowhide for now
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = null;
}
}
const ipList = cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted];
let ipList = [];
try {
ipList = await cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted];
} catch (e) {
Logger.error(`skipSegments: Error while trying to find IP: ${e}`);
if (db instanceof Postgres && privateDB instanceof Postgres) {
Logger.error(`Postgres stats: ${JSON.stringify(db.getStats())}`);
Logger.error(`Postgres private stats: ${JSON.stringify(privateDB.getStats())}`);
}
return false;
}
if (ipList?.length > 0 && cache.userHashedIP === undefined) {
//hash the IP only if it's strictly necessary
cache.userHashedIP = await getHashCache((getIP(req) + config.globalSalt) as IPAddress);
cache.userHashedIP = await cache.userHashedIPPromise;
}
//if this isn't their ip, don't send it to them
const shouldShadowHide = cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted]?.some(
const shouldShadowHide = ipList?.some(
(shadowHiddenSegment) => shadowHiddenSegment.hashedIP === cache.userHashedIP) ?? false;
if (shouldShadowHide) useCache = false;
@@ -73,9 +113,6 @@ 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;
@@ -84,7 +121,17 @@ 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)));
.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
}));
if (forcePoiAsSkip) {
processedSegments = processedSegments.map((segment) => ({
@@ -94,7 +141,7 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
}
return processedSegments;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
if (err) {
Logger.error(err as string);
return null;
@@ -103,7 +150,7 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
}
async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categories: Category[],
actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise<SBRecord<VideoID, VideoData>> {
actionTypes: ActionType[], trimUUIDs: number, requiredSegments: SegmentUUID[], service: Service): Promise<SBRecord<VideoID, VideoData>> {
const cache: SegmentCache = { shadowHiddenSegmentIPs: {} };
const segments: SBRecord<VideoID, VideoData> = {};
@@ -114,15 +161,11 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
}
try {
type SegmentWithHashPerVideoID = SBRecord<VideoID, { hash: VideoIDHash, segments: DBSegment[] }>;
type SegmentPerVideoID = SBRecord<VideoID, { segments: DBSegment[] }>;
categories = categories.filter((category) => !(/[^a-z|_|-]/.test(category)));
if (categories.length === 0) return null;
const segmentPerVideoID: SegmentWithHashPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service))
.reduce((acc: SegmentWithHashPerVideoID, segment: DBSegment) => {
const segmentPerVideoID: SegmentPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service))
.reduce((acc: SegmentPerVideoID, segment: DBSegment) => {
acc[segment.videoID] = acc[segment.videoID] || {
hash: segment.hashedVideoID,
segments: []
};
if (filterRequiredSegments(segment.UUID, requiredSegments)) segment.required = true;
@@ -133,16 +176,44 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
return acc;
}, {});
for (const [videoID, videoData] of Object.entries(segmentPerVideoID)) {
await Promise.all(Object.entries(segmentPerVideoID).map(async ([videoID, videoData]) => {
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))
const filteredSegments = (await prepareCategorySegments(req, videoID as VideoID, service, videoData.segments, cache, canUseCache))
.filter((segment: Segment) => categories.includes(segment?.category) && actionTypes.includes(segment?.actionType));
// Make sure no hash duplicates exist
if (trimUUIDs) {
const seen = new Set<string>();
for (const segment of filteredSegments) {
const shortUUID = segment.UUID.substring(0, trimUUIDs);
if (seen.has(shortUUID)) {
// Duplicate found, disable trimming
trimUUIDs = undefined;
break;
}
seen.add(shortUUID);
}
seen.clear();
}
data.segments = filteredSegments
.map((segment) => ({
category: segment.category,
actionType: segment.actionType,
segment: segment.segment,
UUID: trimUUIDs ? segment.UUID.substring(0, trimUUIDs) as SegmentUUID : segment.UUID,
videoDuration: segment.videoDuration,
locked: segment.locked,
votes: segment.votes,
description: segment.description
}));
if (forcePoiAsSkip) {
data.segments = data.segments.map((segment) => ({
...segment,
@@ -153,11 +224,11 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
if (data.segments.length > 0) {
segments[videoID] = data;
}
}
}));
return segments;
} catch (err) {
Logger.error(err as string);
} catch (err) /* istanbul ignore next */ {
Logger.error(`get segments by hash error: ${err}`);
return null;
}
}
@@ -166,13 +237,16 @@ async function getSegmentsFromDBByHash(hashedVideoIDPrefix: VideoIDHash, service
const fetchFromDB = () => db
.prepare(
"all",
`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]
`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 }
) as Promise<DBSegment[]>;
if (hashedVideoIDPrefix.length === 4) {
return await QueryCacher.get(fetchFromDB, skipSegmentsHashKey(hashedVideoIDPrefix, service));
} else if (hashedVideoIDPrefix.length === 5) {
return await QueryCacher.get(fetchFromDB, skipSegmentsLargerHashKey(hashedVideoIDPrefix, service));
}
return await fetchFromDB();
@@ -182,19 +256,20 @@ async function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): P
const fetchFromDB = () => db
.prepare(
"all",
`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]
`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 }
) as Promise<DBSegment[]>;
return await QueryCacher.get(fetchFromDB, skipSegmentsKey(videoID, service));
}
// Gets a weighted random choice from the choices array based on their `votes` property.
// Gets the best choice from the choices array based on their `votes` property.
// amountOfChoices specifies the maximum amount of choices to return, 1 or more.
// Choices are unique
// If a predicate is given, it will only filter choices following it, and will leave the rest in the list
function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOfChoices: number, filterLocked = false, predicate?: (choice: T) => void): T[] {
function getBestChoice<T extends VotableObject>(choices: T[], amountOfChoices: number, filterLocked = false, predicate?: (choice: T) => void): T[] {
//trivial case: no need to go through the whole process
if (amountOfChoices >= choices.length) {
return choices;
@@ -217,39 +292,22 @@ function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOf
}
//assign a weight to each choice
let totalWeight = 0;
const choicesWithWeights: TWithWeight[] = filteredChoices.map(choice => {
const boost = Math.min(choice.reputation, 4);
//The 3 makes -2 the minimum votes before being ignored completely
//this can be changed if this system increases in popularity.
const repFactor = choice.votes > 0 ? Math.max(1, choice.reputation + 1) : 1;
const weight = Math.exp(choice.votes * repFactor + 3 + boost);
totalWeight += Math.max(weight, 0);
const choicesWithWeights: TWithWeight[] = shuffleArray(filteredChoices.map(choice => {
const boost = choice.reputation;
const weight = choice.votes + boost;
return { ...choice, weight };
});
})).sort((a, b) => b.weight - a.weight);
// Nothing to filter for
if (amountOfChoices >= choicesWithWeights.length) {
return [...forceIncludedChoices, ...filteredChoices];
}
//iterate and find amountOfChoices choices
// Pick the top options
const chosen = [...forceIncludedChoices];
while (amountOfChoices-- > 0) {
//weighted random draw of one element of choices
const randomNumber = Math.random() * totalWeight;
let stackWeight = choicesWithWeights[0].weight;
let i = 0;
while (stackWeight < randomNumber) {
stackWeight += choicesWithWeights[++i].weight;
}
//add it to the chosen ones and remove it from the choices before the next iteration
for (let i = 0; i < amountOfChoices; i++) {
chosen.push(choicesWithWeights[i]);
totalWeight -= choicesWithWeights[i].weight;
choicesWithWeights.splice(i, 1);
}
return chosen;
@@ -258,23 +316,26 @@ function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOf
async function chooseSegments(videoID: VideoID, service: Service, segments: DBSegment[], useCache: boolean): Promise<DBSegment[]> {
const fetchData = async () => await buildSegmentGroups(segments);
const groups = useCache
const groups = useCache && config.useCacheForSegmentGroups
? await QueryCacher.get(fetchData, skipSegmentGroupsKey(videoID, service))
: await fetchData();
// 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);
return chosenGroups.map(//randomly choose 1 good segment per group and return them
group => getWeightedRandomChoice(group.segments, 1)[0]
let chosenGroups = getBestChoice(groups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Full);
chosenGroups = getBestChoice(chosenGroups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Poi);
return chosenGroups.map(// choose 1 good segment per group and return them
group => getBestChoice(group.segments, 1)[0]
);
}
//This function will find segments that are contained inside of eachother, called similar segments
//Only one similar time will be returned, randomly generated based on the sqrt of votes.
//Only one similar time will be returned, based on its score
//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
@@ -283,7 +344,8 @@ 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 (const segment of segments) {
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
if (segment.startTime >= cursor) {
currentGroup = { segments: [], votes: 0, reputation: 0, locked: false, required: false };
overlappingSegmentsGroups.push(currentGroup);
@@ -295,7 +357,7 @@ async function buildSegmentGroups(segments: DBSegment[]): Promise<OverlappingSeg
currentGroup.votes += segment.votes;
}
if (segment.userID) segment.reputation = Math.min(segment.reputation, await getReputation(segment.userID));
if (segment.userID) segment.reputation = Math.min(segment.reputation, (await reputationPromises[i]) || Infinity);
if (segment.reputation > 0) {
currentGroup.reputation += segment.reputation;
}
@@ -359,75 +421,59 @@ function splitPercentOverlap(groups: OverlappingSegmentGroup[]): OverlappingSegm
});
}
/**
*
* 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> {
async function getSkipSegments(req: Request, res: Response): Promise<Response> {
const videoID = req.query.videoID as VideoID;
if (!videoID) {
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;
return res.status(400).send("videoID not specified");
}
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 parseResult = parseSkipSegments(req);
if (parseResult.errors.length > 0) {
return res.status(400).send(parseResult.errors);
}
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 { categories, actionTypes, requiredSegments, service } = parseResult;
const segments = await getSegmentsByVideoID(req, videoID, categories, actionTypes, requiredSegments, service);
if (segments === null || segments === undefined) {
res.sendStatus(500);
return false;
return res.sendStatus(500);
} else if (segments.length === 0) {
return res.sendStatus(404);
}
if (segments.length === 0) {
res.sendStatus(404);
return false;
await getEtag("skipSegments", (videoID as string), service)
.then(etag => res.set("ETag", etag))
.catch(() => ({}));
return res.send(segments);
}
async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise<Response> {
const videoID = req.query.videoID as VideoID;
if (!videoID) {
return res.status(400).send("videoID not specified");
}
return segments;
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,
});
}
const filterRequiredSegments = (UUID: SegmentUUID, requiredSegments: SegmentUUID[]): boolean => {
@@ -437,25 +483,9 @@ 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,
endpoint,
handleGetSegments
getSkipSegments,
oldGetVideoSponsorTimes
};

View File

@@ -1,8 +1,10 @@
import { hashPrefixTester } from "../utils/hashPrefixTester";
import { getSegmentsByHash } from "./getSkipSegments";
import { Request, Response } from "express";
import { ActionType, Category, SegmentUUID, VideoIDHash, Service } from "../types/segments.model";
import { getService } from "../utils/getService";
import { VideoIDHash } from "../types/segments.model";
import { Logger } from "../utils/logger";
import { parseSkipSegments } from "../utils/parseSkipSegments";
import { getEtag } from "../middleware/etag";
export async function getSkipSegmentsByHash(req: Request, res: Response): Promise<Response> {
let hashPrefix = req.params.prefix as VideoIDHash;
@@ -11,68 +13,28 @@ export async function getSkipSegmentsByHash(req: Request, res: Response): Promis
}
hashPrefix = hashPrefix.toLowerCase() as VideoIDHash;
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 parseResult = parseSkipSegments(req);
if (parseResult.errors.length > 0) {
return res.status(400).send(parseResult.errors);
}
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");
const { categories, actionTypes, trimUUIDs, requiredSegments, service } = parseResult;
// Get all video id's that match hash prefix
const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, requiredSegments, service);
const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, trimUUIDs, requiredSegments, service);
if (!segments) return res.status(404).json([]);
try {
const hashKey = hashPrefix.length === 4 ? "skipSegmentsHash" : "skipSegmentsLargerHash";
await getEtag(hashKey, hashPrefix, service)
.then(etag => res.set("ETag", etag))
.catch(/* istanbul ignore next */ () => null);
const output = Object.entries(segments).map(([videoID, data]) => ({
videoID,
segments: data.segments,
}));
return res.status(output.length === 0 ? 404 : 200).json(output);
} catch (e) /* istanbul ignore next */ {
Logger.error(`skip segments by hash error: ${e}`);
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);
return res.status(500).send("Internal server error");
}
}

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