397 Commits

Author SHA1 Message Date
Ajay
5c61f1d366 Fix inspect command 2023-04-16 21:34:34 -04:00
Ajay
36352b0c8e Build debug 2023-04-16 21:23:01 -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
202 changed files with 13198 additions and 5742 deletions

View File

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

3
.github/pull_request_template.md vendored 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,9 +19,10 @@ on:
jobs:
build_container:
runs-on: ubuntu-latest
permissions:
packages: write
steps:
- name: Checkout
uses: actions/checkout@v3
- uses: actions/checkout@v3
- name: Docker meta
id: meta
uses: docker/metadata-action@v4

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@v3
- uses: actions/setup-node@v3
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@v3
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

@@ -2,24 +2,15 @@ name: Docker image builds
on:
push:
branches:
- master
- debug
workflow_dispatch:
jobs:
sb-server:
uses: ./.github/workflows/docker-build.yml
with:
name: "sb-server"
name: "sb-server-debug"
username: "ajayyy"
folder: "."
secrets:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
rsync-host:
needs: sb-server
uses: ./.github/workflows/docker-build.yml
with:
name: "rsync-host"
username: "ajayyy"
folder: "./containers/rsync"
secrets:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

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 }}

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

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

4
.gitignore vendored
View File

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

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

@@ -126,7 +126,6 @@
| channelID | TEXT | not null |
| title | TEXT | not null |
| published | REAL | not null |
| genreUrl | TEXT | not null |
| index | field |
| -- | :--: |
@@ -209,6 +208,7 @@
| userID | TEXT | not null |
| hashedIP | TEXT | not null |
| type | INTEGER | not null |
| originalVoteType | INTEGER | not null | # Since type was reused to also specify the number of votes removed when less than 0, this is being used for the actual type
| index | field |
| -- | :--: |

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 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.

23
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,7 +56,6 @@
]
}
],
"maxNumberOfActiveWarnings": 3,
"hoursAfterWarningExpires": 24,
"rateLimit": {
"vote": {
@@ -67,5 +69,12 @@
"max": 20,
"statusCode": 200
}
}
},
"patreon": {
"clientId": "testClientID",
"clientSecret": "testClientSecret",
"redirectUri": "http://127.0.0.1/fake/callback"
},
"minReputationToSubmitFiller": -1,
"minUserIDLength": 0
}

1
codecov.yml Normal file
View File

@@ -0,0 +1 @@
comment: false

View File

@@ -66,5 +66,6 @@
{
"name": "vipUsers"
}]
}
},
"minUserIDLength": 30 // minimum length of UserID to be accepted
}

View File

@@ -4,10 +4,10 @@ RUN apk add restic --repository http://dl-cdn.alpinelinux.org/alpine/latest-stab
COPY ./backup.sh /usr/src/app/backup.sh
RUN chmod +x /usr/src/app/backup.sh
COPY ./backup.sh /usr/src/app/forget.sh
COPY ./forget.sh /usr/src/app/forget.sh
RUN chmod +x /usr/src/app/forget.sh
RUN echo '30 * * * * /usr/src/app/backup.sh' >> /etc/crontabs/root
RUN echo '10 0 * * 1 /usr/src/app/forget.sh' >> /etc/crontabs/root
CMD crond -l 2 -f
CMD crond -l 2 -f

View File

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

View File

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

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,45 @@ CREATE INDEX IF NOT EXISTS "ratings_hashedVideoID"
CREATE INDEX IF NOT EXISTS "ratings_videoID"
ON public."ratings" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, service COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
--- userFeatures
CREATE INDEX IF NOT EXISTS "userFeatures_userID"
ON public."userFeatures" USING btree
("userID" COLLATE pg_catalog."default" ASC NULLS LAST, "feature" ASC NULLS LAST)
TABLESPACE pg_default;
-- titles
CREATE INDEX IF NOT EXISTS "titles_timeSubmitted"
ON public."titles" USING btree
("timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "titles_videoID"
ON public."titles" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "titles_hashedVideoID"
ON public."titles" USING btree
("hashedVideoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
-- thumbnails
CREATE INDEX IF NOT EXISTS "thumbnails_timeSubmitted"
ON public."thumbnails" USING btree
("timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "thumbnails_videoID"
ON public."thumbnails" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "thumbnails_hashedVideoID"
ON public."thumbnails" USING btree
("hashedVideoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;

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,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

@@ -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 --inspect 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;

6743
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,49 +5,56 @@
"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.1.3",
"better-sqlite3": "^8.0.1",
"cron": "^2.1.0",
"express": "^4.18.2",
"express-promise-router": "^4.1.1",
"express-rate-limit": "^6.3.0",
"express-rate-limit": "^6.7.0",
"form-data": "^4.0.0",
"lodash": "^4.17.21",
"pg": "^8.7.1",
"pg": "^8.8.0",
"rate-limit-redis": "^3.0.1",
"redis": "^4.0.6",
"redis": "^4.5.0",
"sync-mysql": "^3.0.1"
},
"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/sinon": "^10.0.13",
"@typescript-eslint/eslint-plugin": "^5.44.0",
"@typescript-eslint/parser": "^5.44.0",
"axios-mock-adapter": "^1.21.2",
"eslint": "^8.28.0",
"mocha": "^10.1.0",
"nodemon": "^2.0.20",
"nyc": "^15.1.0",
"sinon": "^14.0.2",
"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,17 @@ import ExpressPromiseRouter from "express-promise-router";
import { Server } from "http";
import { youtubeApiProxy } from "./routes/youtubeApiProxy";
import { getChapterNames } from "./routes/getChapterNames";
import { postRating } from "./routes/ratings/postRating";
import { getRating } from "./routes/ratings/getRating";
import { postClearCache as ratingPostClearCache } from "./routes/ratings/postClearCache";
import { getTopCategoryUsers } from "./routes/getTopCategoryUsers";
import { addUserAsTempVIP } from "./routes/addUserAsTempVIP";
import { endpoint as getVideoLabels } from "./routes/getVideoLabel";
import { getVideoLabelsByHash } from "./routes/getVideoLabelByHash";
import { addFeature } from "./routes/addFeature";
import { generateTokenRequest } from "./routes/generateToken";
import { verifyTokenRequest } from "./routes/verifyToken";
import { getBranding, getBrandingByHashEndpoint } from "./routes/getBranding";
import { postBranding } from "./routes/postBranding";
import { cacheMiddlware } from "./middleware/etag";
import { hostHeader } from "./middleware/hostHeader";
export function createServer(callback: () => void): Server {
// Create a service (the app object is just a callback).
@@ -55,11 +60,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);
@@ -75,15 +83,14 @@ export function createServer(callback: () => void): Server {
return app.listen(config.port, callback);
}
/* eslint-disable @typescript-eslint/no-misused-promises */
function setupRoutes(router: Router) {
// Rate limit endpoint lists
const voteEndpoints: RequestHandler[] = [voteOnSponsorTime];
const viewEndpoints: RequestHandler[] = [viewedVideoSponsorTime];
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
@@ -196,20 +203,29 @@ 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/generateToken/:type", generateTokenRequest);
router.get("/api/verifyToken", verifyTokenRequest);
// labels
router.get("/api/videoLabels", getVideoLabels);
router.get("/api/videoLabels/:prefix", getVideoLabelsByHash);
router.get("/api/branding", getBranding);
router.get("/api/branding/:prefix", getBrandingByHashEndpoint);
router.post("/api/branding", postBranding);
/* istanbul ignore next */
if (config.postgres?.enabled) {
router.get("/database", (req, res) => dumpDatabase(req, res, true));
router.get("/database.json", (req, res) => dumpDatabase(req, res, false));
router.get("/database/*", 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,7 @@
import fs from "fs";
import { SBSConfig } from "./types/config.model";
import packageJson from "../package.json";
import { isBoolean, isNumber } from "lodash";
import { isNumber } from "lodash";
const isTestMode = process.env.npm_lifecycle_script === packageJson.scripts.test;
const configFile = process.env.TEST_POSTGRES ? "ci.json"
@@ -20,7 +20,7 @@ addDefaults(config, {
privateDBSchema: "./databases/_private.db.sql",
readOnly: false,
webhooks: [],
categoryList: ["sponsor", "selfpromo", "exclusive_access", "interaction", "intro", "outro", "preview", "music_offtopic", "filler", "poi_highlight"],
categoryList: ["sponsor", "selfpromo", "exclusive_access", "interaction", "intro", "outro", "preview", "music_offtopic", "filler", "poi_highlight", "chapter"],
categorySupport: {
sponsor: ["skip", "mute", "full"],
selfpromo: ["skip", "mute", "full"],
@@ -42,6 +42,9 @@ addDefaults(config, {
discordNeuralBlockRejectWebhookURL: null,
discordFailedReportChannelWebhookURL: null,
discordReportChannelWebhookURL: null,
discordMaliciousReportWebhookURL: null,
minReputationToSubmitChapter: 0,
minReputationToSubmitFiller: 0,
getTopUsersCacheTimeMinutes: 240,
globalSalt: null,
mode: "",
@@ -59,15 +62,10 @@ addDefaults(config, {
max: 10,
statusCode: 200,
message: "OK",
},
rate: {
windowMs: 900000,
max: 20,
statusCode: 200,
message: "Success",
}
},
userCounterURL: null,
userCounterRatio: 10,
newLeafURLs: null,
maxRewardTimePerSegmentInSeconds: 600,
poiMinimumStartTime: 2,
@@ -76,7 +74,27 @@ addDefaults(config, {
user: "",
host: "",
password: "",
port: 5432
port: 5432,
max: 10,
idleTimeoutMillis: 10000,
maxTries: 3,
maxActiveRequests: 0,
timeout: 60000,
highLoadThreshold: 10
},
postgresReadOnly: {
enabled: false,
weight: 1,
user: "",
host: "",
password: "",
port: 5432,
readTimeout: 250,
max: 10,
idleTimeoutMillis: 10000,
maxTries: 3,
fallbackOnFail: true,
stopRetryThreshold: 800
},
dumpDatabase: {
enabled: false,
@@ -110,6 +128,21 @@ addDefaults(config, {
},
{
name: "ratings"
},
{
name: "titles"
},
{
name: "titleVotes"
},
{
name: "thumbnails"
},
{
name: "thumbnailTimestamps"
},
{
name: "thumbnailVotes"
}]
},
diskCacheURL: null,
@@ -120,8 +153,36 @@ 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,
disableHashCache: false
},
redisRead: {
enabled: false,
socket: {
host: "",
port: 0
},
disableOfflineQueue: true,
weight: 1
},
redisRateLimit: true,
patreon: {
clientId: "",
clientSecret: "",
minPrice: 0,
redirectUri: "https://sponsor.ajay.app/api/generateToken/patreon"
},
gumroad: {
productPermalinks: ["sponsorblock"]
},
minUserIDLength: 30
});
loadFromEnv(config);
migrate(config);
@@ -170,7 +231,7 @@ function loadFromEnv(config: SBSConfig, prefix = "") {
} else if (process.env[fullKey]) {
const value = process.env[fullKey];
if (isNumber(value)) {
config[key] = parseInt(value, 10);
config[key] = parseFloat(value);
} else if (value.toLowerCase() === "true" || value.toLowerCase() === "false") {
config[key] = value === "true";
} else if (key === "newLeafURLs") {

View File

@@ -57,7 +57,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,14 @@
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: QueryType, query: string, params?: any[], options?: QueryOption): Promise<any | any[] | void>;
highLoad(): boolean;
}
export type QueryType = "get" | "all" | "run";
export type QueryType = "get" | "all" | "run";

View File

@@ -32,4 +32,8 @@ export class Mysql implements IDatabase {
}
}
highLoad() {
return false;
}
}

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,32 @@ 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;
}
}

View File

@@ -95,6 +95,10 @@ export class Sqlite implements IDatabase {
private static processUpgradeQuery(query: string): string {
return query.replace(/^.*--!sqlite-ignore/gm, "");
}
highLoad() {
return false;
}
}
export interface SqliteConfig {

View File

@@ -17,12 +17,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 +33,13 @@ 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,
database: "privateDB"
},
postgresReadOnly: config.postgresReadOnly ? {
...config.postgresReadOnly,
database: "privateDB"
} : null
});
} else {
db = new Sqlite({

View File

@@ -4,6 +4,7 @@ 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) => {
@@ -12,7 +13,14 @@ async function init() {
process.exit(1);
});
await initDb();
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 +35,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");
next();
}

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

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

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();

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

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

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

@@ -35,6 +35,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,7 +49,7 @@ 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.",
});
}

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();
@@ -123,7 +124,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 +135,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>
@@ -232,7 +238,7 @@ async function queueDump(): Promise<void> {
resolve(error ? stderr : stdout);
});
})
});
dumpFiles.push({
fileName,

View File

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

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

@@ -0,0 +1,222 @@
import { Request, Response } from "express";
import { isEmpty } from "lodash";
import { config } from "../config";
import { db, privateDB } from "../databases/databases";
import { Postgres } from "../databases/Postgres";
import { BrandingDBSubmission, BrandingHashDBResult, BrandingResult, ThumbnailDBResult, ThumbnailResult, TitleDBResult, TitleResult } from "../types/branding.model";
import { HashedIP, IPAddress, Service, VideoID, VideoIDHash, Visibility } from "../types/segments.model";
import { shuffleArray } from "../utils/array";
import { getHashCache } from "../utils/getHashCache";
import { getIP } from "../utils/getIP";
import { getService } from "../utils/getService";
import { hashPrefixTester } from "../utils/hashPrefixTester";
import { Logger } from "../utils/logger";
import { promiseOrTimeout } from "../utils/promise";
import { QueryCacher } from "../utils/queryCacher";
import { brandingHashKey, brandingIPKey, brandingKey } from "../utils/redisKeys";
enum BrandingSubmissionType {
Title = "title",
Thumbnail = "thumbnail"
}
export async function getVideoBranding(res: Response, videoID: VideoID, service: Service, ip: IPAddress): Promise<BrandingResult> {
const getTitles = () => db.prepare(
"all",
`SELECT "titles"."title", "titles"."original", "titleVotes"."votes", "titleVotes"."locked", "titleVotes"."shadowHidden", "titles"."UUID", "titles"."videoID", "titles"."hashedVideoID"
FROM "titles" JOIN "titleVotes" ON "titles"."UUID" = "titleVotes"."UUID"
WHERE "titles"."videoID" = ? AND "titles"."service" = ? AND "titleVotes"."votes" > -2`,
[videoID, service],
{ useReplica: true }
) as Promise<TitleDBResult[]>;
const getThumbnails = () => db.prepare(
"all",
`SELECT "thumbnailTimestamps"."timestamp", "thumbnails"."original", "thumbnailVotes"."votes", "thumbnailVotes"."locked", "thumbnailVotes"."shadowHidden", "thumbnails"."UUID", "thumbnails"."videoID", "thumbnails"."hashedVideoID"
FROM "thumbnails" LEFT JOIN "thumbnailVotes" ON "thumbnails"."UUID" = "thumbnailVotes"."UUID" LEFT JOIN "thumbnailTimestamps" ON "thumbnails"."UUID" = "thumbnailTimestamps"."UUID"
WHERE "thumbnails"."videoID" = ? AND "thumbnails"."service" = ? AND "thumbnailVotes"."votes" > -2`,
[videoID, service],
{ useReplica: true }
) as Promise<ThumbnailDBResult[]>;
const getBranding = async () => ({
titles: await getTitles(),
thumbnails: await getThumbnails()
});
const brandingTrace = await QueryCacher.getTraced(getBranding, brandingKey(videoID, service));
const branding = brandingTrace.data;
// Add trace info to request for debugging purposes
res.setHeader("X-Start-Time", brandingTrace.startTime);
if (brandingTrace.dbStartTime) res.setHeader("X-DB-Start-Time", brandingTrace.dbStartTime);
res.setHeader("X-End-Time", brandingTrace.endTime);
const stats = (db as Postgres)?.getStats?.();
if (stats) {
res.setHeader("X-DB-Pool-Total", stats.pool.total);
res.setHeader("X-DB-Pool-Idle", stats.pool.idle);
res.setHeader("X-DB-Pool-Waiting", stats.pool.waiting);
}
const cache = {
currentIP: null as Promise<HashedIP> | null
};
return filterAndSortBranding(branding.titles, branding.thumbnails, ip, cache);
}
export async function getVideoBrandingByHash(videoHashPrefix: VideoIDHash, service: Service, ip: IPAddress): Promise<Record<VideoID, BrandingResult>> {
const getTitles = () => db.prepare(
"all",
`SELECT "titles"."title", "titles"."original", "titleVotes"."votes", "titleVotes"."locked", "titleVotes"."shadowHidden", "titles"."UUID", "titles"."videoID", "titles"."hashedVideoID"
FROM "titles" JOIN "titleVotes" ON "titles"."UUID" = "titleVotes"."UUID"
WHERE "titles"."hashedVideoID" LIKE ? AND "titles"."service" = ? AND "titleVotes"."votes" > -2`,
[`${videoHashPrefix}%`, service],
{ useReplica: true }
) as Promise<TitleDBResult[]>;
const getThumbnails = () => db.prepare(
"all",
`SELECT "thumbnailTimestamps"."timestamp", "thumbnails"."original", "thumbnailVotes"."votes", "thumbnailVotes"."locked", "thumbnailVotes"."shadowHidden", "thumbnails"."UUID", "thumbnails"."videoID", "thumbnails"."hashedVideoID"
FROM "thumbnails" LEFT JOIN "thumbnailVotes" ON "thumbnails"."UUID" = "thumbnailVotes"."UUID" LEFT JOIN "thumbnailTimestamps" ON "thumbnails"."UUID" = "thumbnailTimestamps"."UUID"
WHERE "thumbnails"."hashedVideoID" LIKE ? AND "thumbnails"."service" = ? AND "thumbnailVotes"."votes" > -2`,
[`${videoHashPrefix}%`, service],
{ useReplica: true }
) as Promise<ThumbnailDBResult[]>;
const branding = await QueryCacher.get(async () => {
// Make sure they are both called in parallel
const branding = {
titles: getTitles(),
thumbnails: getThumbnails()
};
const dbResult: Record<VideoID, BrandingHashDBResult> = {};
const initResult = (submission: BrandingDBSubmission) => {
dbResult[submission.videoID] = dbResult[submission.videoID] || {
titles: [],
thumbnails: []
};
};
(await branding.titles).map((title) => {
initResult(title);
dbResult[title.videoID].titles.push(title);
});
(await branding.thumbnails).map((thumbnail) => {
initResult(thumbnail);
dbResult[thumbnail.videoID].thumbnails.push(thumbnail);
});
return dbResult;
}, brandingHashKey(videoHashPrefix, service));
const cache = {
currentIP: null as Promise<HashedIP> | null
};
const processedResult: Record<VideoID, BrandingResult> = {};
await Promise.all(Object.keys(branding).map(async (key) => {
const castedKey = key as VideoID;
processedResult[castedKey] = await filterAndSortBranding(branding[castedKey].titles, branding[castedKey].thumbnails, ip, cache);
}));
return processedResult;
}
async function filterAndSortBranding(dbTitles: TitleDBResult[], dbThumbnails: ThumbnailDBResult[], ip: IPAddress, cache: { currentIP: Promise<HashedIP> | null }): Promise<BrandingResult> {
const shouldKeepTitles = shouldKeepSubmission(dbTitles, BrandingSubmissionType.Title, ip, cache);
const shouldKeepThumbnails = shouldKeepSubmission(dbThumbnails, BrandingSubmissionType.Thumbnail, ip, cache);
const titles = shuffleArray(dbTitles.filter(await shouldKeepTitles))
.sort((a, b) => b.votes - a.votes)
.sort((a, b) => b.locked - a.locked)
.map((r) => ({
title: r.title,
original: r.original === 1,
votes: r.votes,
locked: r.locked === 1,
UUID: r.UUID,
})) as TitleResult[];
const thumbnails = shuffleArray(dbThumbnails.filter(await shouldKeepThumbnails))
.sort((a, b) => b.votes - a.votes)
.sort((a, b) => b.locked - a.locked)
.map((r) => ({
timestamp: r.timestamp,
original: r.original === 1,
votes: r.votes,
locked: r.locked === 1,
UUID: r.UUID
})) as ThumbnailResult[];
return {
titles,
thumbnails
};
}
async function shouldKeepSubmission(submissions: BrandingDBSubmission[], type: BrandingSubmissionType, ip: IPAddress,
cache: { currentIP: Promise<HashedIP> | null }): Promise<(_: unknown, index: number) => boolean> {
const shouldKeep = await Promise.all(submissions.map(async (s) => {
if (s.shadowHidden != Visibility.HIDDEN) return true;
const table = type === BrandingSubmissionType.Title ? "titleVotes" : "thumbnailVotes";
const fetchData = () => privateDB.prepare("get", `SELECT "hashedIP" FROM "${table}" WHERE "UUID" = ?`,
[s.UUID], { useReplica: true }) as Promise<{ hashedIP: HashedIP }>;
try {
const submitterIP = await promiseOrTimeout(QueryCacher.get(fetchData, brandingIPKey(s.UUID)), 150);
if (cache.currentIP === null) cache.currentIP = getHashCache((ip + config.globalSalt) as IPAddress);
const hashedIP = await cache.currentIP;
return submitterIP.hashedIP !== hashedIP;
} catch (e) {
// give up on shadow hide for now
return false;
}
}));
return (_, index) => shouldKeep[index];
}
export async function getBranding(req: Request, res: Response) {
const videoID: VideoID = req.query.videoID as VideoID;
const service: Service = getService(req.query.service as string);
if (!videoID) {
return res.status(400).send("Missing parameter: videoID");
}
const ip = getIP(req);
try {
const result = await getVideoBranding(res, videoID, service, ip);
const status = result.titles.length > 0 || result.thumbnails.length > 0 ? 200 : 404;
return res.status(status).json(result);
} catch (e) {
Logger.error(e as string);
return res.status(500).send("Internal server error");
}
}
export async function getBrandingByHashEndpoint(req: Request, res: Response) {
let hashPrefix = req.params.prefix as VideoIDHash;
if (!hashPrefix || !hashPrefixTester(hashPrefix) || hashPrefix.length !== 4) {
return res.status(400).send("Hash prefix does not match format requirements."); // Exit early on faulty prefix
}
hashPrefix = hashPrefix.toLowerCase() as VideoIDHash;
const service: Service = getService(req.query.service as string);
const ip = getIP(req);
try {
const result = await getVideoBrandingByHash(hashPrefix, service, ip);
const status = !isEmpty(result) ? 200 : 404;
return res.status(status).json(result);
} catch (e) {
Logger.error(e as string);
return res.status(500).send([]);
}
}

View File

@@ -22,7 +22,7 @@ export async function getChapterNames(req: Request, res: Response): Promise<Resp
const descriptions = await db.prepare("all", `
SELECT "description"
FROM "sponsorTimes"
WHERE ("votes" > 0 OR ("views" > 100 AND "votes" >= 0)) AND "videoID" IN (
WHERE ("locked" = 1 OR "votes" > 0 OR ("views" > 25 AND "votes" >= 0)) AND "videoID" IN (
SELECT "videoID"
FROM "videoInfo"
WHERE "channelID" = ?

View File

@@ -7,7 +7,11 @@ export async function getDaysSavedFormatted(req: Request, res: Response): Promis
if (row !== undefined) {
//send this result
return res.send({
daysSaved: row.daysSaved.toFixed(2),
daysSaved: row.daysSaved?.toFixed(2) ?? "0",
});
} else {
return res.send({
daysSaved: 0
});
}
}

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);
}

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

@@ -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

@@ -11,33 +11,47 @@ import { Logger } from "../utils/logger";
import { QueryCacher } from "../utils/queryCacher";
import { getReputation } from "../utils/reputation";
import { getService } from "../utils/getService";
import { promiseOrTimeout } from "../utils/promise";
import { parseSkipSegments } from "../utils/parseSkipSegments";
import { getEtag } from "../middleware/etag";
async function prepareCategorySegments(req: Request, videoID: VideoID, service: Service, segments: DBSegment[], cache: SegmentCache = { shadowHiddenSegmentIPs: {} }, useCache: boolean): Promise<Segment[]> {
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) {
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 {
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = await promiseOrTimeout(QueryCacher.get(fetchData, shadowHiddenIPKey(videoID, segment.timeSubmitted, service)), 150);
} catch (e) {
// give up on shadowhide for now
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = null;
}
}
const ipList = cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted];
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(
@@ -73,9 +87,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 +95,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 +115,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;
@@ -114,15 +135,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,15 +150,24 @@ 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))
.filter((segment: Segment) => categories.includes(segment?.category) && actionTypes.includes(segment?.actionType));
.filter((segment: Segment) => categories.includes(segment?.category) && actionTypes.includes(segment?.actionType))
.map((segment) => ({
category: segment.category,
actionType: segment.actionType,
segment: segment.segment,
UUID: segment.UUID,
videoDuration: segment.videoDuration,
locked: segment.locked,
votes: segment.votes,
description: segment.description
}));
if (forcePoiAsSkip) {
data.segments = data.segments.map((segment) => ({
@@ -153,10 +179,10 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
if (data.segments.length > 0) {
segments[videoID] = data;
}
}
}));
return segments;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return null;
}
@@ -166,9 +192,10 @@ 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) {
@@ -182,9 +209,10 @@ 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));
@@ -275,6 +303,9 @@ async function chooseSegments(videoID: VideoID, service: Service, segments: DBSe
//This allows new less voted items to still sometimes appear to give them a chance at getting votes.
//Segments with less than -1 votes are already ignored before this function is called
async function buildSegmentGroups(segments: DBSegment[]): Promise<OverlappingSegmentGroup[]> {
const reputationPromises = segments.map(segment =>
segment.userID && !db.highLoad() ? getReputation(segment.userID).catch((e) => Logger.error(e)) : null);
//Create groups of segments that are similar to eachother
//Segments must be sorted by their startTime so that we can build groups chronologically:
//1. As long as the segments' startTime fall inside the currentGroup, we keep adding them to that group
@@ -283,7 +314,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 +327,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 +391,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(() => null);
return res.send(segments);
}
async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise<Response> {
const videoID = req.query.videoID as VideoID;
if (!videoID) {
return res.status(400).send("videoID not specified");
}
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 +453,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,27 @@ 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, requiredSegments, service } = parseResult;
// Get all video id's that match hash prefix
const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, requiredSegments, service);
if (!segments) return res.status(404).json([]);
try {
await getEtag("skipSegmentsHash", hashPrefix, service)
.then(etag => res.set("ETag", etag))
.catch(/* istanbul ignore next */ () => null);
const output = Object.entries(segments).map(([videoID, data]) => ({
videoID,
segments: data.segments,
}));
return res.status(output.length === 0 ? 404 : 200).json(output);
} catch (e) /* istanbul ignore next */ {
Logger.error(`skip segments by hash error: ${e}`);
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");
}
}

View File

@@ -2,31 +2,53 @@ import { db } from "../databases/databases";
import { Logger } from "../utils/logger";
import { Request, Response } from "express";
import os from "os";
import redis from "../utils/redis";
import redis, { getRedisStats } from "../utils/redis";
import { promiseOrTimeout } from "../utils/promise";
import { Postgres } from "../databases/Postgres";
export async function getStatus(req: Request, res: Response): Promise<Response> {
const startTime = Date.now();
let value = req.params.value as string[] | string;
value = Array.isArray(value) ? value[0] : value;
let processTime, redisProcessTime = -1;
try {
const dbVersion = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value;
const dbStartTime = Date.now();
const dbVersion = await promiseOrTimeout(db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"]), 5000)
.then(e => {
processTime = Date.now() - dbStartTime;
return e.value;
})
.catch(e => /* istanbul ignore next */ {
Logger.error(`status: SQL query timed out: ${e}`);
return -1;
});
let statusRequests: unknown = 0;
try {
const numberRequests = await redis.increment("statusRequest");
statusRequests = numberRequests?.[0];
} catch (error) { } // eslint-disable-line no-empty
const redisStartTime = Date.now();
const numberRequests = await promiseOrTimeout(redis.increment("statusRequest"), 5000)
.then(e => {
redisProcessTime = Date.now() - redisStartTime;
return e;
}).catch(e => /* istanbul ignore next */ {
Logger.error(`status: redis increment timed out ${e}`);
return [-1];
});
statusRequests = numberRequests?.[0];
const statusValues: Record<string, any> = {
uptime: process.uptime(),
commit: (global as any).HEADCOMMIT || "unknown",
commit: (global as any)?.HEADCOMMIT ?? "unknown",
db: Number(dbVersion),
startTime,
processTime: Date.now() - startTime,
processTime,
redisProcessTime,
loadavg: os.loadavg().slice(1), // only return 5 & 15 minute load average
statusRequests
statusRequests,
hostname: os.hostname(),
postgresStats: (db as Postgres)?.getStats?.(),
redisStats: getRedisStats(),
};
return value ? res.send(JSON.stringify(statusValues[value])) : res.send(statusValues);
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -2,9 +2,12 @@ import { db } from "../databases/databases";
import { createMemoryCache } from "../utils/createMemoryCache";
import { config } from "../config";
import { Request, Response } from "express";
import { validateCategories } from "../utils/parseParams";
const MILLISECONDS_IN_MINUTE = 60000;
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const getTopCategoryUsersWithCache = createMemoryCache(generateTopCategoryUsersStats, config.getTopUsersCacheTimeMinutes * MILLISECONDS_IN_MINUTE);
/* istanbul ignore next */
const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400;
interface DBSegment {
@@ -25,7 +28,7 @@ async function generateTopCategoryUsersStats(sortBy: string, category: string) {
SUM("votes") as "userVotes", COALESCE("userNames"."userName", "sponsorTimes"."userID") as "userName" FROM "sponsorTimes" LEFT JOIN "userNames" ON "sponsorTimes"."userID"="userNames"."userID"
LEFT JOIN "shadowBannedUsers" ON "sponsorTimes"."userID"="shadowBannedUsers"."userID"
WHERE "sponsorTimes"."category" = ? AND "sponsorTimes"."votes" > -1 AND "sponsorTimes"."shadowHidden" != 1 AND "shadowBannedUsers"."userID" IS NULL
GROUP BY COALESCE("userName", "sponsorTimes"."userID") HAVING SUM("votes") > 20
GROUP BY COALESCE("userName", "sponsorTimes"."userID") HAVING SUM("votes") > 2
ORDER BY "${sortBy}" DESC LIMIT 100`, [maxRewardTimePerSegmentInSeconds, maxRewardTimePerSegmentInSeconds, category]);
if (rows) {
@@ -33,11 +36,10 @@ async function generateTopCategoryUsersStats(sortBy: string, category: string) {
userNames.push(row.userName);
viewCounts.push(row.viewCount);
totalSubmissions.push(row.totalSubmissions);
minutesSaved.push(row.minutesSaved);
minutesSaved.push(category === "chapter" ? 0 : row.minutesSaved);
}
}
return {
userNames,
viewCounts,
@@ -50,11 +52,15 @@ export async function getTopCategoryUsers(req: Request, res: Response): Promise<
const sortType = parseInt(req.query.sortType as string);
const category = req.query.category as string;
if (sortType == undefined || !config.categoryList.includes(category) ) {
if (sortType == undefined || !validateCategories([category]) ) {
//invalid request
return res.sendStatus(400);
}
if (db.highLoad()) {
return res.status(503).send("Disabled for load reasons");
}
//setup which sort type to use
let sortBy = "";
if (sortType == 0) {

View File

@@ -4,6 +4,7 @@ import { config } from "../config";
import { Request, Response } from "express";
const MILLISECONDS_IN_MINUTE = 60000;
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const getTopUsersWithCache = createMemoryCache(generateTopUsersStats, config.getTopUsersCacheTimeMinutes * MILLISECONDS_IN_MINUTE);
const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400;
@@ -27,11 +28,12 @@ async function generateTopUsersStats(sortBy: string, categoryStatsEnabled = fals
SUM(CASE WHEN category = 'poi_highlight' THEN 1 ELSE 0 END) as "categorySumHighlight",
SUM(CASE WHEN category = 'filler' THEN 1 ELSE 0 END) as "categorySumFiller",
SUM(CASE WHEN category = 'exclusive_access' THEN 1 ELSE 0 END) as "categorySumExclusiveAccess",
SUM(CASE WHEN category = 'chapter' THEN 1 ELSE 0 END) as "categorySumChapter",
`;
}
const rows = await db.prepare("all", `SELECT COUNT(*) as "totalSubmissions", SUM(views) as "viewCount",
SUM(((CASE WHEN "sponsorTimes"."endTime" - "sponsorTimes"."startTime" > ? THEN ? ELSE "sponsorTimes"."endTime" - "sponsorTimes"."startTime" END) / 60) * "sponsorTimes"."views") as "minutesSaved",
SUM(CASE WHEN "sponsorTimes"."actionType" = 'chapter' THEN 0 ELSE ((CASE WHEN "sponsorTimes"."endTime" - "sponsorTimes"."startTime" > ? THEN ? ELSE "sponsorTimes"."endTime" - "sponsorTimes"."startTime" END) / 60) * "sponsorTimes"."views" END) as "minutesSaved",
SUM("votes") as "userVotes", ${additionalFields} COALESCE("userNames"."userName", "sponsorTimes"."userID") as "userName" FROM "sponsorTimes" LEFT JOIN "userNames" ON "sponsorTimes"."userID"="userNames"."userID"
LEFT JOIN "shadowBannedUsers" ON "sponsorTimes"."userID"="shadowBannedUsers"."userID"
WHERE "sponsorTimes"."votes" > -1 AND "sponsorTimes"."shadowHidden" != 1 AND "shadowBannedUsers"."userID" IS NULL
@@ -54,7 +56,8 @@ async function generateTopUsersStats(sortBy: string, categoryStatsEnabled = fals
row.categorySumPreview,
row.categorySumHighlight,
row.categorySumFiller,
row.categorySumExclusiveAccess
row.categorySumExclusiveAccess,
row.categorySumChapter
]);
}
}
@@ -72,11 +75,6 @@ export async function getTopUsers(req: Request, res: Response): Promise<Response
const sortType = parseInt(req.query.sortType as string);
const categoryStatsEnabled = req.query.categoryStats;
if (sortType == undefined) {
//invalid request
return res.sendStatus(400);
}
//setup which sort type to use
let sortBy = "";
if (sortType == 0) {
@@ -90,6 +88,10 @@ export async function getTopUsers(req: Request, res: Response): Promise<Response
return res.sendStatus(400);
}
if (db.highLoad()) {
return res.status(503).send("Disabled for load reasons");
}
const stats = await getTopUsersWithCache(sortBy, categoryStatsEnabled);
//send this result

View File

@@ -3,6 +3,7 @@ import { config } from "../config";
import { Request, Response } from "express";
import axios from "axios";
import { Logger } from "../utils/logger";
import { getCWSUsers } from "../utils/getCWSUsers";
// A cache of the number of chrome web store users
let chromeUsersCache = 0;
@@ -10,73 +11,110 @@ let firefoxUsersCache = 0;
// By the privacy friendly user counter
let apiUsersCache = 0;
let lastUserCountCheck = 0;
interface DBStatsData {
userCount: number,
viewCount: number,
totalSubmissions: number,
minutesSaved: number
}
let lastFetch: DBStatsData = {
userCount: 0,
viewCount: 0,
totalSubmissions: 0,
minutesSaved: 0
};
updateExtensionUsers();
export async function getTotalStats(req: Request, res: Response): Promise<void> {
const userCountQuery = `(SELECT COUNT(*) FROM (SELECT DISTINCT "userID" from "sponsorTimes") t) "userCount",`;
const countContributingUsers = Boolean(req.query?.countContributingUsers == "true");
const row = await getStats(countContributingUsers);
lastFetch = row;
const row = await db.prepare("get", `SELECT ${req.query.countContributingUsers ? userCountQuery : ""} COUNT(*) as "totalSubmissions",
SUM("views") as "viewCount", SUM(("endTime" - "startTime") / 60 * "views") as "minutesSaved" FROM "sponsorTimes" WHERE "shadowHidden" != 1 AND "votes" >= 0`, []);
/* istanbul ignore if */
if (!row) res.sendStatus(500);
const extensionUsers = chromeUsersCache + firefoxUsersCache;
if (row !== undefined) {
const extensionUsers = chromeUsersCache + firefoxUsersCache;
//send this result
res.send({
userCount: row.userCount ?? 0,
activeUsers: extensionUsers,
apiUsers: Math.max(apiUsersCache, extensionUsers),
viewCount: row.viewCount,
totalSubmissions: row.totalSubmissions,
minutesSaved: row.minutesSaved,
});
//send this result
res.send({
userCount: row.userCount,
activeUsers: extensionUsers,
apiUsers: Math.max(apiUsersCache, extensionUsers),
viewCount: row.viewCount,
totalSubmissions: row.totalSubmissions,
minutesSaved: row.minutesSaved,
});
// Check if the cache should be updated (every ~14 hours)
const now = Date.now();
if (now - lastUserCountCheck > 5000000) {
lastUserCountCheck = now;
// Check if the cache should be updated (every ~14 hours)
const now = Date.now();
if (now - lastUserCountCheck > 5000000) {
lastUserCountCheck = now;
updateExtensionUsers();
}
}
updateExtensionUsers();
}
function getStats(countContributingUsers: boolean): Promise<DBStatsData> {
if (db.highLoad()) {
return Promise.resolve(lastFetch);
} else {
const userCountQuery = `(SELECT COUNT(*) FROM (SELECT DISTINCT "userID" from "sponsorTimes") t) "userCount",`;
return db.prepare("get", `SELECT ${countContributingUsers ? userCountQuery : ""} COUNT(*) as "totalSubmissions",
SUM("views") as "viewCount", SUM(("endTime" - "startTime") / 60 * "views") as "minutesSaved" FROM "sponsorTimes" WHERE "shadowHidden" != 1 AND "votes" >= 0 AND "actionType" != 'chapter'`, []);
}
}
function updateExtensionUsers() {
/* istanbul ignore else */
if (config.userCounterURL) {
axios.get(`${config.userCounterURL}/api/v1/userCount`)
.then(res => {
apiUsersCache = Math.max(apiUsersCache, res.data.userCount);
})
.catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
.then(res => apiUsersCache = Math.max(apiUsersCache, res.data.userCount))
.catch( /* istanbul ignore next */ () => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
}
const mozillaAddonsUrl = "https://addons.mozilla.org/api/v3/addons/addon/sponsorblock/";
const chromeExtensionUrl = "https://chrome.google.com/webstore/detail/sponsorblock-for-youtube/mnjggcdmjocbbbhaepdhchncahnbgone";
const chromeExtId = "mnjggcdmjocbbbhaepdhchncahnbgone";
axios.get(mozillaAddonsUrl)
.then(res => {
firefoxUsersCache = res.data.average_daily_users;
axios.get(chromeExtensionUrl)
.then(res => {
const body = res.data;
// 2021-01-05
// [...]<span><meta itemprop="interactionCount" content="UserDownloads:100.000+"/><meta itemprop="opera[...]
const matchingString = '"UserDownloads:';
const matchingStringLen = matchingString.length;
const userDownloadsStartIndex = body.indexOf(matchingString);
if (userDownloadsStartIndex >= 0) {
const closingQuoteIndex = body.indexOf('"', userDownloadsStartIndex + matchingStringLen);
const userDownloadsStr = body.substr(userDownloadsStartIndex + matchingStringLen, closingQuoteIndex - userDownloadsStartIndex).replace(",","").replace(".","");
chromeUsersCache = parseInt(userDownloadsStr);
}
else {
lastUserCountCheck = 0;
}
})
.catch(() => Logger.debug(`Failing to connect to ${chromeExtensionUrl}`));
})
.catch(() => {
.then(res => firefoxUsersCache = res.data.average_daily_users )
.catch( /* istanbul ignore next */ () => {
Logger.debug(`Failing to connect to ${mozillaAddonsUrl}`);
return 0;
});
getCWSUsers(chromeExtId)
.then(res => chromeUsersCache = res)
.catch(/* istanbul ignore next */ () =>
getChromeUsers(chromeExtensionUrl)
.then(res => chromeUsersCache = res)
);
}
/* istanbul ignore next */
function getChromeUsers(chromeExtensionUrl: string): Promise<number> {
return axios.get(chromeExtensionUrl)
.then(res => {
const body = res.data;
// 2021-01-05
// [...]<span><meta itemprop="interactionCount" content="UserDownloads:100.000+"/><meta itemprop="opera[...]
const matchingString = '"UserDownloads:';
const matchingStringLen = matchingString.length;
const userDownloadsStartIndex = body.indexOf(matchingString);
/* istanbul ignore else */
if (userDownloadsStartIndex >= 0) {
const closingQuoteIndex = body.indexOf('"', userDownloadsStartIndex + matchingStringLen);
const userDownloadsStr = body.substr(userDownloadsStartIndex + matchingStringLen, closingQuoteIndex - userDownloadsStartIndex).replace(",", "").replace(".", "");
return parseInt(userDownloadsStr);
} else {
lastUserCountCheck = 0;
}
})
.catch(/* istanbul ignore next */ () => {
Logger.debug(`Failing to connect to ${chromeExtensionUrl}`);
return 0;
});
}

View File

@@ -12,7 +12,7 @@ function getFuzzyUserID(userName: string): Promise<{userName: string, userID: Us
try {
return db.prepare("all", `SELECT "userName", "userID" FROM "userNames" WHERE "userName"
LIKE ? ESCAPE '\\' LIMIT 10`, [userName]);
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return null;
}
}
@@ -20,7 +20,7 @@ function getFuzzyUserID(userName: string): Promise<{userName: string, userID: Us
function getExactUserID(userName: string): Promise<{userName: string, userID: UserID }[]> {
try {
return db.prepare("all", `SELECT "userName", "userID" from "userNames" WHERE "userName" = ? LIMIT 10`, [userName]);
} catch (err) {
} catch (err) /* istanbul ignore next */{
return null;
}
}
@@ -42,6 +42,7 @@ export async function getUserID(req: Request, res: Response): Promise<Response>
: await getFuzzyUserID(userName);
if (results === undefined || results === null) {
/* istanbul ignore next */
return res.sendStatus(500);
} else if (results.length === 0) {
return res.sendStatus(404);

View File

@@ -5,16 +5,17 @@ import { Request, Response } from "express";
import { Logger } from "../utils/logger";
import { HashedUserID, UserID } from "../types/user.model";
import { getReputation } from "../utils/reputation";
import { SegmentUUID } from "../types/segments.model";
import { Category, SegmentUUID } from "../types/segments.model";
import { config } from "../config";
import { canSubmit } from "../utils/permissions";
const maxRewardTime = config.maxRewardTimePerSegmentInSeconds;
async function dbGetSubmittedSegmentSummary(userID: HashedUserID): Promise<{ minutesSaved: number, segmentCount: number }> {
try {
const row = await db.prepare("get",
`SELECT SUM(((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views") as "minutesSaved",
`SELECT SUM(CASE WHEN "actionType" = 'chapter' THEN 0 ELSE ((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views" END) as "minutesSaved",
count(*) as "segmentCount" FROM "sponsorTimes"
WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`, [maxRewardTime, maxRewardTime, userID]);
WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`, [maxRewardTime, maxRewardTime, userID], { useReplica: true });
if (row.minutesSaved != null) {
return {
minutesSaved: row.minutesSaved,
@@ -26,16 +27,16 @@ async function dbGetSubmittedSegmentSummary(userID: HashedUserID): Promise<{ min
segmentCount: 0,
};
}
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return null;
}
}
async function dbGetIgnoredSegmentCount(userID: HashedUserID): Promise<number> {
try {
const row = await db.prepare("get", `SELECT COUNT(*) as "ignoredSegmentCount" FROM "sponsorTimes" WHERE "userID" = ? AND ( "votes" <= -2 OR "shadowHidden" = 1 )`, [userID]);
const row = await db.prepare("get", `SELECT COUNT(*) as "ignoredSegmentCount" FROM "sponsorTimes" WHERE "userID" = ? AND ( "votes" <= -2 OR "shadowHidden" = 1 )`, [userID], { useReplica: true });
return row?.ignoredSegmentCount ?? 0;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return null;
}
}
@@ -44,34 +45,34 @@ async function dbGetUsername(userID: HashedUserID) {
try {
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
return row?.userName ?? userID;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return false;
}
}
async function dbGetViewsForUser(userID: HashedUserID) {
try {
const row = await db.prepare("get", `SELECT SUM("views") as "viewCount" FROM "sponsorTimes" WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`, [userID]);
const row = await db.prepare("get", `SELECT SUM("views") as "viewCount" FROM "sponsorTimes" WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`, [userID], { useReplica: true });
return row?.viewCount ?? 0;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return false;
}
}
async function dbGetIgnoredViewsForUser(userID: HashedUserID) {
try {
const row = await db.prepare("get", `SELECT SUM("views") as "ignoredViewCount" FROM "sponsorTimes" WHERE "userID" = ? AND ( "votes" <= -2 OR "shadowHidden" = 1 )`, [userID]);
const row = await db.prepare("get", `SELECT SUM("views") as "ignoredViewCount" FROM "sponsorTimes" WHERE "userID" = ? AND ( "votes" <= -2 OR "shadowHidden" = 1 )`, [userID], { useReplica: true });
return row?.ignoredViewCount ?? 0;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return false;
}
}
async function dbGetWarningsForUser(userID: HashedUserID): Promise<number> {
try {
const row = await db.prepare("get", `SELECT COUNT(*) as total FROM "warnings" WHERE "userID" = ? AND "enabled" = 1`, [userID]);
const row = await db.prepare("get", `SELECT COUNT(*) as total FROM "warnings" WHERE "userID" = ? AND "enabled" = 1`, [userID], { useReplica: true });
return row?.total ?? 0;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(`Couldn't get warnings for user ${userID}. returning 0`);
return 0;
}
@@ -79,18 +80,18 @@ async function dbGetWarningsForUser(userID: HashedUserID): Promise<number> {
async function dbGetLastSegmentForUser(userID: HashedUserID): Promise<SegmentUUID> {
try {
const row = await db.prepare("get", `SELECT "UUID" FROM "sponsorTimes" WHERE "userID" = ? ORDER BY "timeSubmitted" DESC LIMIT 1`, [userID]);
const row = await db.prepare("get", `SELECT "UUID" FROM "sponsorTimes" WHERE "userID" = ? ORDER BY "timeSubmitted" DESC LIMIT 1`, [userID], { useReplica: true });
return row?.UUID ?? null;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return null;
}
}
async function dbGetActiveWarningReasonForUser(userID: HashedUserID): Promise<string> {
try {
const row = await db.prepare("get", `SELECT reason FROM "warnings" WHERE "userID" = ? AND "enabled" = 1 ORDER BY "issueTime" DESC LIMIT 1`, [userID]);
const row = await db.prepare("get", `SELECT reason FROM "warnings" WHERE "userID" = ? AND "enabled" = 1 ORDER BY "issueTime" DESC LIMIT 1`, [userID], { useReplica: true });
return row?.reason ?? "";
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(`Couldn't get reason for user ${userID}. returning blank`);
return "";
}
@@ -98,13 +99,22 @@ async function dbGetActiveWarningReasonForUser(userID: HashedUserID): Promise<st
async function dbGetBanned(userID: HashedUserID): Promise<boolean> {
try {
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ? LIMIT 1`, [userID]);
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ? LIMIT 1`, [userID], { useReplica: true });
return row?.userCount > 0 ?? false;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return false;
}
}
async function getPermissions(userID: HashedUserID): Promise<Record<string, boolean>> {
const result: Record<string, boolean> = {};
for (const category of config.categoryList) {
result[category] = (await canSubmit(userID, category as Category)).canSubmit;
}
return result;
}
type cases = Record<string, any>
const executeIfFunction = (f: any) =>
@@ -119,16 +129,18 @@ const functionSwitch = (cases: cases) => (defaultCase: string) => (key: string)
const dbGetValue = (userID: HashedUserID, property: string): Promise<string|SegmentUUID|number> => {
return functionSwitch({
userID,
userName: dbGetUsername(userID),
ignoredSegmentCount: dbGetIgnoredSegmentCount(userID),
viewCount: dbGetViewsForUser(userID),
ignoredViewCount: dbGetIgnoredViewsForUser(userID),
warnings: dbGetWarningsForUser(userID),
warningReason: dbGetActiveWarningReasonForUser(userID),
banned: dbGetBanned(userID),
reputation: getReputation(userID),
vip: isUserVIP(userID),
lastSegmentID: dbGetLastSegmentForUser(userID),
userName: () => dbGetUsername(userID),
ignoredSegmentCount: () => dbGetIgnoredSegmentCount(userID),
viewCount: () => dbGetViewsForUser(userID),
ignoredViewCount: () => dbGetIgnoredViewsForUser(userID),
warnings: () => dbGetWarningsForUser(userID),
warningReason: () => dbGetActiveWarningReasonForUser(userID),
banned: () => dbGetBanned(userID),
reputation: () => getReputation(userID),
vip: () => isUserVIP(userID),
lastSegmentID: () => dbGetLastSegmentForUser(userID),
permissions: () => getPermissions(userID),
freeChaptersAccess: () => true
})("")(property);
};
@@ -138,7 +150,7 @@ async function getUserInfo(req: Request, res: Response): Promise<Response> {
const defaultProperties: string[] = ["userID", "userName", "minutesSaved", "segmentCount", "ignoredSegmentCount",
"viewCount", "ignoredViewCount", "warnings", "warningReason", "reputation",
"vip", "lastSegmentID"];
const allProperties: string[] = [...defaultProperties, "banned"];
const allProperties: string[] = [...defaultProperties, "banned", "permissions", "freeChaptersAccess"];
let paramValues: string[] = req.query.values
? JSON.parse(req.query.values as string)
: req.query.value
@@ -175,9 +187,9 @@ async function getUserInfo(req: Request, res: Response): Promise<Response> {
export async function endpoint(req: Request, res: Response): Promise<Response> {
try {
return await getUserInfo(req, res);
} catch (err) {
} catch (err) /* istanbul ignore next */ {
if (err instanceof SyntaxError) { // catch JSON.parse error
return res.status(400).send("Invalid values JSON");
} else return res.sendStatus(500);
}
}
}

View File

@@ -21,6 +21,7 @@ async function dbGetUserSummary(userID: HashedUserID, fetchCategoryStats: boolea
SUM(CASE WHEN "category" = 'poi_highlight' THEN 1 ELSE 0 END) as "categorySumHighlight",
SUM(CASE WHEN "category" = 'filler' THEN 1 ELSE 0 END) as "categorySumFiller",
SUM(CASE WHEN "category" = 'exclusive_access' THEN 1 ELSE 0 END) as "categorySumExclusiveAccess",
SUM(CASE WHEN "category" = 'chapter' THEN 1 ELSE 0 END) as "categorySumChapter",
`;
}
if (fetchActionTypeStats) {
@@ -29,15 +30,16 @@ async function dbGetUserSummary(userID: HashedUserID, fetchCategoryStats: boolea
SUM(CASE WHEN "actionType" = 'mute' THEN 1 ELSE 0 END) as "typeSumMute",
SUM(CASE WHEN "actionType" = 'full' THEN 1 ELSE 0 END) as "typeSumFull",
SUM(CASE WHEN "actionType" = 'poi' THEN 1 ELSE 0 END) as "typeSumPoi",
SUM(CASE WHEN "actionType" = 'chapter' THEN 1 ELSE 0 END) as "typeSumChapter",
`;
}
try {
const row = await db.prepare("get", `
SELECT SUM(((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views") as "minutesSaved",
SELECT SUM(CASE WHEN "actionType" = 'chapter' THEN 0 ELSE ((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views" END) as "minutesSaved",
${additionalQuery}
count(*) as "segmentCount"
FROM "sponsorTimes"
WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" !=1`,
WHERE "userID" = ? AND "votes" > -2 AND "shadowHidden" != 1`,
[maxRewardTimePerSegmentInSeconds, maxRewardTimePerSegmentInSeconds, userID]);
const source = (row.minutesSaved != null) ? row : {};
const handler = { get: (target: Record<string, any>, name: string) => target?.[name] || 0 };
@@ -60,6 +62,7 @@ async function dbGetUserSummary(userID: HashedUserID, fetchCategoryStats: boolea
poi_highlight: proxy.categorySumHighlight,
filler: proxy.categorySumFiller,
exclusive_access: proxy.categorySumExclusiveAccess,
chapter: proxy.categorySumChapter,
};
}
if (fetchActionTypeStats) {
@@ -67,11 +70,12 @@ async function dbGetUserSummary(userID: HashedUserID, fetchCategoryStats: boolea
skip: proxy.typeSumSkip,
mute: proxy.typeSumMute,
full: proxy.typeSumFull,
poi: proxy.typeSumPoi
poi: proxy.typeSumPoi,
chapter: proxy.typeSumChapter,
};
}
return result;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return null;
}
@@ -81,7 +85,7 @@ async function dbGetUsername(userID: HashedUserID) {
try {
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
return row?.userName ?? userID;
} catch (err) {
} catch (err) /* istanbul ignore next */ {
return false;
}
}

View File

@@ -15,7 +15,7 @@ export async function getUsername(req: Request, res: Response): Promise<Response
userID = await getHashCache(userID);
try {
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID], { useReplica: true });
if (row !== undefined) {
return res.send({
@@ -27,7 +27,7 @@ export async function getUsername(req: Request, res: Response): Promise<Response
userName: userID,
});
}
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return res.sendStatus(500);
}

166
src/routes/getVideoLabel.ts Normal file
View File

@@ -0,0 +1,166 @@
import { Request, Response } from "express";
import { db } from "../databases/databases";
import { videoLabelsHashKey, videoLabelsKey } from "../utils/redisKeys";
import { SBRecord } from "../types/lib.model";
import { DBSegment, Segment, Service, VideoData, VideoID, VideoIDHash } from "../types/segments.model";
import { Logger } from "../utils/logger";
import { QueryCacher } from "../utils/queryCacher";
import { getService } from "../utils/getService";
function transformDBSegments(segments: DBSegment[]): Segment[] {
return segments.map((chosenSegment) => ({
category: chosenSegment.category,
actionType: chosenSegment.actionType,
segment: [chosenSegment.startTime, chosenSegment.endTime],
UUID: chosenSegment.UUID,
locked: chosenSegment.locked,
votes: chosenSegment.votes,
videoDuration: chosenSegment.videoDuration,
userID: chosenSegment.userID,
description: chosenSegment.description
}));
}
async function getLabelsByVideoID(videoID: VideoID, service: Service): Promise<Segment[]> {
try {
const segments: DBSegment[] = await getSegmentsFromDBByVideoID(videoID, service);
return chooseSegment(segments);
} catch (err) {
if (err) {
Logger.error(err as string);
return null;
}
}
}
async function getLabelsByHash(hashedVideoIDPrefix: VideoIDHash, service: Service): Promise<SBRecord<VideoID, VideoData>> {
const segments: SBRecord<VideoID, VideoData> = {};
try {
type SegmentWithHashPerVideoID = SBRecord<VideoID, { hash: VideoIDHash, segments: DBSegment[] }>;
const segmentPerVideoID: SegmentWithHashPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service))
.reduce((acc: SegmentWithHashPerVideoID, segment: DBSegment) => {
acc[segment.videoID] = acc[segment.videoID] || {
hash: segment.hashedVideoID,
segments: []
};
acc[segment.videoID].segments ??= [];
acc[segment.videoID].segments.push(segment);
return acc;
}, {});
for (const [videoID, videoData] of Object.entries(segmentPerVideoID)) {
const data: VideoData = {
segments: chooseSegment(videoData.segments),
};
if (data.segments.length > 0) {
segments[videoID] = data;
}
}
return segments;
} catch (err) {
Logger.error(err as string);
return null;
}
}
async function getSegmentsFromDBByHash(hashedVideoIDPrefix: VideoIDHash, service: Service): Promise<DBSegment[]> {
const fetchFromDB = () => db
.prepare(
"all",
`SELECT "startTime", "endTime", "videoID", "votes", "locked", "UUID", "userID", "category", "actionType", "hashedVideoID", "description" FROM "sponsorTimes"
WHERE "hashedVideoID" LIKE ? AND "service" = ? AND "actionType" = 'full' AND "hidden" = 0 AND "shadowHidden" = 0`,
[`${hashedVideoIDPrefix}%`, service]
) as Promise<DBSegment[]>;
if (hashedVideoIDPrefix.length === 3) {
return await QueryCacher.get(fetchFromDB, videoLabelsHashKey(hashedVideoIDPrefix, service));
}
return await fetchFromDB();
}
async function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): Promise<DBSegment[]> {
const fetchFromDB = () => db
.prepare(
"all",
`SELECT "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "description" FROM "sponsorTimes"
WHERE "videoID" = ? AND "service" = ? AND "actionType" = 'full' AND "hidden" = 0 AND "shadowHidden" = 0`,
[videoID, service]
) as Promise<DBSegment[]>;
return await QueryCacher.get(fetchFromDB, videoLabelsKey(videoID, service));
}
function chooseSegment<T extends DBSegment>(choices: T[]): Segment[] {
// filter out -2 segments
choices = choices.filter((segment) => segment.votes > -2);
const results = [];
// trivial decisions
if (choices.length === 0) {
return [];
} else if (choices.length === 1) {
return transformDBSegments(choices);
}
// if locked, only choose from locked
const locked = choices.filter((segment) => segment.locked);
if (locked.length > 0) {
choices = locked;
}
//no need to filter, just one label
if (choices.length === 1) {
return transformDBSegments(choices);
}
// sponsor > exclusive > selfpromo
const findCategory = (category: string) => choices.find((segment) => segment.category === category);
const categoryResult = findCategory("sponsor") ?? findCategory("exclusive_access") ?? findCategory("selfpromo");
if (categoryResult) results.push(categoryResult);
return transformDBSegments(results);
}
async function handleGetLabel(req: Request, res: Response): Promise<Segment[] | false> {
const videoID = req.query.videoID as VideoID;
if (!videoID) {
res.status(400).send("videoID not specified");
return false;
}
const service = getService(req.query.service, req.body.service);
const segments = await getLabelsByVideoID(videoID, service);
if (!segments || segments.length === 0) {
res.sendStatus(404);
return false;
}
return segments;
}
async function endpoint(req: Request, res: Response): Promise<Response> {
try {
const segments = await handleGetLabel(req, res);
// If false, res.send has already been called
if (segments) {
//send result
return res.send(segments);
}
} catch (err) {
if (err instanceof SyntaxError) {
return res.status(400).send("Categories parameter does not match format requirements.");
} else return res.sendStatus(500);
}
}
export {
getLabelsByVideoID,
getLabelsByHash,
endpoint
};

View File

@@ -0,0 +1,26 @@
import { hashPrefixTester } from "../utils/hashPrefixTester";
import { getLabelsByHash } from "./getVideoLabel";
import { Request, Response } from "express";
import { VideoIDHash, Service } from "../types/segments.model";
import { getService } from "../utils/getService";
export async function getVideoLabelsByHash(req: Request, res: Response): Promise<Response> {
let hashPrefix = req.params.prefix as VideoIDHash;
if (!req.params.prefix || !hashPrefixTester(req.params.prefix)) {
return res.status(400).send("Hash prefix does not match format requirements."); // Exit early on faulty prefix
}
hashPrefix = hashPrefix.toLowerCase() as VideoIDHash;
const service: Service = getService(req.query.service, req.body.service);
// Get all video id's that match hash prefix
const segments = await getLabelsByHash(hashPrefix, service);
if (!segments) return res.status(404).json([]);
const output = Object.entries(segments).map(([videoID, data]) => ({
videoID,
segments: data.segments,
}));
return res.status(output.length === 0 ? 404 : 200).json(output);
}

View File

@@ -15,7 +15,7 @@ export async function getViewsForUser(req: Request, res: Response): Promise<Resp
userID = await getHashCache(userID);
try {
const row = await db.prepare("get", `SELECT SUM("views") as "viewCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID]);
const row = await db.prepare("get", `SELECT SUM("views") as "viewCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID], { useReplica: true });
//increase the view count by one
if (row.viewCount != null) {
@@ -25,7 +25,7 @@ export async function getViewsForUser(req: Request, res: Response): Promise<Resp
} else {
return res.sendStatus(404);
}
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -1,24 +0,0 @@
import { handleGetSegments } from "./getSkipSegments";
import { Request, Response } from "express";
export async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise<Response> {
const segments = await handleGetSegments(req, res);
if (segments) {
// Convert to old outputs
const sponsorTimes = [];
const UUIDs = [];
for (const segment of segments) {
sponsorTimes.push(segment.segment);
UUIDs.push(segment.UUID);
}
return res.send({
sponsorTimes,
UUIDs,
});
}
// Error has already been handled in the other method
}

149
src/routes/postBranding.ts Normal file
View File

@@ -0,0 +1,149 @@
import { Request, Response } from "express";
import { config } from "../config";
import { db, privateDB } from "../databases/databases";
import { BrandingSubmission, BrandingUUID, TimeThumbnailSubmission } from "../types/branding.model";
import { HashedIP, IPAddress, VideoID } from "../types/segments.model";
import { HashedUserID } from "../types/user.model";
import { getHashCache } from "../utils/getHashCache";
import { getIP } from "../utils/getIP";
import { getService } from "../utils/getService";
import { isUserVIP } from "../utils/isUserVIP";
import { Logger } from "../utils/logger";
import crypto from "crypto";
import { QueryCacher } from "../utils/queryCacher";
enum BrandingType {
Title,
Thumbnail
}
interface ExistingVote {
UUID: BrandingUUID;
type: number;
id: number;
}
export async function postBranding(req: Request, res: Response) {
const { videoID, userID, title, thumbnail } = req.body as BrandingSubmission;
const service = getService(req.body.service);
if (!videoID || !userID || userID.length < 30 || !service
|| ((!title || !title.title)
&& (!thumbnail || thumbnail.original == null
|| (!thumbnail.original && !(thumbnail as TimeThumbnailSubmission).timestamp)))) {
res.status(400).send("Bad Request");
return;
}
try {
const hashedUserID = await getHashCache(userID);
// const isVip = await isUserVIP(hashedUserID);
const isVip = false; // TODO: In future, reenable locks
const hashedVideoID = await getHashCache(videoID, 1);
const hashedIP = await getHashCache(getIP(req) + config.globalSalt as IPAddress);
const now = Date.now();
const voteType = 1;
await Promise.all([(async () => {
if (title) {
const existingUUID = (await db.prepare("get", `SELECT "UUID" from "titles" where "videoID" = ? AND "title" = ?`, [videoID, title.title]))?.UUID;
const UUID = existingUUID || crypto.randomUUID();
const existingVote = await handleExistingVotes(BrandingType.Title, videoID, hashedUserID, UUID, hashedIP, voteType);
if (existingUUID) {
await updateVoteTotals(BrandingType.Title, existingVote, UUID, isVip);
} else {
await db.prepare("run", `INSERT INTO "titles" ("videoID", "title", "original", "userID", "service", "hashedVideoID", "timeSubmitted", "UUID") VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[videoID, title.title, title.original ? 1 : 0, hashedUserID, service, hashedVideoID, now, UUID]);
await db.prepare("run", `INSERT INTO "titleVotes" ("UUID", "votes", "locked", "shadowHidden") VALUES (?, 0, ?, 0);`,
[UUID, isVip ? 1 : 0]);
}
if (isVip) {
// unlock all other titles
await db.prepare("run", `UPDATE "titleVotes" SET "locked" = 0 WHERE "UUID" != ? AND "videoID" = ?`, [UUID, videoID]);
}
}
})(), (async () => {
if (thumbnail) {
const existingUUID = thumbnail.original
? (await db.prepare("get", `SELECT "UUID" from "thumbnails" where "videoID" = ? AND "original" = 1`, [videoID]))?.UUID
: (await db.prepare("get", `SELECT "thumbnails"."UUID" from "thumbnailTimestamps" JOIN "thumbnails" ON "thumbnails"."UUID" = "thumbnailTimestamps"."UUID"
WHERE "thumbnailTimestamps"."timestamp" = ? AND "thumbnails"."videoID" = ?`, [(thumbnail as TimeThumbnailSubmission).timestamp, videoID]))?.UUID;
const UUID = existingUUID || crypto.randomUUID();
const existingVote = await handleExistingVotes(BrandingType.Thumbnail, videoID, hashedUserID, UUID, hashedIP, voteType);
if (existingUUID) {
await updateVoteTotals(BrandingType.Thumbnail, existingVote, UUID, isVip);
} else {
await db.prepare("run", `INSERT INTO "thumbnails" ("videoID", "original", "userID", "service", "hashedVideoID", "timeSubmitted", "UUID") VALUES (?, ?, ?, ?, ?, ?, ?)`,
[videoID, thumbnail.original ? 1 : 0, hashedUserID, service, hashedVideoID, now, UUID]);
await db.prepare("run", `INSERT INTO "thumbnailVotes" ("UUID", "votes", "locked", "shadowHidden") VALUES (?, 0, ?, 0)`,
[UUID, isVip ? 1 : 0]);
if (!thumbnail.original) {
await db.prepare("run", `INSERT INTO "thumbnailTimestamps" ("UUID", "timestamp") VALUES (?, ?)`,
[UUID, (thumbnail as TimeThumbnailSubmission).timestamp]);
}
if (isVip) {
// unlock all other titles
await db.prepare("run", `UPDATE "thumbnailVotes" SET "locked" = 0 WHERE "UUID" != ? AND "videoID" = ?`, [UUID, videoID]);
}
}
}
})()]);
QueryCacher.clearBrandingCache({ videoID, hashedVideoID, service });
res.status(200).send("OK");
} catch (e) {
Logger.error(e as string);
res.status(500).send("Internal Server Error");
}
}
/**
* Finds an existing vote, if found, and it's for a different submission, it undoes it, and points to the new submission.
* If no existing vote, it adds one.
*/
async function handleExistingVotes(type: BrandingType, videoID: VideoID,
hashedUserID: HashedUserID, UUID: BrandingUUID, hashedIP: HashedIP, voteType: number): Promise<ExistingVote> {
const table = type === BrandingType.Title ? `"titleVotes"` : `"thumbnailVotes"`;
const existingVote = await privateDB.prepare("get", `SELECT "id", "UUID", "type" from ${table} where "videoID" = ? AND "userID" = ?`, [videoID, hashedUserID]);
if (existingVote && existingVote.UUID !== UUID) {
if (existingVote.type === 1) {
await db.prepare("run", `UPDATE ${table} SET "votes" = "votes" - 1 WHERE "UUID" = ?`, [existingVote.UUID]);
}
await privateDB.prepare("run", `UPDATE ${table} SET "type" = ?, "UUID" = ? WHERE "id" = ?`, [voteType, UUID, existingVote.id]);
} else if (!existingVote) {
await privateDB.prepare("run", `INSERT INTO ${table} ("videoID", "UUID", "userID", "hashedIP", "type") VALUES (?, ?, ?, ?, ?)`,
[videoID, UUID, hashedUserID, hashedIP, voteType]);
}
return existingVote;
}
/**
* Only called if an existing vote exists.
* Will update public vote totals and locked status.
*/
async function updateVoteTotals(type: BrandingType, existingVote: ExistingVote, UUID: BrandingUUID, isVip: boolean): Promise<void> {
if (!existingVote) return;
const table = type === BrandingType.Title ? `"titleVotes"` : `"thumbnailVotes"`;
// Don't upvote if we vote on the same submission
if (!existingVote || existingVote.UUID !== UUID) {
await db.prepare("run", `UPDATE ${table} SET "votes" = "votes" + 1 WHERE "UUID" = ?`, [UUID]);
}
if (isVip) {
await db.prepare("run", `UPDATE ${table} SET "locked" = 1 WHERE "UUID" = ?`, [UUID]);
}
}

View File

@@ -44,10 +44,15 @@ export async function postClearCache(req: Request, res: Response): Promise<Respo
hashedVideoID,
service
});
QueryCacher.clearBrandingCache({
videoID,
hashedVideoID,
service
});
return res.status(200).json({
message: `Cache cleared on video ${videoID}`
});
} catch(err) {
} catch(err) /* istanbul ignore next */ {
return res.sendStatus(500);
}
}

View File

@@ -37,7 +37,7 @@ export async function postLockCategories(req: Request, res: Response): Promise<s
if (!userIsVIP) {
res.status(403).json({
message: "Must be a VIP to mark videos.",
message: "Must be a VIP to lock videos.",
});
return;
}
@@ -66,7 +66,7 @@ export async function postLockCategories(req: Request, res: Response): Promise<s
for (const lock of locksToApply) {
try {
await db.prepare("run", `INSERT INTO "lockCategories" ("videoID", "userID", "actionType", "category", "hashedVideoID", "reason", "service") VALUES(?, ?, ?, ?, ?, ?, ?)`, [videoID, userID, lock.actionType, lock.category, hashedVideoID, reason, service]);
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(`Error submitting 'lockCategories' marker for category '${lock.category}' and actionType '${lock.actionType}' for video '${videoID}' (${service})`);
Logger.error(err as string);
res.status(500).json({
@@ -82,7 +82,7 @@ export async function postLockCategories(req: Request, res: Response): Promise<s
await db.prepare("run",
'UPDATE "lockCategories" SET "reason" = ?, "userID" = ? WHERE "videoID" = ? AND "actionType" = ? AND "category" = ? AND "service" = ?',
[reason, userID, videoID, lock.actionType, lock.category, service]);
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(`Error submitting 'lockCategories' marker for category '${lock.category}' and actionType '${lock.actionType}' for video '${videoID}' (${service})`);
Logger.error(err as string);
res.status(500).json({

View File

@@ -37,7 +37,7 @@ export async function postPurgeAllSegments(req: Request, res: Response): Promise
service
});
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -91,7 +91,7 @@ export async function postSegmentShift(req: Request, res: Response): Promise<Res
break;
}
}
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -1,7 +1,7 @@
import { config } from "../config";
import { Logger } from "../utils/logger";
import { db, privateDB } from "../databases/databases";
import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi";
import { getMaxResThumbnail } from "../utils/youtubeApi";
import { getSubmissionUUID } from "../utils/getSubmissionUUID";
import { getHash } from "../utils/getHash";
import { getHashCache } from "../utils/getHashCache";
@@ -13,7 +13,6 @@ import { ActionType, Category, IncomingSegment, IPAddress, SegmentUUID, Service,
import { deleteLockCategories } from "./deleteLockCategories";
import { QueryCacher } from "../utils/queryCacher";
import { getReputation } from "../utils/reputation";
import { APIVideoData, APIVideoInfo } from "../types/youtubeApi.model";
import { HashedUserID, UserID } from "../types/user.model";
import { isUserVIP } from "../utils/isUserVIP";
import { isUserTempVIP } from "../utils/isUserTempVIP";
@@ -21,6 +20,10 @@ import { parseUserAgent } from "../utils/userAgent";
import { getService } from "../utils/getService";
import axios from "axios";
import { vote } from "./voteOnSponsorTime";
import { canSubmit } from "../utils/permissions";
import { getVideoDetails, videoDetails } from "../utils/getVideoDetails";
import * as youtubeID from "../utils/youtubeID";
import { banUser } from "./shadowBanUser";
type CheckResult = {
pass: boolean,
@@ -34,7 +37,7 @@ const CHECK_PASS: CheckResult = {
errorCode: 0
};
async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: APIVideoData, { submissionStart, submissionEnd }: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) {
async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: videoDetails, { submissionStart, submissionEnd }: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) {
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
const userName = row !== undefined ? row.userName : null;
@@ -47,7 +50,7 @@ async function sendWebhookNotification(userID: string, videoID: string, UUID: st
"video": {
"id": videoID,
"title": youtubeData?.title,
"thumbnail": getMaxResThumbnail(youtubeData) || null,
"thumbnail": getMaxResThumbnail(videoID),
"url": `https://www.youtube.com/watch?v=${videoID}`,
},
"submission": {
@@ -63,19 +66,16 @@ async function sendWebhookNotification(userID: string, videoID: string, UUID: st
});
}
async function sendWebhooks(apiVideoInfo: APIVideoInfo, userID: string, videoID: string, UUID: string, segmentInfo: any, service: Service) {
if (apiVideoInfo && service == Service.YouTube) {
async function sendWebhooks(apiVideoDetails: videoDetails, userID: string, videoID: string, UUID: string, segmentInfo: any, service: Service) {
if (apiVideoDetails && service == Service.YouTube) {
const userSubmissionCountRow = await db.prepare("get", `SELECT count(*) as "submissionCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID]);
const { data, err } = apiVideoInfo;
if (err) return;
const startTime = parseFloat(segmentInfo.segment[0]);
const endTime = parseFloat(segmentInfo.segment[1]);
sendWebhookNotification(userID, videoID, UUID, userSubmissionCountRow.submissionCount, data, {
sendWebhookNotification(userID, videoID, UUID, userSubmissionCountRow.submissionCount, apiVideoDetails, {
submissionStart: startTime,
submissionEnd: endTime,
}, segmentInfo);
}, segmentInfo).catch((e) => Logger.error(`sending webhooks: ${e}`));
// If it is a first time submission
// Then send a notification to discord
@@ -83,7 +83,7 @@ async function sendWebhooks(apiVideoInfo: APIVideoInfo, userID: string, videoID:
axios.post(config.discordFirstTimeSubmissionsWebhookURL, {
embeds: [{
title: data?.title,
title: apiVideoDetails.title,
url: `https://www.youtube.com/watch?v=${videoID}&t=${(parseInt(startTime.toFixed(0)) - 2)}s#requiredSegment=${UUID}`,
description: `Submission ID: ${UUID}\
\n\nTimestamp: \
@@ -94,7 +94,7 @@ async function sendWebhooks(apiVideoInfo: APIVideoInfo, userID: string, videoID:
name: userID,
},
thumbnail: {
url: getMaxResThumbnail(data) || "",
url: getMaxResThumbnail(videoID),
},
}],
})
@@ -119,18 +119,10 @@ async function sendWebhooks(apiVideoInfo: APIVideoInfo, userID: string, videoID:
// Looks like this was broken for no defined youtube key - fixed but IMO we shouldn't return
// false for a pass - it was confusing and lead to this bug - any use of this function in
// the future could have the same problem.
async function autoModerateSubmission(apiVideoInfo: APIVideoInfo,
submission: { videoID: VideoID; userID: UserID; segments: IncomingSegment[], service: Service, videoDuration: number }) {
const apiVideoDuration = (apiVideoInfo: APIVideoInfo) => {
if (!apiVideoInfo) return undefined;
const { err, data } = apiVideoInfo;
// return undefined if API error
if (err) return undefined;
return data?.lengthSeconds;
};
async function autoModerateSubmission(apiVideoDetails: videoDetails,
submission: { videoID: VideoID; userID: HashedUserID; segments: IncomingSegment[], service: Service, videoDuration: number }) {
// get duration from API
const apiDuration = apiVideoDuration(apiVideoInfo);
const apiDuration = apiVideoDetails.duration;
// if API fail or returns 0, get duration from client
const duration = apiDuration || submission.videoDuration;
// return false on undefined or 0
@@ -138,14 +130,16 @@ async function autoModerateSubmission(apiVideoInfo: APIVideoInfo,
const segments = submission.segments;
// map all times to float array
const allSegmentTimes = segments.map(segment => [parseFloat(segment.segment[0]), parseFloat(segment.segment[1])]);
const allSegmentTimes = segments.filter((s) => s.actionType !== ActionType.Chapter)
.map(segment => [parseFloat(segment.segment[0]), parseFloat(segment.segment[1])]);
// add previous submissions by this user
const allSubmittedByUser = await db.prepare("all", `SELECT "startTime", "endTime" FROM "sponsorTimes" WHERE "userID" = ? AND "videoID" = ? AND "votes" > -1 AND "hidden" = 0`, [submission.userID, submission.videoID]);
const allSubmittedByUser = await db.prepare("all", `SELECT "startTime", "endTime" FROM "sponsorTimes" WHERE "userID" = ? AND "videoID" = ? AND "votes" > -1 AND "actionType" != 'chapter' AND "hidden" = 0`
, [submission.userID, submission.videoID]) as { startTime: string, endTime: string }[];
if (allSubmittedByUser) {
//add segments the user has previously submitted
const allSubmittedTimes = allSubmittedByUser.map((segment: { startTime: string, endTime: string }) => [parseFloat(segment.startTime), parseFloat(segment.endTime)]);
const allSubmittedTimes = allSubmittedByUser.map((segment) => [parseFloat(segment.startTime), parseFloat(segment.endTime)]);
allSegmentTimes.push(...allSubmittedTimes);
}
@@ -162,15 +156,7 @@ async function autoModerateSubmission(apiVideoInfo: APIVideoInfo,
return false;
}
function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise<APIVideoInfo> {
if (config.newLeafURLs !== null) {
return YouTubeAPI.listVideos(videoID, ignoreCache);
} else {
return null;
}
}
async function checkUserActiveWarning(userID: string): Promise<CheckResult> {
async function checkUserActiveWarning(userID: HashedUserID): Promise<CheckResult> {
const MILLISECONDS_IN_HOUR = 3600000;
const now = Date.now();
const warnings = (await db.prepare("all",
@@ -200,15 +186,24 @@ async function checkUserActiveWarning(userID: string): Promise<CheckResult> {
return CHECK_PASS;
}
function checkInvalidFields(videoID: VideoID, userID: UserID, segments: IncomingSegment[]): CheckResult {
async function checkInvalidFields(videoID: VideoID, userID: UserID, hashedUserID: HashedUserID
, segments: IncomingSegment[], videoDurationParam: number, userAgent: string, service: Service): Promise<CheckResult> {
const invalidFields = [];
const errors = [];
if (typeof videoID !== "string" || videoID?.length == 0) {
invalidFields.push("videoID");
}
if (typeof userID !== "string" || userID?.length < 30) {
if (service === Service.YouTube && config.mode !== "test") {
const sanitizedVideoID = youtubeID.validate(videoID) ? videoID : youtubeID.sanitize(videoID);
if (!youtubeID.validate(sanitizedVideoID)) {
invalidFields.push("videoID");
errors.push("YouTube videoID could not be extracted");
}
}
const minLength = config.minUserIDLength;
if (typeof userID !== "string" || userID?.length < minLength) {
invalidFields.push("userID");
if (userID?.length < 30) errors.push(`userID must be at least 30 characters long`);
if (userID?.length < minLength) errors.push(`userID must be at least ${minLength} characters long`);
}
if (!Array.isArray(segments) || segments.length == 0) {
invalidFields.push("segments");
@@ -223,10 +218,20 @@ function checkInvalidFields(videoID: VideoID, userID: UserID, segments: Incoming
}
if (typeof segmentPair.description !== "string"
|| (segmentPair.actionType === ActionType.Chapter && segmentPair.description.length > 60 )
|| (segmentPair.description.length !== 0 && segmentPair.actionType !== ActionType.Chapter)) {
invalidFields.push("segment description");
}
if (segmentPair.actionType === ActionType.Chapter && segmentPair.description.length > 200) {
invalidFields.push("chapter name (too long)");
}
const permission = await canSubmit(hashedUserID, segmentPair.category);
if (!permission.canSubmit) {
Logger.warn(`Rejecting submission due to lack of permissions for category ${segmentPair.category}: ${segmentPair.segment} ${hashedUserID} ${videoID} ${videoDurationParam} ${userAgent}`);
invalidFields.push(`permission to submit ${segmentPair.category}`);
errors.push(permission.reason);
}
}
if (invalidFields.length !== 0) {
@@ -235,7 +240,7 @@ function checkInvalidFields(videoID: VideoID, userID: UserID, segments: Incoming
const formattedErrors = errors.reduce((p, c, i) => p + (i !== 0 ? ". " : " ") + c, "");
return {
pass: false,
errorMessage: `No valid ${formattedFields} field(s) provided.${formattedErrors}`,
errorMessage: `No valid ${formattedFields}.${formattedErrors}`,
errorCode: 400
};
}
@@ -244,7 +249,7 @@ function checkInvalidFields(videoID: VideoID, userID: UserID, segments: Incoming
}
async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, userID: HashedUserID, videoID: VideoID,
segments: IncomingSegment[], service: string, isVIP: boolean, lockedCategoryList: Array<any>): Promise<CheckResult> {
segments: IncomingSegment[], service: Service, isVIP: boolean, isTempVIP: boolean, lockedCategoryList: Array<any>): Promise<CheckResult> {
for (let i = 0; i < segments.length; i++) {
if (segments[i] === undefined || segments[i].segment === undefined || segments[i].category === undefined) {
@@ -259,15 +264,22 @@ async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, user
// Reject segment if it's in the locked categories list
const lockIndex = lockedCategoryList.findIndex(c => segments[i].category === c.category && segments[i].actionType === c.actionType);
if (!isVIP && lockIndex !== -1) {
// TODO: Do something about the fradulent submission
QueryCacher.clearSegmentCache({
videoID,
hashedVideoID: await getHashCache(videoID, 1),
service,
userID
});
Logger.warn(`Caught a submission for a locked category. userID: '${userID}', videoID: '${videoID}', category: '${segments[i].category}', times: ${segments[i].segment}`);
return {
pass: false,
errorCode: 403,
errorMessage:
`Users have voted that new segments aren't needed for the following category: ` +
`Users have voted that all the segments required for this video have already been submitted for the following category: ` +
`'${segments[i].category}'\n` +
`${lockedCategoryList[lockIndex].reason?.length !== 0 ? `\nReason: '${lockedCategoryList[lockIndex].reason}'` : ""}\n` +
`${lockedCategoryList[lockIndex].reason?.length !== 0 ? `\nReason: '${lockedCategoryList[lockIndex].reason}\n'` : ""}` +
`You may need to refresh if you don't see the segments.\n` +
`${(segments[i].category === "sponsor" ? "\nMaybe the segment you are submitting is a different category that you have not enabled and is not a sponsor. " +
"Categories that aren't sponsor, such as self-promotion can be enabled in the options.\n" : "")}` +
`\nIf you believe this is incorrect, please contact someone on chat.sponsor.ajay.app, discord.gg/SponsorBlock or matrix.to/#/#sponsor:ajay.app`
@@ -297,11 +309,11 @@ async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, user
}
// Check for POI segments before some seconds
if (!isVIP && segments[i].actionType === ActionType.Poi && startTime < config.poiMinimumStartTime) {
if (!(isVIP || isTempVIP) && segments[i].actionType === ActionType.Poi && startTime < config.poiMinimumStartTime) {
return { pass: false, errorMessage: `POI cannot be that early`, errorCode: 400 };
}
if (!isVIP && segments[i].category === "sponsor"
if (!(isVIP || isTempVIP) && segments[i].category === "sponsor"
&& segments[i].actionType !== ActionType.Full && (endTime - startTime) < 1) {
// Too short
return { pass: false, errorMessage: "Segments must be longer than 1 second long", errorCode: 400 };
@@ -309,7 +321,7 @@ async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, user
//check if this info has already been submitted before
const duplicateCheck2Row = await db.prepare("get", `SELECT "UUID" FROM "sponsorTimes" WHERE "startTime" = ?
and "endTime" = ? and "category" = ? and "actionType" = ? and "videoID" = ? and "service" = ?`, [startTime, endTime, segments[i].category, segments[i].actionType, videoID, service]);
and "endTime" = ? and "category" = ? and "actionType" = ? and "description" = ? and "videoID" = ? and "service" = ?`, [startTime, endTime, segments[i].category, segments[i].actionType, segments[i].description, videoID, service]);
if (duplicateCheck2Row) {
if (segments[i].actionType === ActionType.Full) {
// Forward as vote
@@ -325,15 +337,15 @@ async function checkEachSegmentValid(rawIP: IPAddress, paramUserID: UserID, user
return CHECK_PASS;
}
async function checkByAutoModerator(videoID: any, userID: any, segments: Array<any>, service:string, apiVideoInfo: APIVideoInfo, videoDuration: number): Promise<CheckResult> {
async function checkByAutoModerator(videoID: VideoID, userID: HashedUserID, segments: IncomingSegment[], service: Service, apiVideoDetails: videoDetails, videoDuration: number): Promise<CheckResult> {
// Auto moderator check
if (service == Service.YouTube) {
const autoModerateResult = await autoModerateSubmission(apiVideoInfo, { userID, videoID, segments, service, videoDuration });
const autoModerateResult = await autoModerateSubmission(apiVideoDetails, { videoID, userID, segments, service, videoDuration });
if (autoModerateResult) {
return {
pass: false,
errorCode: 403,
errorMessage: `Request rejected by auto moderator: ${autoModerateResult} If this is an issue, send a message on Discord.`
errorMessage: `Submissions rejected: ${autoModerateResult} If this is an issue, send a message on Discord.`
};
}
}
@@ -357,12 +369,13 @@ async function updateDataIfVideoDurationChange(videoID: VideoID, service: Servic
const videoDurationChanged = (videoDuration: number) => videoDuration != 0
&& previousSubmissions.length > 0 && !previousSubmissions.some((e) => Math.abs(videoDuration - e.videoDuration) < 2);
let apiVideoInfo: APIVideoInfo = null;
let apiVideoDetails: videoDetails = null;
if (service == Service.YouTube) {
// Don't use cache if we don't know the video duration, or the client claims that it has changed
apiVideoInfo = await getYouTubeVideoInfo(videoID, !videoDurationParam || previousSubmissions.length === 0 || videoDurationChanged(videoDurationParam));
const ignoreCache = !videoDurationParam || previousSubmissions.length === 0 || videoDurationChanged(videoDurationParam);
apiVideoDetails = await getVideoDetails(videoID, ignoreCache);
}
const apiVideoDuration = apiVideoInfo?.data?.lengthSeconds as VideoDuration;
const apiVideoDuration = apiVideoDetails?.duration as VideoDuration;
if (!videoDurationParam || (apiVideoDuration && Math.abs(videoDurationParam - apiVideoDuration) > 2)) {
// If api duration is far off, take that one instead (it is only precise to seconds, not millis)
videoDuration = apiVideoDuration || 0 as VideoDuration;
@@ -375,12 +388,12 @@ async function updateDataIfVideoDurationChange(videoID: VideoID, service: Servic
await db.prepare("run", `UPDATE "sponsorTimes" SET "hidden" = 1 WHERE "UUID" = ?`, [submission.UUID]);
}
lockedCategoryList = [];
deleteLockCategories(videoID, null, null, service);
deleteLockCategories(videoID, null, null, service).catch((e) => Logger.error(`deleting lock categories: ${e}`));
}
return {
videoDuration,
apiVideoInfo,
apiVideoDetails,
lockedCategoryList
};
}
@@ -478,36 +491,39 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
// eslint-disable-next-line prefer-const
let { videoID, userID: paramUserID, service, videoDuration, videoDurationParam, segments, userAgent } = preprocessInput(req);
const invalidCheckResult = checkInvalidFields(videoID, paramUserID, segments);
//hash the userID
if (!paramUserID) {
return res.status(400).send("No userID provided");
}
const userID: HashedUserID = await getHashCache(paramUserID);
const invalidCheckResult = await checkInvalidFields(videoID, paramUserID, userID, segments, videoDurationParam, userAgent, service);
if (!invalidCheckResult.pass) {
return res.status(invalidCheckResult.errorCode).send(invalidCheckResult.errorMessage);
}
//hash the userID
const userID = await getHashCache(paramUserID);
const userWarningCheckResult = await checkUserActiveWarning(userID);
if (!userWarningCheckResult.pass) {
Logger.warn(`Caught a submission for a warned user. userID: '${userID}', videoID: '${videoID}', category: '${segments.reduce<string>((prev, val) => `${prev} ${val.category}`, "")}', times: ${segments.reduce<string>((prev, val) => `${prev} ${val.segment}`, "")}`);
return res.status(userWarningCheckResult.errorCode).send(userWarningCheckResult.errorMessage);
}
const isVIP = await isUserVIP(userID);
const isTempVIP = await isUserTempVIP(userID, videoID);
const isVIP = (await isUserVIP(userID));
const isTempVIP = (await isUserTempVIP(userID, videoID));
const rawIP = getIP(req);
const newData = await updateDataIfVideoDurationChange(videoID, service, videoDuration, videoDurationParam);
videoDuration = newData.videoDuration;
const { lockedCategoryList, apiVideoInfo } = newData;
const { lockedCategoryList, apiVideoDetails } = newData;
// Check if all submissions are correct
const segmentCheckResult = await checkEachSegmentValid(rawIP, paramUserID, userID, videoID, segments, service, isVIP, lockedCategoryList);
const segmentCheckResult = await checkEachSegmentValid(rawIP, paramUserID, userID, videoID, segments, service, isVIP, isTempVIP, lockedCategoryList);
if (!segmentCheckResult.pass) {
return res.status(segmentCheckResult.errorCode).send(segmentCheckResult.errorMessage);
}
if (!isVIP && !isTempVIP) {
const autoModerateCheckResult = await checkByAutoModerator(videoID, userID, segments, service, apiVideoInfo, videoDurationParam);
if (!(isVIP || isTempVIP)) {
const autoModerateCheckResult = await checkByAutoModerator(videoID, userID, segments, service, apiVideoDetails, videoDurationParam);
if (!autoModerateCheckResult.pass) {
return res.status(autoModerateCheckResult.errorCode).send(autoModerateCheckResult.errorMessage);
}
@@ -530,21 +546,30 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
// }
//check to see if this user is shadowbanned
const shadowBanRow = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ? LIMIT 1`, [userID]);
const userBanCount = (await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ? LIMIT 1`, [userID]))?.userCount;
const ipBanCount = (await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedIPs" WHERE "hashedIP" = ? LIMIT 1`, [hashedIP]))?.userCount;
const shadowBanCount = userBanCount || ipBanCount;
const startingVotes = 0;
const reputation = await getReputation(userID);
if (!userBanCount && ipBanCount) {
// Make sure the whole user is banned
banUser(userID, true, true, 1, config.categoryList as Category[])
.catch((e) => Logger.error(`Error banning user after submitting from a banned IP: ${e}`));
}
for (const segmentInfo of segments) {
// Full segments are always rejected since there can only be one, so shadow hide wouldn't work
if (segmentInfo.ignoreSegment
|| (shadowBanRow.userCount && segmentInfo.actionType === ActionType.Full)) {
|| (shadowBanCount && segmentInfo.actionType === ActionType.Full)) {
continue;
}
//this can just be a hash of the data
//it's better than generating an actual UUID like what was used before
//also better for duplication checking
const UUID = getSubmissionUUID(videoID, segmentInfo.category, segmentInfo.actionType, userID, parseFloat(segmentInfo.segment[0]), parseFloat(segmentInfo.segment[1]), service);
const UUID = getSubmissionUUID(videoID, segmentInfo.category, segmentInfo.actionType,
segmentInfo.description, userID, parseFloat(segmentInfo.segment[0]), parseFloat(segmentInfo.segment[1]), service);
const hashedVideoID = getHash(videoID, 1);
const startingLocked = isVIP ? 1 : 0;
@@ -553,17 +578,17 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "category", "actionType", "service", "videoDuration", "reputation", "shadowHidden", "hashedVideoID", "userAgent", "description")
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
videoID, segmentInfo.segment[0], segmentInfo.segment[1], startingVotes, startingLocked, UUID, userID, timeSubmitted, 0
, segmentInfo.category, segmentInfo.actionType, service, videoDuration, reputation, shadowBanRow.userCount, hashedVideoID, userAgent, segmentInfo.description
, segmentInfo.category, segmentInfo.actionType, service, videoDuration, reputation, shadowBanCount, hashedVideoID, userAgent, segmentInfo.description
],
);
//add to private db as well
await privateDB.prepare("run", `INSERT INTO "sponsorTimes" VALUES(?, ?, ?, ?)`, [videoID, hashedIP, timeSubmitted, service]);
await db.prepare("run", `INSERT INTO "videoInfo" ("videoID", "channelID", "title", "published", "genreUrl")
SELECT ?, ?, ?, ?, ?
await db.prepare("run", `INSERT INTO "videoInfo" ("videoID", "channelID", "title", "published")
SELECT ?, ?, ?, ?
WHERE NOT EXISTS (SELECT 1 FROM "videoInfo" WHERE "videoID" = ?)`, [
videoID, apiVideoInfo?.data?.authorId || "", apiVideoInfo?.data?.title || "", apiVideoInfo?.data?.published || 0, apiVideoInfo?.data?.genreUrl || "", videoID]);
videoID, apiVideoDetails?.authorId || "", apiVideoDetails?.title || "", apiVideoDetails?.published || 0, videoID]);
// Clear redis cache for this video
QueryCacher.clearSegmentCache({
@@ -591,7 +616,7 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
}
for (let i = 0; i < segments.length; i++) {
sendWebhooks(apiVideoInfo, userID, videoID, UUIDs[i], segments[i], service);
sendWebhooks(apiVideoDetails, userID, videoID, UUIDs[i], segments[i], service).catch((e) => Logger.error(`call send webhooks ${e}`));
}
return res.json(newSegments);
}

View File

@@ -5,6 +5,7 @@ import { isUserVIP } from "../utils/isUserVIP";
import { getHashCache } from "../utils/getHashCache";
import { HashedUserID, UserID } from "../types/user.model";
import { config } from "../config";
import { generateWarningDiscord, warningData, dispatchEvent } from "../utils/webhookUtils";
type warningEntry = {
userID: HashedUserID,
@@ -21,18 +22,18 @@ function checkExpiredWarning(warning: warningEntry): boolean {
return warning.issueTime > expiry && !warning.enabled;
}
const getUsername = (userID: HashedUserID) => db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID], { useReplica: true });
export async function postWarning(req: Request, res: Response): Promise<Response> {
// exit early if no body passed in
if (!req.body.userID && !req.body.issuerUserID) return res.status(400).json({ "message": "Missing parameters" });
// Collect user input data
const issuerUserID: HashedUserID = await getHashCache(<UserID> req.body.issuerUserID);
const userID: UserID = req.body.userID;
if (!req.body.userID) return res.status(400).json({ "message": "Missing parameters" });
const issuerUserID: HashedUserID = req.body.issuerUserID ? await getHashCache(req.body.issuerUserID as UserID) : null;
const userID: HashedUserID = issuerUserID ? req.body.userID : await getHashCache(req.body.userID as UserID);
const issueTime = new Date().getTime();
const enabled: boolean = req.body.enabled ?? true;
const reason: string = req.body.reason ?? "";
// Ensure user is a VIP
if (!await isUserVIP(issuerUserID)) {
if ((!issuerUserID && enabled) || (issuerUserID && !await isUserVIP(issuerUserID))) {
Logger.warn(`Permission violation: User ${issuerUserID} attempted to warn user ${userID}.`);
return res.status(403).json({ "message": "Not a VIP" });
}
@@ -52,8 +53,8 @@ export async function postWarning(req: Request, res: Response): Promise<Response
// check if warning is still within issue time and warning is not enabled
} else if (checkExpiredWarning(previousWarning) ) {
await db.prepare(
"run", 'UPDATE "warnings" SET "enabled" = 1 WHERE "userID" = ? AND "issueTime" = ?',
[userID, previousWarning.issueTime]
"run", 'UPDATE "warnings" SET "enabled" = 1, "reason" = ? WHERE "userID" = ? AND "issueTime" = ?',
[reason, userID, previousWarning.issueTime]
);
resultStatus = "re-enabled";
} else {
@@ -64,6 +65,27 @@ export async function postWarning(req: Request, res: Response): Promise<Response
resultStatus = "removed from";
}
const targetUsername = await getUsername(userID) ?? null;
const issuerUsername = await getUsername(issuerUserID) ?? null;
const webhookData = {
target: {
userID,
username: targetUsername
},
issuer: {
userID: issuerUserID,
username: issuerUsername
},
reason
} as warningData;
try {
const warning = generateWarningDiscord(webhookData);
dispatchEvent("warning", warning);
} catch /* istanbul ignore next */ (err) {
Logger.error(`Error sending warning to Discord ${err}`);
}
return res.status(200).json({
message: `Warning ${resultStatus} user '${userID}'.`,
});

View File

@@ -1,91 +0,0 @@
import { Request, Response } from "express";
import { db } from "../../databases/databases";
import { RatingType } from "../../types/ratings.model";
import { Service, VideoID, VideoIDHash } from "../../types/segments.model";
import { getService } from "../../utils/getService";
import { hashPrefixTester } from "../../utils/hashPrefixTester";
import { Logger } from "../../utils/logger";
import { QueryCacher } from "../../utils/queryCacher";
import { ratingHashKey } from "../../utils/redisKeys";
interface DBRating {
videoID: VideoID,
hashedVideoID: VideoIDHash,
service: Service,
type: RatingType,
count: number
}
export async function getRating(req: Request, res: Response): Promise<Response> {
let hashPrefixes: VideoIDHash[] = [];
try {
hashPrefixes = req.query.hashPrefixes
? JSON.parse(req.query.hashPrefixes as string)
: Array.isArray(req.query.prefix)
? req.query.prefix
: [req.query.prefix ?? req.params.prefix];
if (!Array.isArray(hashPrefixes)) {
return res.status(400).send("hashPrefixes parameter does not match format requirements.");
}
hashPrefixes.map((hashPrefix) => hashPrefix?.toLowerCase());
} catch(error) {
return res.status(400).send("Bad parameter: hashPrefixes (invalid JSON)");
}
if (hashPrefixes.length === 0 || hashPrefixes.length > 75
|| hashPrefixes.some((hashPrefix) => !hashPrefix || !hashPrefixTester(hashPrefix))) {
return res.status(400).send("Hash prefix does not match format requirements."); // Exit early on faulty prefix
}
let types: RatingType[] = [];
try {
types = req.query.types
? JSON.parse(req.query.types as string)
: req.query.type
? Array.isArray(req.query.type)
? req.query.type
: [req.query.type]
: [RatingType.Upvote, RatingType.Downvote];
if (!Array.isArray(types)) {
return res.status(400).send("Types parameter does not match format requirements.");
}
types = types.map((type) => parseInt(type as unknown as string, 10));
} catch(error) {
return res.status(400).send("Bad parameter: types (invalid JSON)");
}
const service: Service = getService(req.query.service, req.body.service);
try {
const ratings = (await getRatings(hashPrefixes, service))
.filter((rating) => types.includes(rating.type))
.map((rating) => ({
videoID: rating.videoID,
hash: rating.hashedVideoID,
service: rating.service,
type: rating.type,
count: rating.count
}));
return res.status((ratings.length) ? 200 : 404)
.send(ratings ?? []);
} catch (err) {
Logger.error(err as string);
return res.sendStatus(500);
}
}
function getRatings(hashPrefixes: VideoIDHash[], service: Service): Promise<DBRating[]> {
const fetchFromDB = (hashPrefixes: VideoIDHash[]) => db
.prepare(
"all",
`SELECT "videoID", "hashedVideoID", "type", "count" FROM "ratings" WHERE "hashedVideoID" ~* ? AND "service" = ? ORDER BY "hashedVideoID"`,
[`^(?:${hashPrefixes.join("|")})`, service]
) as Promise<DBRating[]>;
return (hashPrefixes.every((hashPrefix) => hashPrefix.length === 4))
? QueryCacher.getAndSplit(fetchFromDB, (prefix) => ratingHashKey(prefix, service), "hashedVideoID", hashPrefixes)
: fetchFromDB(hashPrefixes);
}

View File

@@ -1,53 +0,0 @@
import { Logger } from "../../utils/logger";
import { HashedUserID, UserID } from "../../types/user.model";
import { getHash } from "../../utils/getHash";
import { getHashCache } from "../../utils/getHashCache";
import { Request, Response } from "express";
import { Service, VideoID } from "../../types/segments.model";
import { QueryCacher } from "../../utils/queryCacher";
import { isUserVIP } from "../../utils/isUserVIP";
import { VideoIDHash } from "../../types/segments.model";
import { getService } from "../..//utils/getService";
export async function postClearCache(req: Request, res: Response): Promise<Response> {
const videoID = req.query.videoID as VideoID;
const userID = req.query.userID as UserID;
const service = getService(req.query.service as Service);
const invalidFields = [];
if (typeof videoID !== "string") {
invalidFields.push("videoID");
}
if (typeof userID !== "string") {
invalidFields.push("userID");
}
if (invalidFields.length !== 0) {
// invalid request
const fields = invalidFields.reduce((p, c, i) => p + (i !== 0 ? ", " : "") + c, "");
return res.status(400).send(`No valid ${fields} field(s) provided`);
}
// hash the userID as early as possible
const hashedUserID: HashedUserID = await getHashCache(userID);
// hash videoID
const hashedVideoID: VideoIDHash = getHash(videoID, 1);
// Ensure user is a VIP
if (!(await isUserVIP(hashedUserID))){
Logger.warn(`Permission violation: User ${hashedUserID} attempted to clear cache for video ${videoID}.`);
return res.status(403).json({ "message": "Not a VIP" });
}
try {
QueryCacher.clearRatingCache({
hashedVideoID,
service
});
return res.status(200).json({
message: `Cache cleared on video ${videoID}`
});
} catch(err) {
return res.sendStatus(500);
}
}

View File

@@ -1,65 +0,0 @@
import { db, privateDB } from "../../databases/databases";
import { getHash } from "../../utils/getHash";
import { getHashCache } from "../../utils/getHashCache";
import { Logger } from "../../utils/logger";
import { Request, Response } from "express";
import { HashedUserID, UserID } from "../../types/user.model";
import { HashedIP, IPAddress, VideoID } from "../../types/segments.model";
import { getIP } from "../../utils/getIP";
import { getService } from "../../utils/getService";
import { RatingType, RatingTypes } from "../../types/ratings.model";
import { config } from "../../config";
import { QueryCacher } from "../../utils/queryCacher";
export async function postRating(req: Request, res: Response): Promise<Response> {
const privateUserID = req.body.userID as UserID;
const videoID = req.body.videoID as VideoID;
const service = getService(req.query.service, req.body.service);
const type = req.body.type as RatingType;
const enabled = req.body.enabled ?? true;
if (privateUserID == undefined || videoID == undefined || service == undefined || type == undefined
|| (typeof privateUserID !== "string") || (typeof videoID !== "string") || (typeof service !== "string")
|| (typeof type !== "number") || (enabled && (typeof enabled !== "boolean")) || !RatingTypes.includes(type)) {
//invalid request
return res.sendStatus(400);
}
const hashedIP: HashedIP = getHash(getIP(req) + config.globalSalt as IPAddress, 1);
const hashedUserID: HashedUserID = await getHashCache(privateUserID);
const hashedVideoID = getHash(videoID, 1);
try {
// Check if this user has voted before
const existingVote = await privateDB.prepare("get", `SELECT count(*) as "count" FROM "ratings" WHERE "videoID" = ? AND "service" = ? AND "type" = ? AND "userID" = ?`, [videoID, service, type, hashedUserID]);
if (existingVote.count > 0 && !enabled) {
// Undo the vote
await privateDB.prepare("run", `DELETE FROM "ratings" WHERE "videoID" = ? AND "service" = ? AND "type" = ? AND "userID" = ?`, [videoID, service, type, hashedUserID]);
await db.prepare("run", `UPDATE "ratings" SET "count" = "count" - 1 WHERE "videoID" = ? AND "service" = ? AND type = ?`, [videoID, service, type]);
} else if (existingVote.count === 0 && enabled) {
// Make sure there hasn't been another vote from this IP
const existingIPVote = (await privateDB.prepare("get", `SELECT count(*) as "count" FROM "ratings" WHERE "videoID" = ? AND "service" = ? AND "type" = ? AND "hashedIP" = ?`, [videoID, service, type, hashedIP]))
.count > 0;
if (existingIPVote) { // if exisiting vote, exit early instead
return res.sendStatus(200);
}
// Create entry in privateDB
await privateDB.prepare("run", `INSERT INTO "ratings" ("videoID", "service", "type", "userID", "timeSubmitted", "hashedIP") VALUES (?, ?, ?, ?, ?, ?)`, [videoID, service, type, hashedUserID, Date.now(), hashedIP]);
// Check if general rating already exists, if so increase it
const rating = await db.prepare("get", `SELECT count(*) as "count" FROM "ratings" WHERE "videoID" = ? AND "service" = ? AND type = ?`, [videoID, service, type]);
if (rating.count > 0) {
await db.prepare("run", `UPDATE "ratings" SET "count" = "count" + 1 WHERE "videoID" = ? AND "service" = ? AND type = ?`, [videoID, service, type]);
} else {
await db.prepare("run", `INSERT INTO "ratings" ("videoID", "service", "type", "count", "hashedVideoID") VALUES (?, ?, ?, 1, ?)`, [videoID, service, type, hashedVideoID]);
}
}
// clear rating cache
QueryCacher.clearRatingCache({ hashedVideoID, service });
return res.sendStatus(200);
} catch (err) {
Logger.error(err as string);
return res.sendStatus(500);
}
}

View File

@@ -32,6 +32,11 @@ export async function setUsername(req: Request, res: Response): Promise<Response
// eslint-disable-next-line no-control-regex
userName = userName.replace(/[\u0000-\u001F\u007F-\u009F]/g, "");
// check privateID against publicID
if (!await checkPrivateUsername(userName, userID)) {
return res.sendStatus(400);
}
if (adminUserIDInput != undefined) {
//this is the admin controlling the other users account, don't hash the controling account's ID
adminUserIDInput = await getHashCache(adminUserIDInput);
@@ -56,7 +61,7 @@ export async function setUsername(req: Request, res: Response): Promise<Response
return res.sendStatus(200);
}
}
catch (error) {
catch (error) /* istanbul ignore next */ {
Logger.error(error as string);
return res.sendStatus(500);
}
@@ -83,8 +88,17 @@ export async function setUsername(req: Request, res: Response): Promise<Response
await logUserNameChange(userID, userName, oldUserName, adminUserIDInput !== undefined);
return res.sendStatus(200);
} catch (err) {
} catch (err) /* istanbul ignore next */ {
Logger.error(err as string);
return res.sendStatus(500);
}
}
async function checkPrivateUsername(username: string, userID: string): Promise<boolean> {
if (username == userID) return false;
if (username.length <= config.minUserIDLength) return true; // don't check for cross matches <= 30 characters
const userNameHash = await getHashCache(username);
const userNameRow = await db.prepare("get", `SELECT "userID" FROM "userNames" WHERE "userID" = ? LIMIT 1`, [userNameHash]);
if (userNameRow?.userID) return false;
return true;
}

View File

@@ -1,28 +1,36 @@
import { db } from "../databases/databases";
import { db, privateDB } from "../databases/databases";
import { getHashCache } from "../utils/getHashCache";
import { Request, Response } from "express";
import { config } from "../config";
import { Category, Service, VideoID, VideoIDHash } from "../types/segments.model";
import { Category, HashedIP, Service, VideoID, VideoIDHash } from "../types/segments.model";
import { UserID } from "../types/user.model";
import { QueryCacher } from "../utils/queryCacher";
import { isUserVIP } from "../utils/isUserVIP";
import { parseCategories } from "../utils/parseParams";
export async function shadowBanUser(req: Request, res: Response): Promise<Response> {
const userID = req.query.userID as UserID;
const hashedIP = req.query.hashedIP as string;
const hashedIP = req.query.hashedIP as HashedIP;
const adminUserIDInput = req.query.adminUserID as UserID;
const type = Number.parseInt(req.query.type as string ?? "1");
if (isNaN(type)) {
return res.sendStatus(400);
}
const enabled = req.query.enabled === undefined
? true
: req.query.enabled === "true";
const lookForIPs = req.query.lookForIPs === "true";
const banUsers = req.query.banUsers === undefined
? true
: req.query.banUsers === "true";
//if enabled is false and the old submissions should be made visible again
const unHideOldSubmissions = req.query.unHideOldSubmissions !== "false";
const categories: string[] = req.query.categories ? JSON.parse(req.query.categories as string) : config.categoryList;
categories.filter((category) => typeof category === "string" && !(/[^a-z|_|-]/.test(category)));
const categories: Category[] = parseCategories(req, config.categoryList as Category[]);
if (adminUserIDInput == undefined || (userID == undefined && hashedIP == undefined)) {
if (adminUserIDInput == undefined || (userID == undefined && hashedIP == undefined || type <= 0)) {
//invalid request
return res.sendStatus(400);
}
@@ -37,88 +45,111 @@ export async function shadowBanUser(req: Request, res: Response): Promise<Respon
}
if (userID) {
//check to see if this user is already shadowbanned
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
const result = await banUser(userID, enabled, unHideOldSubmissions, type, categories);
if (enabled && row.userCount == 0) {
//add them to the shadow ban list
if (enabled && lookForIPs) {
const ipLoggingFixedTime = 1675295716000;
const timeSubmitted = (await db.prepare("all", `SELECT "timeSubmitted" FROM "sponsorTimes" WHERE "timeSubmitted" > ? AND "userID" = ?`, [ipLoggingFixedTime, userID])) as { timeSubmitted: number }[];
const ips = (await Promise.all(timeSubmitted.map((s) => {
return privateDB.prepare("all", `SELECT "hashedIP" FROM "sponsorTimes" WHERE "timeSubmitted" = ?`, [s.timeSubmitted]) as Promise<{ hashedIP: HashedIP }[]>;
}))).flat();
//add it to the table
await db.prepare("run", `INSERT INTO "shadowBannedUsers" VALUES(?)`, [userID]);
await Promise.all([...new Set(ips.map((ip) => ip.hashedIP))].map((ip) => {
return banIP(ip, enabled, unHideOldSubmissions, type, categories, true);
}));
}
//find all previous submissions and hide them
if (unHideOldSubmissions) {
await unHideSubmissions(categories, userID);
}
} else if (!enabled && row.userCount > 0) {
//remove them from the shadow ban list
await db.prepare("run", `DELETE FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
//find all previous submissions and unhide them
if (unHideOldSubmissions) {
const segmentsToIgnore = (await db.prepare("all", `SELECT "UUID" FROM "sponsorTimes" st
JOIN "lockCategories" ns on "st"."videoID" = "ns"."videoID" AND st.category = ns.category AND "st"."service" = "ns"."service" WHERE "st"."userID" = ?`
, [userID])).map((item: {UUID: string}) => item.UUID);
const allSegments = (await db.prepare("all", `SELECT "UUID" FROM "sponsorTimes" st WHERE "st"."userID" = ?`, [userID]))
.map((item: {UUID: string}) => item.UUID);
await Promise.all(allSegments.filter((item: {uuid: string}) => {
return segmentsToIgnore.indexOf(item) === -1;
}).map(async (UUID: string) => {
// collect list for unshadowbanning
(await db.prepare("all", `SELECT "videoID", "hashedVideoID", "service", "votes", "views", "userID" FROM "sponsorTimes" WHERE "UUID" = ? AND "shadowHidden" = 1 AND "category" in (${categories.map((c) => `'${c}'`).join(",")})`, [UUID]))
.forEach((videoInfo: {category: Category, videoID: VideoID, hashedVideoID: VideoIDHash, service: Service, userID: UserID}) => {
QueryCacher.clearSegmentCache(videoInfo);
}
);
return db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = 0 WHERE "UUID" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})`, [UUID]);
}));
}
// already shadowbanned
} else if (enabled && row.userCount > 0) {
// apply unHideOldSubmissions if applicable
if (unHideOldSubmissions) {
await unHideSubmissions(categories, userID);
return res.sendStatus(200);
}
// otherwise ban already exists, send 409
return res.sendStatus(409);
if (result) {
res.sendStatus(result);
return;
}
} else if (hashedIP) {
//check to see if this user is already shadowbanned
// let row = await privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedIPs WHERE hashedIP = ?", [hashedIP]);
// if (enabled && row.userCount == 0) {
if (enabled) {
//add them to the shadow ban list
//add it to the table
// await privateDB.prepare('run', "INSERT INTO shadowBannedIPs VALUES(?)", [hashedIP]);
//find all previous submissions and hide them
if (unHideOldSubmissions) {
await db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = 1 WHERE "timeSubmitted" IN
(SELECT "privateDB"."timeSubmitted" FROM "sponsorTimes" LEFT JOIN "privateDB"."sponsorTimes" as "privateDB" ON "sponsorTimes"."timeSubmitted"="privateDB"."timeSubmitted"
WHERE "privateDB"."hashedIP" = ?)`, [hashedIP]);
}
} /*else if (!enabled && row.userCount > 0) {
// //remove them from the shadow ban list
// await db.prepare('run', "DELETE FROM shadowBannedUsers WHERE userID = ?", [userID]);
// //find all previous submissions and unhide them
// if (unHideOldSubmissions) {
// await db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 0 WHERE userID = ?", [userID]);
// }
}*/
const result = await banIP(hashedIP, enabled, unHideOldSubmissions, type, categories, banUsers);
if (result) {
res.sendStatus(result);
return;
}
}
return res.sendStatus(200);
}
async function unHideSubmissions(categories: string[], userID: UserID) {
await db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = 1 WHERE "userID" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})
export async function banUser(userID: UserID, enabled: boolean, unHideOldSubmissions: boolean, type: number, categories: Category[]): Promise<number> {
//check to see if this user is already shadowbanned
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
if (enabled && row.userCount == 0) {
//add them to the shadow ban list
//add it to the table
await db.prepare("run", `INSERT INTO "shadowBannedUsers" VALUES(?)`, [userID]);
//find all previous submissions and hide them
if (unHideOldSubmissions) {
await unHideSubmissionsByUser(categories, userID, type);
}
} else if (enabled && row.userCount > 0) {
// apply unHideOldSubmissions if applicable
if (unHideOldSubmissions) {
await unHideSubmissionsByUser(categories, userID, type);
} else {
// otherwise ban already exists, send 409
return 409;
}
} else if (!enabled && row.userCount > 0) {
//find all previous submissions and unhide them
if (unHideOldSubmissions) {
await unHideSubmissionsByUser(categories, userID, 0);
}
//remove them from the shadow ban list
await db.prepare("run", `DELETE FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
} else if (row.userCount == 0) { // already shadowbanned
// already not shadowbanned
return 400;
}
return 200;
}
export async function banIP(hashedIP: HashedIP, enabled: boolean, unHideOldSubmissions: boolean, type: number, categories: Category[], banUsers: boolean): Promise<number> {
//check to see if this user is already shadowbanned
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "shadowBannedIPs" WHERE "hashedIP" = ?`, [hashedIP]);
if (enabled) {
if (row.userCount == 0) {
await db.prepare("run", `INSERT INTO "shadowBannedIPs" VALUES(?)`, [hashedIP]);
}
//find all previous submissions and hide them
if (unHideOldSubmissions) {
const users = await unHideSubmissionsByIP(categories, hashedIP, type);
if (banUsers) {
await Promise.all([...users].map((user) => {
return banUser(user, enabled, unHideOldSubmissions, type, categories);
}));
}
} else if (row.userCount > 0) {
// Nothing to do, and already added
return 409;
}
} else if (!enabled) {
if (row.userCount > 0) {
//remove them from the shadow ban list
await db.prepare("run", `DELETE FROM "shadowBannedIPs" WHERE "hashedIP" = ?`, [hashedIP]);
}
//find all previous submissions and unhide them
if (unHideOldSubmissions) {
await unHideSubmissionsByIP(categories, hashedIP, 0);
}
}
return 200;
}
async function unHideSubmissionsByUser(categories: string[], userID: UserID, type = 1) {
await db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = '${type}' WHERE "userID" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})
AND NOT EXISTS ( SELECT "videoID", "category" FROM "lockCategories" WHERE
"sponsorTimes"."videoID" = "lockCategories"."videoID" AND "sponsorTimes"."service" = "lockCategories"."service" AND "sponsorTimes"."category" = "lockCategories"."category")`, [userID]);
@@ -128,3 +159,23 @@ async function unHideSubmissions(categories: string[], userID: UserID) {
QueryCacher.clearSegmentCache(videoInfo);
});
}
async function unHideSubmissionsByIP(categories: string[], hashedIP: HashedIP, type = 1): Promise<Set<UserID>> {
const submissions = await privateDB.prepare("all", `SELECT "timeSubmitted" FROM "sponsorTimes" WHERE "hashedIP" = ?`, [hashedIP]) as { timeSubmitted: number }[];
const users: Set<UserID> = new Set();
await Promise.all(submissions.map(async (submission) => {
(await db.prepare("all", `SELECT "videoID", "hashedVideoID", "service", "votes", "views", "userID" FROM "sponsorTimes" WHERE "timeSubmitted" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})`, [submission.timeSubmitted]))
.forEach((videoInfo: { category: Category, videoID: VideoID, hashedVideoID: VideoIDHash, service: Service, userID: UserID }) => {
QueryCacher.clearSegmentCache(videoInfo);
users.add(videoInfo.userID);
}
);
await db.prepare("run", `UPDATE "sponsorTimes" SET "shadowHidden" = ${type} WHERE "timeSubmitted" = ? AND "category" in (${categories.map((c) => `'${c}'`).join(",")})
AND NOT EXISTS ( SELECT "videoID", "category" FROM "lockCategories" WHERE
"sponsorTimes"."videoID" = "lockCategories"."videoID" AND "sponsorTimes"."service" = "lockCategories"."service" AND "sponsorTimes"."category" = "lockCategories"."category")`, [submission.timeSubmitted]);
}));
return users;
}

82
src/routes/verifyToken.ts Normal file
View File

@@ -0,0 +1,82 @@
import axios from "axios";
import { Request, Response } from "express";
import { config } from "../config";
import { privateDB } from "../databases/databases";
import { Logger } from "../utils/logger";
import { getPatreonIdentity, PatronStatus, refreshToken, TokenType } from "../utils/tokenUtils";
interface VerifyTokenRequest extends Request {
query: {
licenseKey: string;
}
}
export const validateLicenseKeyRegex = (token: string) =>
new RegExp(/[A-Za-z0-9]{40}|[A-Za-z0-9-]{35}/).test(token);
export async function verifyTokenRequest(req: VerifyTokenRequest, res: Response): Promise<Response> {
const { query: { licenseKey } } = req;
if (!licenseKey) {
return res.status(400).send("Invalid request");
} else if (!validateLicenseKeyRegex(licenseKey)) {
// fast check for invalid licence key
return res.status(200).send({
allowed: false
});
}
const tokens = (await privateDB.prepare("get", `SELECT "accessToken", "refreshToken", "expiresIn" from "oauthLicenseKeys" WHERE "licenseKey" = ?`
, [licenseKey])) as {accessToken: string, refreshToken: string, expiresIn: number};
if (tokens) {
const identity = await getPatreonIdentity(tokens.accessToken);
if (tokens.expiresIn < 15 * 24 * 60 * 60) {
refreshToken(TokenType.patreon, licenseKey, tokens.refreshToken).catch((e) => Logger.error(`refresh token: ${e}`));
}
/* istanbul ignore else */
if (identity) {
const membership = identity.included?.[0]?.attributes;
const allowed = !!membership && ((membership.patron_status === PatronStatus.active && membership.currently_entitled_amount_cents > 0)
|| (membership.patron_status === PatronStatus.former && membership.campaign_lifetime_support_cents > 300));
return res.status(200).send({
allowed
});
} else {
return res.status(500);
}
} else {
// Check Local
const result = await privateDB.prepare("get", `SELECT "licenseKey" from "licenseKeys" WHERE "licenseKey" = ?`, [licenseKey]);
if (result) {
return res.status(200).send({
allowed: true
});
} else {
// Gumroad
return res.status(200).send({
allowed: await checkAllGumroadProducts(licenseKey)
});
}
}
}
async function checkAllGumroadProducts(licenseKey: string): Promise<boolean> {
for (const link of config.gumroad.productPermalinks) {
try {
const result = await axios.post("https://api.gumroad.com/v2/licenses/verify", null, {
params: { product_permalink: link, license_key: licenseKey }
});
const allowed = result.status === 200 && result.data?.success;
if (allowed) return allowed;
} catch (e) /* istanbul ignore next */ {
Logger.error(`Gumroad fetch for ${link} failed: ${e}`);
}
}
return false;
}

View File

@@ -2,9 +2,9 @@ import { db } from "../databases/databases";
import { Request, Response } from "express";
export async function viewedVideoSponsorTime(req: Request, res: Response): Promise<Response> {
const UUID = req.query.UUID;
const UUID = req.query?.UUID;
if (UUID == undefined) {
if (!UUID) {
//invalid request
return res.sendStatus(400);
}

View File

@@ -3,7 +3,6 @@ import { Logger } from "../utils/logger";
import { isUserVIP } from "../utils/isUserVIP";
import { isUserTempVIP } from "../utils/isUserTempVIP";
import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi";
import { APIVideoInfo } from "../types/youtubeApi.model";
import { db, privateDB } from "../databases/databases";
import { dispatchEvent, getVoteAuthor, getVoteAuthorRaw } from "../utils/webhookUtils";
import { getFormattedTime } from "../utils/getFormattedTime";
@@ -11,9 +10,11 @@ import { getIP } from "../utils/getIP";
import { getHashCache } from "../utils/getHashCache";
import { config } from "../config";
import { UserID } from "../types/user.model";
import { DBSegment, Category, HashedIP, IPAddress, SegmentUUID, Service, VideoID, VideoIDHash, VideoDuration, ActionType } from "../types/segments.model";
import { DBSegment, Category, HashedIP, IPAddress, SegmentUUID, Service, VideoID, VideoIDHash, VideoDuration, ActionType, VoteType } from "../types/segments.model";
import { QueryCacher } from "../utils/queryCacher";
import axios from "axios";
import { getVideoDetails, videoDetails } from "../utils/getVideoDetails";
import { deleteLockCategories } from "./deleteLockCategories";
const voteTypes = {
normal: 0,
@@ -36,6 +37,7 @@ interface FinalResponse {
interface VoteData {
UUID: string;
nonAnonUserID: string;
originalType: VoteType;
voteTypeEnum: number;
isTempVIP: boolean;
isVIP: boolean;
@@ -51,20 +53,16 @@ interface VoteData {
finalResponse: FinalResponse;
}
function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise<APIVideoInfo> {
return config.newLeafURLs ? YouTubeAPI.listVideos(videoID, ignoreCache) : null;
}
const videoDurationChanged = (segmentDuration: number, APIDuration: number) => (APIDuration > 0 && Math.abs(segmentDuration - APIDuration) > 2);
async function updateSegmentVideoDuration(UUID: SegmentUUID) {
const { videoDuration, videoID, service } = await db.prepare("get", `select "videoDuration", "videoID", "service" from "sponsorTimes" where "UUID" = ?`, [UUID]);
let apiVideoInfo: APIVideoInfo = null;
let apiVideoDetails: videoDetails = null;
if (service == Service.YouTube) {
// don't use cache since we have no information about the video length
apiVideoInfo = await getYouTubeVideoInfo(videoID);
apiVideoDetails = await getVideoDetails(videoID, true);
}
const apiVideoDuration = apiVideoInfo?.data?.lengthSeconds as VideoDuration;
const apiVideoDuration = apiVideoDetails?.duration as VideoDuration;
if (videoDurationChanged(videoDuration, apiVideoDuration)) {
Logger.info(`Video duration changed for ${videoID} from ${videoDuration} to ${apiVideoDuration}`);
await db.prepare("run", `UPDATE "sponsorTimes" SET "videoDuration" = ? WHERE "UUID" = ?`, [apiVideoDuration, UUID]);
@@ -73,12 +71,12 @@ async function updateSegmentVideoDuration(UUID: SegmentUUID) {
async function checkVideoDuration(UUID: SegmentUUID) {
const { videoID, service } = await db.prepare("get", `select "videoID", "service" from "sponsorTimes" where "UUID" = ?`, [UUID]);
let apiVideoInfo: APIVideoInfo = null;
let apiVideoDetails: videoDetails = null;
if (service == Service.YouTube) {
// don't use cache since we have no information about the video length
apiVideoInfo = await getYouTubeVideoInfo(videoID, true);
apiVideoDetails = await getVideoDetails(videoID, true);
}
const apiVideoDuration = apiVideoInfo?.data?.lengthSeconds as VideoDuration;
const apiVideoDuration = apiVideoDetails?.duration as VideoDuration;
// if no videoDuration return early
if (isNaN(apiVideoDuration)) return;
// fetch latest submission
@@ -98,6 +96,7 @@ async function checkVideoDuration(UUID: SegmentUUID) {
AND "hidden" = 0 AND "shadowHidden" = 0 AND
"actionType" != 'full' AND "votes" > -2`,
[videoID, service, latestSubmission.timeSubmitted]);
deleteLockCategories(videoID, null, null, service).catch((e) => Logger.error(`delete lock categories after vote: ${e}`));
}
}
@@ -112,7 +111,9 @@ async function sendWebhooks(voteData: VoteData) {
if (submissionInfoRow !== undefined && userSubmissionCountRow != undefined) {
let webhookURL: string = null;
if (voteData.voteTypeEnum === voteTypes.normal) {
if (voteData.originalType === VoteType.Malicious) {
webhookURL = config.discordMaliciousReportWebhookURL;
} else if (voteData.voteTypeEnum === voteTypes.normal) {
switch (voteData.finalResponse.webhookType) {
case VoteWebhookType.Normal:
webhookURL = config.discordReportChannelWebhookURL;
@@ -126,7 +127,8 @@ async function sendWebhooks(voteData: VoteData) {
}
if (config.newLeafURLs !== null) {
const { err, data } = await YouTubeAPI.listVideos(submissionInfoRow.videoID);
const videoID = submissionInfoRow.videoID;
const { err, data } = await YouTubeAPI.listVideos(videoID);
if (err) return;
const isUpvote = voteData.incrementAmount > 0;
@@ -138,8 +140,8 @@ async function sendWebhooks(voteData: VoteData) {
"video": {
"id": submissionInfoRow.videoID,
"title": data?.title,
"url": `https://www.youtube.com/watch?v=${submissionInfoRow.videoID}`,
"thumbnail": getMaxResThumbnail(data) || null,
"url": `https://www.youtube.com/watch?v=${videoID}`,
"thumbnail": getMaxResThumbnail(videoID),
},
"submission": {
"UUID": voteData.UUID,
@@ -184,7 +186,7 @@ async function sendWebhooks(voteData: VoteData) {
`${getVoteAuthor(userSubmissionCountRow.submissionCount, voteData.isTempVIP, voteData.isVIP, voteData.isOwnSubmission)}${voteData.row.locked ? " (Locked)" : ""}`,
},
"thumbnail": {
"url": getMaxResThumbnail(data) || "",
"url": getMaxResThumbnail(videoID),
},
}],
})
@@ -208,7 +210,7 @@ async function sendWebhooks(voteData: VoteData) {
async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, isTempVIP: boolean, isOwnSubmission: boolean, category: Category
, hashedIP: HashedIP, finalResponse: FinalResponse): Promise<{ status: number, message?: string }> {
// Check if they've already made a vote
const usersLastVoteInfo = await privateDB.prepare("get", `select count(*) as votes, category from "categoryVotes" where "UUID" = ? and "userID" = ? group by category`, [UUID, userID]);
const usersLastVoteInfo = await privateDB.prepare("get", `select count(*) as votes, category from "categoryVotes" where "UUID" = ? and "userID" = ? group by category`, [UUID, userID], { useReplica: true });
if (usersLastVoteInfo?.category === category) {
// Double vote, ignore
@@ -216,20 +218,17 @@ async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, i
}
const segmentInfo = (await db.prepare("get", `SELECT "category", "actionType", "videoID", "hashedVideoID", "service", "userID", "locked" FROM "sponsorTimes" WHERE "UUID" = ?`,
[UUID])) as {category: Category, actionType: ActionType, videoID: VideoID, hashedVideoID: VideoIDHash, service: Service, userID: UserID, locked: number};
[UUID], { useReplica: true })) as {category: Category, actionType: ActionType, videoID: VideoID, hashedVideoID: VideoIDHash, service: Service, userID: UserID, locked: number};
if (segmentInfo.actionType === ActionType.Full) {
return { status: 400, message: "Not allowed to change category of a full video segment" };
}
if (segmentInfo.actionType === ActionType.Poi || category === "poi_highlight") {
return { status: 400, message: "Not allowed to change category for single point segments" };
if (!config.categorySupport[category]?.includes(segmentInfo.actionType) || segmentInfo.actionType === ActionType.Full) {
return { status: 400, message: `Not allowed to change to ${category} when for segment of type ${segmentInfo.actionType}` };
}
if (!config.categoryList.includes(category)) {
return { status: 400, message: "Category doesn't exist." };
}
// Ignore vote if the next category is locked
const nextCategoryLocked = await db.prepare("get", `SELECT "videoID", "category" FROM "lockCategories" WHERE "videoID" = ? AND "service" = ? AND "category" = ?`, [segmentInfo.videoID, segmentInfo.service, category]);
const nextCategoryLocked = await db.prepare("get", `SELECT "videoID", "category" FROM "lockCategories" WHERE "videoID" = ? AND "service" = ? AND "category" = ?`, [segmentInfo.videoID, segmentInfo.service, category], { useReplica: true });
if (nextCategoryLocked && !isVIP) {
return { status: 200 };
}
@@ -239,12 +238,13 @@ async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, i
return { status: 200 };
}
const nextCategoryInfo = await db.prepare("get", `select votes from "categoryVotes" where "UUID" = ? and category = ?`, [UUID, category]);
const nextCategoryInfo = await db.prepare("get", `select votes from "categoryVotes" where "UUID" = ? and category = ?`, [UUID, category], { useReplica: true });
const timeSubmitted = Date.now();
const voteAmount = (isVIP || isTempVIP) ? 500 : 1;
const ableToVote = isVIP || isTempVIP || finalResponse.finalStatus === 200 || true;
const ableToVote = finalResponse.finalStatus === 200
&& (await db.prepare("get", `SELECT "userID" FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID], { useReplica: true })) === undefined;
if (ableToVote) {
// Add the vote
@@ -267,15 +267,15 @@ async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, i
}
// See if the submissions category is ready to change
const currentCategoryInfo = await db.prepare("get", `select votes from "categoryVotes" where "UUID" = ? and category = ?`, [UUID, segmentInfo.category]);
const currentCategoryInfo = await db.prepare("get", `select votes from "categoryVotes" where "UUID" = ? and category = ?`, [UUID, segmentInfo.category], { useReplica: true });
const submissionInfo = await db.prepare("get", `SELECT "userID", "timeSubmitted", "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
const submissionInfo = await db.prepare("get", `SELECT "userID", "timeSubmitted", "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID], { useReplica: true });
const isSubmissionVIP = submissionInfo && await isUserVIP(submissionInfo.userID);
const startingVotes = isSubmissionVIP ? 10000 : 1;
// Change this value from 1 in the future to make it harder to change categories
// Done this way without ORs incase the value is zero
const currentCategoryCount = (currentCategoryInfo === undefined || currentCategoryInfo === null) ? startingVotes : currentCategoryInfo.votes;
const currentCategoryCount = currentCategoryInfo?.votes ?? startingVotes;
// Add submission as vote
if (!currentCategoryInfo && submissionInfo) {
@@ -287,7 +287,7 @@ async function categoryVote(UUID: SegmentUUID, userID: UserID, isVIP: boolean, i
//TODO: In the future, raise this number from zero to make it harder to change categories
// VIPs change it every time
if (nextCategoryCount - currentCategoryCount >= Math.max(Math.ceil(submissionInfo?.votes / 2), 2) || isVIP || isTempVIP || isOwnSubmission) {
if (isVIP || isTempVIP || isOwnSubmission || nextCategoryCount - currentCategoryCount >= Math.max(Math.ceil(submissionInfo?.votes / 2), 2)) {
// Replace the category
await db.prepare("run", `update "sponsorTimes" set "category" = ? where "UUID" = ?`, [category, UUID]);
}
@@ -325,10 +325,12 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
return { status: 400 };
}
// Ignore this vote, invalid
if (paramUserID.length < 30 && config.mode !== "test") {
if (paramUserID.length < config.minUserIDLength) {
return { status: 200 };
}
const originalType = type;
//hash the userID
const nonAnonUserID = await getHashCache(paramUserID);
const userID = await getHashCache(paramUserID + UUID);
@@ -362,6 +364,19 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
return { status: 400 };
}
const MILLISECONDS_IN_HOUR = 3600000;
const now = Date.now();
const warnings = (await db.prepare("all", `SELECT "reason" FROM warnings WHERE "userID" = ? AND "issueTime" > ? AND enabled = 1`,
[nonAnonUserID, Math.floor(now - (config.hoursAfterWarningExpires * MILLISECONDS_IN_HOUR))],
));
if (warnings.length >= config.maxNumberOfActiveWarnings) {
const warningReason = warnings[0]?.reason;
return { status: 403, message: "Vote rejected due to a warning from a moderator. This means that we noticed you were making some common mistakes that are not malicious, and we just want to clarify the rules. " +
"Could you please send a message in Discord or Matrix so we can further help you?" +
`${(warningReason.length > 0 ? ` Warning reason: '${warningReason}'` : "")}` };
}
// no type but has category, categoryVote
if (!type && category) {
return categoryVote(UUID, nonAnonUserID, isVIP, isTempVIP, isOwnSubmission, category, hashedIP, finalResponse);
@@ -372,7 +387,7 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
const isSegmentLocked = segmentInfo.locked;
const isVideoLocked = async () => !!(await db.prepare("get", `SELECT "category" FROM "lockCategories" WHERE
"videoID" = ? AND "service" = ? AND "category" = ? AND "actionType" = ?`,
[segmentInfo.videoID, segmentInfo.service, segmentInfo.category, segmentInfo.actionType]));
[segmentInfo.videoID, segmentInfo.service, segmentInfo.category, segmentInfo.actionType], { useReplica: true }));
if (isSegmentLocked || await isVideoLocked()) {
finalResponse.blockVote = true;
finalResponse.webhookType = VoteWebhookType.Rejected;
@@ -391,43 +406,30 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
}
}
const MILLISECONDS_IN_HOUR = 3600000;
const now = Date.now();
const warnings = (await db.prepare("all", `SELECT "reason" FROM warnings WHERE "userID" = ? AND "issueTime" > ? AND enabled = 1`,
[nonAnonUserID, Math.floor(now - (config.hoursAfterWarningExpires * MILLISECONDS_IN_HOUR))],
));
if (warnings.length >= config.maxNumberOfActiveWarnings) {
const warningReason = warnings[0]?.reason;
return { status: 403, message: "Vote rejected due to a warning from a moderator. This means that we noticed you were making some common mistakes that are not malicious, and we just want to clarify the rules. " +
"Could you please send a message in Discord or Matrix so we can further help you?" +
`${(warningReason.length > 0 ? ` Warning reason: '${warningReason}'` : "")}` };
}
const voteTypeEnum = (type == 0 || type == 1 || type == 20) ? voteTypes.normal : voteTypes.incorrect;
// no restrictions on checkDuration
// check duration of all submissions on this video
if (type <= 0) {
checkVideoDuration(UUID);
checkVideoDuration(UUID).catch((e) => Logger.error(`checkVideoDuration: ${e}`));
}
try {
// check if vote has already happened
const votesRow = await privateDB.prepare("get", `SELECT "type" FROM "votes" WHERE "userID" = ? AND "UUID" = ?`, [userID, UUID]);
const votesRow = await privateDB.prepare("get", `SELECT "type" FROM "votes" WHERE "userID" = ? AND "UUID" = ?`, [userID, UUID], { useReplica: true });
// -1 for downvote, 1 for upvote. Maybe more depending on reputation in the future
// oldIncrementAmount will be zero if row is null
let incrementAmount = 0;
let oldIncrementAmount = 0;
if (type == 1) {
if (type == VoteType.Upvote) {
//upvote
incrementAmount = 1;
} else if (type == 0) {
} else if (type === VoteType.Downvote || type === VoteType.Malicious) {
//downvote
incrementAmount = -1;
} else if (type == 20) {
} else if (type == VoteType.Undo) {
//undo/cancel vote
incrementAmount = 0;
} else {
@@ -435,17 +437,13 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
return { status: 400 };
}
if (votesRow) {
if (votesRow.type === 1) {
//upvote
if (votesRow.type === VoteType.Upvote) {
oldIncrementAmount = 1;
} else if (votesRow.type === 0) {
//downvote
} else if (votesRow.type === VoteType.Downvote) {
oldIncrementAmount = -1;
} else if (votesRow.type === 2) {
//extra downvote
} else if (votesRow.type === VoteType.ExtraDownvote) {
oldIncrementAmount = -4;
} else if (votesRow.type === 20) {
//undo/cancel vote
} else if (votesRow.type === VoteType.Undo) {
oldIncrementAmount = 0;
} else if (votesRow.type < 0) {
//vip downvote
@@ -466,13 +464,19 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
type = incrementAmount;
}
if (type === VoteType.Malicious) {
incrementAmount = -Math.min(segmentInfo.votes + 2 - oldIncrementAmount, 5);
type = incrementAmount;
}
// Only change the database if they have made a submission before and haven't voted recently
const userAbleToVote = (!(isOwnSubmission && incrementAmount > 0 && oldIncrementAmount >= 0)
&& !(originalType === VoteType.Malicious && segmentInfo.actionType !== ActionType.Chapter)
&& !finalResponse.blockVote
&& finalResponse.finalStatus === 200
&& (await db.prepare("get", `SELECT "userID" FROM "sponsorTimes" WHERE "userID" = ?`, [nonAnonUserID])) !== undefined
&& (await db.prepare("get", `SELECT "userID" FROM "shadowBannedUsers" WHERE "userID" = ?`, [nonAnonUserID])) === undefined
&& (await privateDB.prepare("get", `SELECT "UUID" FROM "votes" WHERE "UUID" = ? AND "hashedIP" = ? AND "userID" != ?`, [UUID, hashedIP, userID])) === undefined);
&& (await db.prepare("get", `SELECT "userID" FROM "sponsorTimes" WHERE "userID" = ?`, [nonAnonUserID], { useReplica: true })) !== undefined
&& (await db.prepare("get", `SELECT "userID" FROM "shadowBannedUsers" WHERE "userID" = ?`, [nonAnonUserID], { useReplica: true })) === undefined
&& (await privateDB.prepare("get", `SELECT "UUID" FROM "votes" WHERE "UUID" = ? AND "hashedIP" = ? AND "userID" != ?`, [UUID, hashedIP, userID], { useReplica: true })) === undefined);
const ableToVote = isVIP || isTempVIP || userAbleToVote;
@@ -480,9 +484,9 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
if (ableToVote) {
//update the votes table
if (votesRow) {
await privateDB.prepare("run", `UPDATE "votes" SET "type" = ? WHERE "userID" = ? AND "UUID" = ?`, [type, userID, UUID]);
await privateDB.prepare("run", `UPDATE "votes" SET "type" = ?, "originalType" = ? WHERE "userID" = ? AND "UUID" = ?`, [type, originalType, userID, UUID]);
} else {
await privateDB.prepare("run", `INSERT INTO "votes" VALUES(?, ?, ?, ?, ?)`, [UUID, userID, hashedIP, type, nonAnonUserID]);
await privateDB.prepare("run", `INSERT INTO "votes" ("UUID", "userID", "hashedIP", "type", "normalUserID", "originalType") VALUES(?, ?, ?, ?, ?, ?)`, [UUID, userID, hashedIP, type, nonAnonUserID, originalType]);
}
// update the vote count on this sponsorTime
@@ -510,6 +514,7 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
sendWebhooks({
UUID,
nonAnonUserID,
originalType,
voteTypeEnum,
isTempVIP,
isVIP,
@@ -519,7 +524,7 @@ export async function vote(ip: IPAddress, UUID: SegmentUUID, paramUserID: UserID
incrementAmount,
oldIncrementAmount,
finalResponse
});
}).catch((e) => Logger.error(`Sending vote webhook: ${e}`));
}
return { status: finalResponse.finalStatus, message: finalResponse.finalMessage ?? undefined };
} catch (err) {

View File

@@ -0,0 +1,75 @@
import { Service, VideoID, VideoIDHash } from "./segments.model";
import { UserID } from "./user.model";
export type BrandingUUID = string & { readonly __brandingUUID: unique symbol };
export interface BrandingDBSubmission {
shadowHidden: number,
UUID: BrandingUUID,
videoID: VideoID,
hashedVideoID: VideoIDHash
}
export interface TitleDBResult extends BrandingDBSubmission {
title: string,
original: number,
votes: number,
locked: number
}
export interface TitleResult {
title: string,
original: boolean,
votes: number,
locked: boolean,
UUID: BrandingUUID
}
export interface ThumbnailDBResult extends BrandingDBSubmission {
timestamp?: number,
original: number,
votes: number,
locked: number
}
export interface ThumbnailResult {
timestamp?: number,
original: boolean,
votes: number,
locked: boolean,
UUID: BrandingUUID
}
export interface BrandingResult {
titles: TitleResult[],
thumbnails: ThumbnailResult[]
}
export interface BrandingHashDBResult {
titles: TitleDBResult[],
thumbnails: ThumbnailDBResult[]
}
export interface OriginalThumbnailSubmission {
original: true;
}
export interface TimeThumbnailSubmission {
timestamp: number;
original: false;
}
export type ThumbnailSubmission = OriginalThumbnailSubmission | TimeThumbnailSubmission;
export interface TitleSubmission {
title: string;
original: boolean;
}
export interface BrandingSubmission {
title: TitleSubmission;
thumbnail: ThumbnailSubmission;
videoID: VideoID;
userID: UserID;
service: Service;
}

View File

@@ -3,10 +3,36 @@ import * as redis from "redis";
interface RedisConfig extends redis.RedisClientOptions {
enabled: boolean;
expiryTime: number;
getTimeout: number;
maxConnections: number;
maxWriteConnections: number;
stopWritingAfterResponseTime: number;
responseTimePause: number;
disableHashCache: boolean;
}
interface CustomPostgresConfig extends PoolConfig {
interface RedisReadOnlyConfig extends redis.RedisClientOptions {
enabled: boolean;
weight: number;
}
export interface CustomPostgresConfig extends PoolConfig {
enabled: boolean;
maxTries: number;
}
export interface CustomWritePostgresConfig extends CustomPostgresConfig {
maxActiveRequests: number;
timeout: number;
highLoadThreshold: number;
}
export interface CustomPostgresReadOnlyConfig extends CustomPostgresConfig {
weight: number;
readTimeout: number;
fallbackOnFail: boolean;
stopRetryThreshold: number;
}
export interface SBSConfig {
@@ -20,9 +46,13 @@ export interface SBSConfig {
discordFailedReportChannelWebhookURL?: string;
discordFirstTimeSubmissionsWebhookURL?: string;
discordCompletelyIncorrectReportWebhookURL?: string;
discordMaliciousReportWebhookURL?: string;
neuralBlockURL?: string;
discordNeuralBlockRejectWebhookURL?: string;
minReputationToSubmitChapter: number;
minReputationToSubmitFiller: number;
userCounterURL?: string;
userCounterRatio: number;
proxySubmission?: string;
behindProxy: string | boolean;
db: string;
@@ -42,18 +72,30 @@ export interface SBSConfig {
rateLimit: {
vote: RateLimitConfig;
view: RateLimitConfig;
rate: RateLimitConfig;
};
mysql?: any;
privateMysql?: any;
minimumPrefix?: string;
maximumPrefix?: string;
redis?: RedisConfig;
redisRead?: RedisReadOnlyConfig;
redisRateLimit: boolean;
maxRewardTimePerSegmentInSeconds?: number;
postgres?: CustomPostgresConfig;
postgres?: CustomWritePostgresConfig;
postgresReadOnly?: CustomPostgresReadOnlyConfig;
dumpDatabase?: DumpDatabase;
diskCacheURL: string;
crons: CronJobOptions;
patreon: {
clientId: string,
clientSecret: string,
minPrice: number,
redirectUri: string
}
gumroad: {
productPermalinks: string[],
},
minUserIDLength: number
}
export interface WebhookConfig {

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