mirror of
https://github.com/ajayyy/SponsorBlockServer.git
synced 2025-12-06 11:36:58 +03:00
Compare commits
821 Commits
k8s-test
...
1eedc9fa09
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1eedc9fa09 | ||
|
|
c1fc6519b4 | ||
|
|
2d5d3637fd | ||
|
|
99ed7698c4 | ||
|
|
c0ee5206a2 | ||
|
|
9c65f3ca34 | ||
|
|
c2c92cd168 | ||
|
|
b4ea2018d5 | ||
|
|
da448af4cf | ||
|
|
33a7934f33 | ||
|
|
a2cad19167 | ||
|
|
721720a60d | ||
|
|
220fe52013 | ||
|
|
07c0f5cfbd | ||
|
|
899000309f | ||
|
|
5664ff4f58 | ||
|
|
c942eea640 | ||
|
|
b09e552d1d | ||
|
|
3e74a0da58 | ||
|
|
1b99a8534c | ||
|
|
3711286ef2 | ||
|
|
74b9b123a8 | ||
|
|
367cb24478 | ||
|
|
41c91b8b03 | ||
|
|
40c4ec7437 | ||
|
|
70ce320737 | ||
|
|
0bfc9b30f5 | ||
|
|
bce5385864 | ||
|
|
f71c4ceba9 | ||
|
|
69ca711bb3 | ||
|
|
e519986027 | ||
|
|
c0e7401a73 | ||
|
|
314461c9f0 | ||
|
|
655789e62d | ||
|
|
339ba127eb | ||
|
|
da393da9e9 | ||
|
|
aa2c7bf6ea | ||
|
|
c82708aae8 | ||
|
|
26c575d37a | ||
|
|
1b3b1b1cb3 | ||
|
|
9bc4bf8c7b | ||
|
|
cbc38c5ac8 | ||
|
|
e7f3753077 | ||
|
|
f44d3cd92c | ||
|
|
4db4e9458e | ||
|
|
b2cd048909 | ||
|
|
5c249fb02b | ||
|
|
f7e5394a18 | ||
|
|
161db6df0c | ||
|
|
920d288f0b | ||
|
|
0d005c23bf | ||
|
|
9f745d3a8b | ||
|
|
39f8dc6c22 | ||
|
|
08ba5c21b1 | ||
|
|
cfd61dc8dd | ||
|
|
039fb3ac7a | ||
|
|
fccebfa487 | ||
|
|
6130ac8150 | ||
|
|
7e681d2cd5 | ||
|
|
707b36d161 | ||
|
|
b849328fae | ||
|
|
3d596f4528 | ||
|
|
ed5a397a30 | ||
|
|
300642fd4f | ||
|
|
46580322fc | ||
|
|
318152dac6 | ||
|
|
8111d34b30 | ||
|
|
ac78dee210 | ||
|
|
d18a4a13f2 | ||
|
|
8d40d61efc | ||
|
|
74f6224091 | ||
|
|
9b55dc5d4d | ||
|
|
8cd2138989 | ||
|
|
e40af45c73 | ||
|
|
5de1fe4388 | ||
|
|
2ef3d68af0 | ||
|
|
f67244663e | ||
|
|
00064d5a7c | ||
|
|
ac26aed21c | ||
|
|
2aa3589312 | ||
|
|
82af8f200b | ||
|
|
69cb33aad0 | ||
|
|
3817d7fdba | ||
|
|
34a6a83e44 | ||
|
|
0967373cb2 | ||
|
|
b7794b57d0 | ||
|
|
550339db41 | ||
|
|
b69f050b44 | ||
|
|
59a986f32f | ||
|
|
7088a1688d | ||
|
|
f07f94fb09 | ||
|
|
a7758a2608 | ||
|
|
fd5bc43281 | ||
|
|
3633d0fbb4 | ||
|
|
aae56887da | ||
|
|
4fe7cebcb3 | ||
|
|
31e678fdc2 | ||
|
|
d44ce3c2dc | ||
|
|
5f9b4c8acc | ||
|
|
d608125b41 | ||
|
|
fb3abb3216 | ||
|
|
ccde64e90f | ||
|
|
4abf57b0ce | ||
|
|
07435b9af1 | ||
|
|
ab9cab8ff5 | ||
|
|
311c653ea2 | ||
|
|
e92d47e1a4 | ||
|
|
3734b88cb5 | ||
|
|
00086d9001 | ||
|
|
a37a552b17 | ||
|
|
fa29cfd3c6 | ||
|
|
be9d97ae2b | ||
|
|
06f83cd8d4 | ||
|
|
80b1019783 | ||
|
|
2455d2cd7e | ||
|
|
e2a9976cd0 | ||
|
|
bba06511ce | ||
|
|
043268dc10 | ||
|
|
003fe77e72 | ||
|
|
efe59c5098 | ||
|
|
7ef6452eb5 | ||
|
|
9c01b711a5 | ||
|
|
b2981fe782 | ||
|
|
405805ff89 | ||
|
|
01c306287a | ||
|
|
826d49ba1f | ||
|
|
b03057c5bf | ||
|
|
54e03a389b | ||
|
|
93f7161724 | ||
|
|
efa6c10d56 | ||
|
|
e9c0c44528 | ||
|
|
4dfbb9039d | ||
|
|
05c5cf57e4 | ||
|
|
566eabdc31 | ||
|
|
f26db7238a | ||
|
|
fb05ec51d3 | ||
|
|
eeb9f1b02f | ||
|
|
8ba68e1b4c | ||
|
|
17059fdbe6 | ||
|
|
6e5f4f7610 | ||
|
|
c313590d36 | ||
|
|
4508ad11f2 | ||
|
|
dc5158257e | ||
|
|
6edd71194b | ||
|
|
7678be1e24 | ||
|
|
d28ac39d4f | ||
|
|
5fd6b5eb8b | ||
|
|
0e1a38c4d4 | ||
|
|
c496be5651 | ||
|
|
15a9c3a4eb | ||
|
|
f1ebd56526 | ||
|
|
258749ac31 | ||
|
|
ccccb1af3c | ||
|
|
13b8a988db | ||
|
|
803fc18554 | ||
|
|
59373cf346 | ||
|
|
05fd6abe91 | ||
|
|
090e185765 | ||
|
|
d2df5cef98 | ||
|
|
214946897d | ||
|
|
8da5de4d7b | ||
|
|
380ec8d0ca | ||
|
|
72086b0195 | ||
|
|
61dcfeb69f | ||
|
|
19d6d85aa6 | ||
|
|
814ceb56f1 | ||
|
|
195cc14d25 | ||
|
|
9427bf4f3d | ||
|
|
3f026409cd | ||
|
|
d75b9ddcaa | ||
|
|
2fb3d05055 | ||
|
|
165ed8a6e0 | ||
|
|
495b8031e3 | ||
|
|
374ddc74bd | ||
|
|
738f863581 | ||
|
|
8b5e69f36f | ||
|
|
10e37824d8 | ||
|
|
428343e7d8 | ||
|
|
4e69ac60bc | ||
|
|
3b03792903 | ||
|
|
1a0b6ab097 | ||
|
|
8e5084cd72 | ||
|
|
96feaf3cbe | ||
|
|
d08cfee5b4 | ||
|
|
96dd9eceb3 | ||
|
|
4422104294 | ||
|
|
4ad553478b | ||
|
|
47323156c1 | ||
|
|
a181d52fb2 | ||
|
|
ee9ed6af1f | ||
|
|
ec1e6d63a4 | ||
|
|
5c10e071dc | ||
|
|
8eb6f5b2ea | ||
|
|
bdfe4938d2 | ||
|
|
bcf29e4047 | ||
|
|
622c3f27d6 | ||
|
|
7c1abd9747 | ||
|
|
709485e0e9 | ||
|
|
f841d8173b | ||
|
|
b2f7e1b39b | ||
|
|
47ea6ae8d3 | ||
|
|
063607fe30 | ||
|
|
4b795da5a0 | ||
|
|
8043bd9006 | ||
|
|
bd8f4b7539 | ||
|
|
0f97ce4a49 | ||
|
|
cfd7c3d8c4 | ||
|
|
af7d8428ab | ||
|
|
7c51586664 | ||
|
|
2251ddc251 | ||
|
|
07d4dde4f6 | ||
|
|
b934b7a937 | ||
|
|
f2cf2e2aac | ||
|
|
2887a8505c | ||
|
|
e289fe9075 | ||
|
|
2cd9401a51 | ||
|
|
47bea9ee6e | ||
|
|
0602fdd651 | ||
|
|
7c77bf566e | ||
|
|
1009fff9e9 | ||
|
|
f43e59250f | ||
|
|
dc2115ef20 | ||
|
|
55c3e4f01f | ||
|
|
af31f511a5 | ||
|
|
0d9cce0512 | ||
|
|
c19d6fe97a | ||
|
|
47c109f012 | ||
|
|
a921085da6 | ||
|
|
d5ebd8ec1a | ||
|
|
a7f10f7727 | ||
|
|
1c234846db | ||
|
|
bc1ca098e7 | ||
|
|
cf21ebc2de | ||
|
|
2426a6ee03 | ||
|
|
ba65c28459 | ||
|
|
591b342855 | ||
|
|
8d8388386e | ||
|
|
a54bf556ed | ||
|
|
f1c5b8a359 | ||
|
|
9bcceb7e5b | ||
|
|
da0cf0dedc | ||
|
|
1cefdf4dac | ||
|
|
aec2aa4457 | ||
|
|
3f29e11449 | ||
|
|
6d11e1c601 | ||
|
|
9fa248037a | ||
|
|
02a640d857 | ||
|
|
17b002649e | ||
|
|
a74189b287 | ||
|
|
09997d82ed | ||
|
|
bf644d6899 | ||
|
|
5929460239 | ||
|
|
09dd10ad6f | ||
|
|
af5e8cd68d | ||
|
|
bd766ab430 | ||
|
|
bf1fe1ff61 | ||
|
|
db225f8a84 | ||
|
|
9364a7e654 | ||
|
|
f3fffa56c9 | ||
|
|
c478546128 | ||
|
|
e61f964d17 | ||
|
|
5f8ef25d88 | ||
|
|
b76cfdf798 | ||
|
|
3c6000f2da | ||
|
|
9944d70f6b | ||
|
|
27069cb5c2 | ||
|
|
8aa03c81a7 | ||
|
|
e8879f66b1 | ||
|
|
acdbd3787b | ||
|
|
1f7156eb29 | ||
|
|
7405053b44 | ||
|
|
a929f69452 | ||
|
|
8574ec3a0c | ||
|
|
1475c91327 | ||
|
|
5b1b362bf0 | ||
|
|
14da10bd8a | ||
|
|
547632341a | ||
|
|
c54c25c73b | ||
|
|
121cc7f481 | ||
|
|
e041b9c930 | ||
|
|
59d9ed390f | ||
|
|
4477ab7ca6 | ||
|
|
25ec9b0291 | ||
|
|
c3e00ac8b1 | ||
|
|
2c9079f565 | ||
|
|
aee84a4b6e | ||
|
|
a8010b553d | ||
|
|
5b95aa8aba | ||
|
|
fce311377f | ||
|
|
dcb479f3d2 | ||
|
|
2ad51842cc | ||
|
|
ea60947092 | ||
|
|
14b6f84f94 | ||
|
|
8e13ec60d6 | ||
|
|
c9f7275942 | ||
|
|
d607d8b179 | ||
|
|
5974b51391 | ||
|
|
7aaf000d99 | ||
|
|
0edf0b9e1c | ||
|
|
84fd7c170f | ||
|
|
b04e0dcd97 | ||
|
|
33dad0a5e4 | ||
|
|
ad439fd368 | ||
|
|
21bb893a47 | ||
|
|
211ecf700b | ||
|
|
951d678640 | ||
|
|
15f19df8a4 | ||
|
|
4a4d5776a1 | ||
|
|
b3a28f7df3 | ||
|
|
f763139664 | ||
|
|
da482054a4 | ||
|
|
134e89af00 | ||
|
|
5cc80f9066 | ||
|
|
e1043aba05 | ||
|
|
c0abedf67f | ||
|
|
d99b7dc2c6 | ||
|
|
579e2b90a3 | ||
|
|
3708d293dc | ||
|
|
077a9ecc50 | ||
|
|
5714f51ac0 | ||
|
|
68bb39c409 | ||
|
|
9dd8b28812 | ||
|
|
a659048afe | ||
|
|
3c6803fb62 | ||
|
|
467443a03f | ||
|
|
d8b93dec00 | ||
|
|
26b3ea6a50 | ||
|
|
f72b1abf41 | ||
|
|
53e5dcb2f0 | ||
|
|
73e5ade529 | ||
|
|
31e1f5bc3c | ||
|
|
df40047a4b | ||
|
|
ad9344c92f | ||
|
|
726983bb9b | ||
|
|
7364499f11 | ||
|
|
5e3ec895d8 | ||
|
|
a9ef3815e2 | ||
|
|
964634dc51 | ||
|
|
1e8970859f | ||
|
|
4438ce7db6 | ||
|
|
86ea0f582b | ||
|
|
e329bccca5 | ||
|
|
1275afa25b | ||
|
|
1b5a079bbd | ||
|
|
ad666ff487 | ||
|
|
7196155d3a | ||
|
|
934ce79728 | ||
|
|
65e7d24b7d | ||
|
|
d08c423c6a | ||
|
|
8361f602c7 | ||
|
|
1e3a50b884 | ||
|
|
55150cb301 | ||
|
|
2015cf1488 | ||
|
|
141f105b79 | ||
|
|
c2a3630d49 | ||
|
|
c77e71e66a | ||
|
|
345c740fdc | ||
|
|
d84276a86a | ||
|
|
16c7ad5531 | ||
|
|
7cb0a0705c | ||
|
|
4600b8a599 | ||
|
|
e9e1fd5228 | ||
|
|
48fa55cc7a | ||
|
|
ecfc2c14c8 | ||
|
|
f58da275eb | ||
|
|
0723503a98 | ||
|
|
9d1af3bdff | ||
|
|
b3cec20215 | ||
|
|
b02134c016 | ||
|
|
c3c8f38423 | ||
|
|
1dbb393e4d | ||
|
|
dfa4578d28 | ||
|
|
99cb22a5e6 | ||
|
|
665b91eb65 | ||
|
|
e942ac5e22 | ||
|
|
83b561d943 | ||
|
|
f0b0217c78 | ||
|
|
d23e9b9940 | ||
|
|
4b214767a0 | ||
|
|
8c687934c2 | ||
|
|
f63fa09605 | ||
|
|
4e93a007c2 | ||
|
|
2fc31655ff | ||
|
|
79515ccc8b | ||
|
|
b6f29b8b6d | ||
|
|
a52ecf2d37 | ||
|
|
8d518b184b | ||
|
|
3924a65e02 | ||
|
|
a4de94bede | ||
|
|
8bcc781da7 | ||
|
|
b2081fe155 | ||
|
|
ea80a413ba | ||
|
|
528f24a431 | ||
|
|
0463165f1a | ||
|
|
38b7ddfd07 | ||
|
|
79bac69c41 | ||
|
|
85fc0477ad | ||
|
|
a5501b9655 | ||
|
|
e9fcf6b445 | ||
|
|
808066a5ed | ||
|
|
93f4cfd82d | ||
|
|
d030de83bd | ||
|
|
d1d2b011f8 | ||
|
|
d2f8e3aee4 | ||
|
|
2e29666781 | ||
|
|
8b418c8851 | ||
|
|
5f80562772 | ||
|
|
69db87f5e1 | ||
|
|
fa6919a1d0 | ||
|
|
633f128e90 | ||
|
|
9f7fa53b14 | ||
|
|
bbb7102e37 | ||
|
|
3bb8d5b58b | ||
|
|
1cacb2dd69 | ||
|
|
fe185234cf | ||
|
|
ef3e48ec24 | ||
|
|
777944665d | ||
|
|
0932f63398 | ||
|
|
5834643ba0 | ||
|
|
8e5be402e1 | ||
|
|
e253c7bb47 | ||
|
|
9129cee9f0 | ||
|
|
39fcdb1d95 | ||
|
|
8d1025e17d | ||
|
|
6f0abddd3e | ||
|
|
a1b5c38e5a | ||
|
|
8db898fab5 | ||
|
|
940cacfb0a | ||
|
|
69a54f64b4 | ||
|
|
9600f56830 | ||
|
|
4e59526b4d | ||
|
|
42f2eb5eae | ||
|
|
e1a607ba39 | ||
|
|
8a236d66ed | ||
|
|
4a10faaea3 | ||
|
|
589b7d4e3e | ||
|
|
a52feee25e | ||
|
|
d6a12a5e99 | ||
|
|
4696ce8d01 | ||
|
|
bffc10e38f | ||
|
|
dde12bcc43 | ||
|
|
7921bc4582 | ||
|
|
0b830610e9 | ||
|
|
b6e9f92da8 | ||
|
|
d4c4dbffcc | ||
|
|
5c549b5295 | ||
|
|
acae9da06c | ||
|
|
1f939116a4 | ||
|
|
8495a9d6c0 | ||
|
|
d76ee7cd22 | ||
|
|
436e75e3e6 | ||
|
|
7ba654e476 | ||
|
|
f4286b15a1 | ||
|
|
76ce1017ea | ||
|
|
780555e9df | ||
|
|
79b7b6ea4c | ||
|
|
80de71a68f | ||
|
|
4b8bc418ba | ||
|
|
f4537160de | ||
|
|
900fa9f64e | ||
|
|
e6f54f11f0 | ||
|
|
6296761fe4 | ||
|
|
820a7eb02f | ||
|
|
c6795a783d | ||
|
|
37a1c7e88d | ||
|
|
31a460e750 | ||
|
|
1bda331b0c | ||
|
|
72fb4eb6ec | ||
|
|
d04230a1c4 | ||
|
|
f70a26009c | ||
|
|
c84eb839a0 | ||
|
|
df279cf48a | ||
|
|
cdc080b58b | ||
|
|
c586c9a7e7 | ||
|
|
81b0c27180 | ||
|
|
bff05dccaa | ||
|
|
9c438602f8 | ||
|
|
19ebca86c9 | ||
|
|
f48fb6c3f6 | ||
|
|
4a90ba8992 | ||
|
|
efc911a229 | ||
|
|
2e3f4f8c70 | ||
|
|
b95b6d8efe | ||
|
|
7985d131ef | ||
|
|
a384079562 | ||
|
|
46c372a764 | ||
|
|
3281954019 | ||
|
|
aece615992 | ||
|
|
6448fbfbd8 | ||
|
|
c5426e5fc4 | ||
|
|
3894d453a5 | ||
|
|
280e6684af | ||
|
|
7361c7056b | ||
|
|
2d751a0b21 | ||
|
|
399bda869f | ||
|
|
663bd96130 | ||
|
|
5b3f4b476e | ||
|
|
b855eea349 | ||
|
|
51d25cfc68 | ||
|
|
f8f02d86d5 | ||
|
|
cb7492628c | ||
|
|
e69b61fb4c | ||
|
|
5c1b502a15 | ||
|
|
d5c544f1ee | ||
|
|
5426ae826e | ||
|
|
7911819cab | ||
|
|
d8e0eac61b | ||
|
|
74c0ba37e2 | ||
|
|
a64b8f99b7 | ||
|
|
9cf2e1f0e9 | ||
|
|
10e9aef8cc | ||
|
|
d07aac3a33 | ||
|
|
b91114165e | ||
|
|
36f1d15605 | ||
|
|
894cd48182 | ||
|
|
1641a41b00 | ||
|
|
4d8ce40ef4 | ||
|
|
07c683e8f0 | ||
|
|
d0a9168531 | ||
|
|
2ed23d7fcb | ||
|
|
e7a43d79ab | ||
|
|
b792354ffb | ||
|
|
a613b68c66 | ||
|
|
66c2be6012 | ||
|
|
2a7083b9ef | ||
|
|
928eef637a | ||
|
|
be03367557 | ||
|
|
fd288dd330 | ||
|
|
0c00f7323d | ||
|
|
5a6ba891f9 | ||
|
|
90e5446078 | ||
|
|
dc0bde0e36 | ||
|
|
7c2feb80bc | ||
|
|
fc607d0cb7 | ||
|
|
3fbcadc3a0 | ||
|
|
7f7a3a37ec | ||
|
|
cc24a4902f | ||
|
|
d738e89f20 | ||
|
|
b591b7194e | ||
|
|
fc5b5ca72c | ||
|
|
8d7b010a12 | ||
|
|
fc73f491fe | ||
|
|
2683c61995 | ||
|
|
cff2325aef | ||
|
|
d7d5618985 | ||
|
|
4e3753d32c | ||
|
|
1202c264aa | ||
|
|
89e122210e | ||
|
|
aed0e38d2f | ||
|
|
665ad6fe50 | ||
|
|
992c65a39d | ||
|
|
b6e62aa68f | ||
|
|
1f844bf56a | ||
|
|
fa5f3b8a50 | ||
|
|
30ac91c537 | ||
|
|
e252411fe1 | ||
|
|
91fc56f59a | ||
|
|
0cd808a2d9 | ||
|
|
87e38c8bc4 | ||
|
|
df76b5f053 | ||
|
|
71d30c0b51 | ||
|
|
238ccc83d9 | ||
|
|
9bd6e9df4f | ||
|
|
7bdcb10994 | ||
|
|
849ca52ef8 | ||
|
|
9e2e1343da | ||
|
|
4139bf8f8c | ||
|
|
1fffd2e6ac | ||
|
|
a417299d3e | ||
|
|
d3d53d0758 | ||
|
|
517c9512e4 | ||
|
|
ed5e3373a5 | ||
|
|
6c18579a78 | ||
|
|
e6e8c8e5a1 | ||
|
|
50743070de | ||
|
|
7fb68937d0 | ||
|
|
90e68caaf7 | ||
|
|
0ead3892ba | ||
|
|
2700b5b530 | ||
|
|
e1a5ca64f0 | ||
|
|
98f202f6a9 | ||
|
|
ee436d982c | ||
|
|
dc8c35695d | ||
|
|
9b509e7289 | ||
|
|
eee44e611b | ||
|
|
5139c7aaf0 | ||
|
|
2254e7f869 | ||
|
|
68d9d3cbde | ||
|
|
571230db56 | ||
|
|
9c5db6a958 | ||
|
|
6b1ecbe90e | ||
|
|
d83d620893 | ||
|
|
db71af480d | ||
|
|
80c018c9d5 | ||
|
|
cc6c5980a1 | ||
|
|
9d7236282c | ||
|
|
7f92ac961d | ||
|
|
96db571a5e | ||
|
|
ccd1321d24 | ||
|
|
19289a149b | ||
|
|
622511c8fd | ||
|
|
c2acc6227b | ||
|
|
176f2ce7b9 | ||
|
|
9286f16e7b | ||
|
|
9e3d059d10 | ||
|
|
13ae4681cb | ||
|
|
ee56a8dea4 | ||
|
|
94eb37cb1c | ||
|
|
0ced78d798 | ||
|
|
f1005fe779 | ||
|
|
1e2437b993 | ||
|
|
a6275b3607 | ||
|
|
ba27a8a056 | ||
|
|
10397fbde2 | ||
|
|
b5434ae234 | ||
|
|
b52ca8b2a6 | ||
|
|
e799821ad9 | ||
|
|
415bb31e36 | ||
|
|
eb3d733a34 | ||
|
|
9386f25f9f | ||
|
|
ceaf9ec6f6 | ||
|
|
d229003f6e | ||
|
|
1becebdcd5 | ||
|
|
b417241ca0 | ||
|
|
ee3d94e7b7 | ||
|
|
b6da103c3d | ||
|
|
52a7d7e791 | ||
|
|
b63572ec43 | ||
|
|
66d5622393 | ||
|
|
b7fcd9ea39 | ||
|
|
c4af2449c3 | ||
|
|
eb5458427d | ||
|
|
95dd36a782 | ||
|
|
67eb165b53 | ||
|
|
d163b1d436 | ||
|
|
715d41fbb2 | ||
|
|
0b9e7029c5 | ||
|
|
9ef0eafac1 | ||
|
|
d80be9e7b3 | ||
|
|
968ffe785f | ||
|
|
847f1bbabb | ||
|
|
ada32217d9 | ||
|
|
a8ddae131d | ||
|
|
54e53f098e | ||
|
|
ed251a047a | ||
|
|
601a17c969 | ||
|
|
771fa18731 | ||
|
|
27f7b6d3c7 | ||
|
|
55aa33aa6e | ||
|
|
07926ada57 | ||
|
|
ea05284b1d | ||
|
|
230191ece9 | ||
|
|
28448f99d9 | ||
|
|
c34de1baa4 | ||
|
|
a469f2f382 | ||
|
|
506b6570f3 | ||
|
|
8562dc2240 | ||
|
|
005ae2c9fb | ||
|
|
9ca087206e | ||
|
|
c0952c15c8 | ||
|
|
47616711ce | ||
|
|
7457b51aa4 | ||
|
|
a00048aaac | ||
|
|
6499381b4f | ||
|
|
0a102c15fd | ||
|
|
e0be4744be | ||
|
|
dd7656d143 | ||
|
|
f683ed4f29 | ||
|
|
3f470a72f5 | ||
|
|
f5bafa2868 | ||
|
|
b652102c42 | ||
|
|
55db24ab74 | ||
|
|
551e103158 | ||
|
|
8fc01ba138 | ||
|
|
1c1496afbc | ||
|
|
7007ab05e1 | ||
|
|
30bac658ed | ||
|
|
f6f83fcbe4 | ||
|
|
f6c68ec29c | ||
|
|
62a9b0eddd | ||
|
|
3c09033267 | ||
|
|
2ecf4b3a9b | ||
|
|
94ca291460 | ||
|
|
0e3eeece01 | ||
|
|
00dae6d6a1 | ||
|
|
e84957a2c8 | ||
|
|
1e66a2e57a | ||
|
|
9be9d05dbe | ||
|
|
072324f0ab | ||
|
|
c1e5f0e117 | ||
|
|
ae95f7e3ea | ||
|
|
bd7dfc63ff | ||
|
|
0ca134dc8f | ||
|
|
d1d7675a8c | ||
|
|
252e2305f2 | ||
|
|
9c72e20d1b | ||
|
|
ec41102f07 | ||
|
|
08ab7e816d | ||
|
|
f103a02a34 | ||
|
|
b413795e45 | ||
|
|
6a61747573 | ||
|
|
420317a18c | ||
|
|
af2ef3d6a5 | ||
|
|
9f2d13780c | ||
|
|
acec7e58e7 | ||
|
|
7060c0ab0d | ||
|
|
ab6fcb8943 | ||
|
|
cbf352173a | ||
|
|
027ff694a0 | ||
|
|
9da1fc523a | ||
|
|
44d541bafe | ||
|
|
dad205e729 | ||
|
|
8dbfe17ee4 | ||
|
|
38a418a37a | ||
|
|
6be2f96f26 | ||
|
|
47a6a13bdb | ||
|
|
525a23abfb | ||
|
|
4f637daeaa | ||
|
|
9559628273 | ||
|
|
5a43f46ac0 | ||
|
|
c3d30b18e2 | ||
|
|
7cb58b946a | ||
|
|
9306729fdc | ||
|
|
1ae4c9a349 | ||
|
|
be204fe873 | ||
|
|
6804e7d7a8 | ||
|
|
f4c104215b | ||
|
|
479890fc0d | ||
|
|
877c3b7107 | ||
|
|
cd35a58f83 | ||
|
|
cb1cc10278 | ||
|
|
6239e53091 | ||
|
|
ef93c692e5 | ||
|
|
ee49689110 | ||
|
|
04eabd5141 | ||
|
|
da1ed70c66 | ||
|
|
186f07b20c | ||
|
|
5e49ce22b2 | ||
|
|
af7634b498 | ||
|
|
b9354e44ae | ||
|
|
17a790b6d9 | ||
|
|
46805f4830 | ||
|
|
954c3db649 | ||
|
|
23add072f3 | ||
|
|
db2f9e11f7 | ||
|
|
2983bdb616 | ||
|
|
597b26ba7c | ||
|
|
f93c197d05 | ||
|
|
9764c01428 | ||
|
|
ad7080d801 | ||
|
|
071aae5cf7 | ||
|
|
10491da7c2 | ||
|
|
b616ac990b | ||
|
|
603bad4967 | ||
|
|
ddb73af515 | ||
|
|
c1d345441c | ||
|
|
e050a6eec3 | ||
|
|
b3c05bc606 | ||
|
|
3203271fdf | ||
|
|
6e1df18c38 | ||
|
|
96a75a8335 | ||
|
|
dd47f87616 | ||
|
|
f1ed8eff84 | ||
|
|
1e441c3ebf | ||
|
|
f4b66d30ec | ||
|
|
288f7d45e7 | ||
|
|
4ac70d2d7e | ||
|
|
0f3efc6fb2 | ||
|
|
f2904da653 | ||
|
|
b11f260377 | ||
|
|
9ab939456b | ||
|
|
5c089dab13 | ||
|
|
bba1c7f965 | ||
|
|
55a8b5d514 | ||
|
|
9c0f0d8e4f | ||
|
|
f24a1415da | ||
|
|
70c98e0819 | ||
|
|
39ad5fb62a | ||
|
|
356edb1f4b | ||
|
|
5b60243b22 | ||
|
|
9f5ac2d9b9 | ||
|
|
972cb96259 | ||
|
|
c2b0ecd6f6 | ||
|
|
47f460bb2c | ||
|
|
adca0256a0 | ||
|
|
7d396f3782 | ||
|
|
8ed695bcdc | ||
|
|
f8c297ddfb | ||
|
|
0f3df8db1b | ||
|
|
f9de547b95 | ||
|
|
cc953884d9 | ||
|
|
ebee00322a | ||
|
|
a99da61039 | ||
|
|
edff48d258 | ||
|
|
3844404637 | ||
|
|
5057c86707 | ||
|
|
b1b40d410f | ||
|
|
de60415f55 | ||
|
|
931e3b8b11 | ||
|
|
8560c3f673 | ||
|
|
54db2c8c10 | ||
|
|
c6868fa839 | ||
|
|
86e61c778c | ||
|
|
e615d7c032 | ||
|
|
08003bc2f2 | ||
|
|
1a232600a1 | ||
|
|
a8d0336cae | ||
|
|
e1d6fdfefb | ||
|
|
f8ef145bb8 | ||
|
|
a187180388 | ||
|
|
749fa4bb95 | ||
|
|
5c43750835 | ||
|
|
8ec44aff1a | ||
|
|
046a535ebc | ||
|
|
b7995832bc | ||
|
|
6a826b63c9 | ||
|
|
65a661ca4d | ||
|
|
2fb7f4faa6 | ||
|
|
ed560425a0 | ||
|
|
267320bc56 | ||
|
|
e6bf20937d |
14
.eslintrc.js
14
.eslintrc.js
@@ -29,4 +29,18 @@ module.exports = {
|
||||
"semi": "warn",
|
||||
"no-console": "warn"
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ["**/*.ts"],
|
||||
|
||||
parserOptions: {
|
||||
project: ["./tsconfig.eslint.json"],
|
||||
},
|
||||
|
||||
rules: {
|
||||
"@typescript-eslint/no-misused-promises": "error",
|
||||
"@typescript-eslint/no-floating-promises" : "error"
|
||||
}
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
3
.github/pull_request_template.md
vendored
Normal file
3
.github/pull_request_template.md
vendored
Normal 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
|
||||
|
||||
***
|
||||
21
.github/workflows/ci.yml
vendored
21
.github/workflows/ci.yml
vendored
@@ -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
|
||||
18
.github/workflows/docker-build.yml
vendored
18
.github/workflows/docker-build.yml
vendored
@@ -19,12 +19,13 @@ on:
|
||||
jobs:
|
||||
build_container:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/${{ inputs.username }}/${{ inputs.name }}
|
||||
@@ -33,14 +34,21 @@ jobs:
|
||||
flavor: |
|
||||
latest=true
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GH_TOKEN }}
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
with:
|
||||
platforms: arm,arm64
|
||||
- name: Set up buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: push
|
||||
uses: docker/build-push-action@v3
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ${{ inputs.folder }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
16
.github/workflows/error-server.yml
vendored
Normal file
16
.github/workflows/error-server.yml
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
name: Docker image builds
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
error-server:
|
||||
uses: ./.github/workflows/docker-build.yml
|
||||
with:
|
||||
name: "error-server"
|
||||
username: "ajayyy"
|
||||
folder: "./containers/error-server"
|
||||
secrets:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
21
.github/workflows/eslint.yml
vendored
21
.github/workflows/eslint.yml
vendored
@@ -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
|
||||
23
.github/workflows/generate-sqlite-base.yml
vendored
23
.github/workflows/generate-sqlite-base.yml
vendored
@@ -6,6 +6,7 @@ on:
|
||||
- master
|
||||
paths:
|
||||
- databases/**
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
make-base-db:
|
||||
@@ -13,16 +14,28 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v2
|
||||
- run: npm install
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: Set config
|
||||
run: |
|
||||
echo '{"mode": "init-db-and-exit"}' > config.json
|
||||
- name: Run Server
|
||||
timeout-minutes: 10
|
||||
run: npm start
|
||||
- uses: actions/upload-artifact@v2
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: SponsorTimesDB.db
|
||||
path: databases/sponsorTimes.db
|
||||
path: databases/sponsorTimes.db
|
||||
- uses: mchangrh/s3cmd-sync@f4f36b9705bdd9af7ac91964136989ac17e3b513
|
||||
with:
|
||||
args: --acl-public
|
||||
env:
|
||||
S3_ENDPOINT: ${{ secrets.S3_ENDPOINT }}
|
||||
S3_BUCKET: ${{ secrets.S3_BUCKET }}
|
||||
S3_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
|
||||
S3_ACCESS_KEY_SECRET: ${{ secrets.S3_ACCESS_KEY_SECRET }}
|
||||
SOURCE_DIR: 'databases/sponsorTimes.db'
|
||||
29
.github/workflows/postgres-redis-ci.yml
vendored
29
.github/workflows/postgres-redis-ci.yml
vendored
@@ -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
|
||||
2
.github/workflows/take-action.yml
vendored
2
.github/workflows/take-action.yml
vendored
@@ -7,6 +7,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: take the issue
|
||||
uses: bdougie/take-action@main
|
||||
uses: bdougie/take-action@28b86cd8d25593f037406ecbf96082db2836e928
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
121
.github/workflows/test.yaml
vendored
Normal file
121
.github/workflows/test.yaml
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
lint-build:
|
||||
name: Lint with ESLint and build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
- run: npm run tsc
|
||||
- name: cache dist build
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
key: dist-${{ github.sha }}
|
||||
path: |
|
||||
${{ github.workspace }}/dist
|
||||
${{ github.workspace }}/node_modules
|
||||
test-sqlite:
|
||||
name: Run Tests with SQLite
|
||||
runs-on: ubuntu-latest
|
||||
needs: lint-build
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
cache: npm
|
||||
- id: cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
key: dist-${{ github.sha }}
|
||||
path: |
|
||||
${{ github.workspace }}/dist
|
||||
${{ github.workspace }}/node_modules
|
||||
- if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: npm ci
|
||||
env:
|
||||
youTubeKeys_visitorData: ${{ secrets.YOUTUBEKEYS_VISITORDATA }}
|
||||
youTubeKeys_poToken: ${{ secrets.YOUTUBEKEYS_POTOKEN }}
|
||||
- name: Run SQLite Tests
|
||||
timeout-minutes: 5
|
||||
run: npx nyc --silent npm test
|
||||
- name: cache nyc output
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
key: nyc-sqlite-${{ github.sha }}
|
||||
path: ${{ github.workspace }}/.nyc_output
|
||||
test-postgres:
|
||||
name: Run Tests with PostgreSQL and Redis
|
||||
runs-on: ubuntu-latest
|
||||
needs: lint-build
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build the docker-compose stack
|
||||
env:
|
||||
PG_USER: ci_db_user
|
||||
PG_PASS: ci_db_pass
|
||||
run: docker compose -f docker/docker-compose-ci.yml up -d
|
||||
- name: Check running containers
|
||||
run: docker ps
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
cache: npm
|
||||
- id: cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
key: dist-${{ github.sha }}
|
||||
path: |
|
||||
${{ github.workspace }}/dist
|
||||
${{ github.workspace }}/node_modules
|
||||
- if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: npm ci
|
||||
- name: Run Postgres Tests
|
||||
env:
|
||||
TEST_POSTGRES: true
|
||||
youTubeKeys_visitorData: ${{ secrets.YOUTUBEKEYS_VISITORDATA }}
|
||||
youTubeKeys_poToken: ${{ secrets.YOUTUBEKEYS_POTOKEN }}
|
||||
timeout-minutes: 5
|
||||
run: npx nyc --silent npm test
|
||||
- name: cache nyc output
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
key: nyc-postgres-${{ github.sha }}
|
||||
path: ${{ github.workspace }}/.nyc_output
|
||||
codecov:
|
||||
needs: [test-sqlite, test-postgres]
|
||||
name: Run Codecov
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: restore postgres nyc output
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
key: nyc-postgres-${{ github.sha }}
|
||||
path: ${{ github.workspace }}/.nyc_output
|
||||
- name: restore sqlite nyc output
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
key: nyc-sqlite-${{ github.sha }}
|
||||
path: ${{ github.workspace }}/.nyc_output
|
||||
- run: npx nyc report --reporter=lcov
|
||||
- name: Upload coverage reports to Codecov
|
||||
uses: codecov/codecov-action@v4
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -45,3 +45,9 @@ working
|
||||
.DS_Store
|
||||
/.idea/
|
||||
/dist/
|
||||
|
||||
# nyc coverage output
|
||||
.nyc_output/
|
||||
coverage/
|
||||
|
||||
.vscode
|
||||
14
.nycrc.json
Normal file
14
.nycrc.json
Normal 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/*"
|
||||
]
|
||||
}
|
||||
@@ -1,20 +1,29 @@
|
||||
# SponsorTimesDB
|
||||
|
||||
[vipUsers](#vipUsers)
|
||||
[sponsorTimes](#sponsorTimes)
|
||||
[userNames](#userNames)
|
||||
[categoryVotes](#categoryVotes)
|
||||
[lockCategories](#lockCategories)
|
||||
[warnings](#warnings)
|
||||
[shadowBannedUsers](#shadowBannedUsers)
|
||||
[unlistedVideos](#unlistedVideos)
|
||||
[config](#config)
|
||||
[archivedSponsorTimes](#archivedSponsorTimes)
|
||||
- [vipUsers](#vipusers)
|
||||
- [sponsorTimes](#sponsortimes)
|
||||
- [userNames](#usernames)
|
||||
- [categoryVotes](#categoryvotes)
|
||||
- [lockCategories](#lockcategories)
|
||||
- [warnings](#warnings)
|
||||
- [shadowBannedUsers](#shadowbannedusers)
|
||||
- [videoInfo](#videoinfo)
|
||||
- [unlistedVideos](#unlistedvideos)
|
||||
- [config](#config)
|
||||
- [archivedSponsorTimes](#archivedsponsortimes)
|
||||
- [ratings](#ratings)
|
||||
- [userFeatures](#userFeatures)
|
||||
- [shadowBannedIPs](#shadowBannedIPs)
|
||||
- [titles](#titles)
|
||||
- [titleVotes](#titleVotes)
|
||||
- [thumbnails](#thumbnails)
|
||||
- [thumbnailTimestamps](#thumbnailTimestamps)
|
||||
- [thumbnailVotes](#thumbnailVotes)
|
||||
|
||||
### vipUsers
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| userID | TEXT | not null |
|
||||
| userID | TEXT | not null, primary key |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
@@ -30,7 +39,7 @@
|
||||
| votes | INTEGER | not null |
|
||||
| locked | INTEGER | not null, default '0' |
|
||||
| incorrectVotes | INTEGER | not null, default 1 |
|
||||
| UUID | TEXT | not null, unique |
|
||||
| UUID | TEXT | not null, unique, primary key |
|
||||
| userID | TEXT | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
| views | INTEGER | not null |
|
||||
@@ -50,14 +59,16 @@
|
||||
| sponsorTime_timeSubmitted | timeSubmitted |
|
||||
| sponsorTime_userID | userID |
|
||||
| sponsorTimes_UUID | UUID |
|
||||
| sponsorTimes_hashedVideoID | hashedVideoID, category |
|
||||
| sponsorTimes_videoID | videoID, service, category, timeSubmitted |
|
||||
| sponsorTimes_hashedVideoID | service, hashedVideoID, startTime |
|
||||
| sponsorTimes_videoID | service, videoID, startTime |
|
||||
| sponsorTimes_videoID_category | videoID, category |
|
||||
| sponsorTimes_description_gin | description, category |
|
||||
|
||||
### userNames
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| userID | TEXT | not null |
|
||||
| userID | TEXT | not null, primary key |
|
||||
| userName | TEXT | not null |
|
||||
| locked | INTEGER | not nul, default '0' |
|
||||
|
||||
@@ -72,6 +83,7 @@
|
||||
| UUID | TEXT | not null |
|
||||
| category | TEXT | not null |
|
||||
| votes | INTEGER | not null, default 0 |
|
||||
| id | SERIAL | primary key
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
@@ -88,6 +100,7 @@
|
||||
| hashedVideoID | TEXT | not null, default '' |
|
||||
| reason | TEXT | not null, default '' |
|
||||
| service | TEXT | not null, default 'YouTube' |
|
||||
| id | SERIAL | primary key
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
@@ -102,17 +115,22 @@
|
||||
| issuerUserID | TEXT | not null |
|
||||
| enabled | INTEGER | not null |
|
||||
| reason | TEXT | not null, default '' |
|
||||
| type | INTEGER | default 0 |
|
||||
|
||||
| constraint | field |
|
||||
| -- | :--: |
|
||||
| PRIMARY KEY | userID, issueTime |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| warnings_index | userID |
|
||||
| warnings_index | userID, issueTime, enabled |
|
||||
| warnings_issueTime | issueTime |
|
||||
|
||||
### shadowBannedUsers
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| userID | TEXT | not null |
|
||||
| userID | TEXT | not null, primary key |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
@@ -126,12 +144,11 @@
|
||||
| channelID | TEXT | not null |
|
||||
| title | TEXT | not null |
|
||||
| published | REAL | not null |
|
||||
| genreUrl | TEXT | not null |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| videoInfo_videoID | timeSubmitted |
|
||||
| videoInfo_channelID | userID |
|
||||
| videoInfo_videoID | videoID |
|
||||
| videoInfo_channelID | channelID |
|
||||
|
||||
### unlistedVideos
|
||||
|
||||
@@ -143,12 +160,13 @@
|
||||
| channelID | TEXT | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
| service | TEXT | not null, default 'YouTube' |
|
||||
| id | SERIAL | primary key
|
||||
|
||||
### config
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| key | TEXT | not null, unique |
|
||||
| key | TEXT | not null, unique, primary key |
|
||||
| value | TEXT | not null |
|
||||
|
||||
### archivedSponsorTimes
|
||||
@@ -161,7 +179,7 @@
|
||||
| votes | INTEGER | not null |
|
||||
| locked | INTEGER | not null, default '0' |
|
||||
| incorrectVotes | INTEGER | not null, default 1 |
|
||||
| UUID | TEXT | not null, unique |
|
||||
| UUID | TEXT | not null, unique, primary key |
|
||||
| userID | TEXT | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
| views | INTEGER | not null |
|
||||
@@ -174,6 +192,7 @@
|
||||
| shadowHidden | INTEGER | not null |
|
||||
| hashedVideoID | TEXT | not null, default '', sha256 |
|
||||
| userAgent | TEXT | not null, default '' |
|
||||
| description | TEXT | not null, default '' |
|
||||
|
||||
### ratings
|
||||
|
||||
@@ -184,6 +203,7 @@
|
||||
| type | INTEGER | not null |
|
||||
| count | INTEGER | not null |
|
||||
| hashedVideoID | TEXT | not null |
|
||||
| id | SERIAL | primary key
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
@@ -191,15 +211,125 @@
|
||||
| ratings_hashedVideoID | hashedVideoID, service |
|
||||
| ratings_videoID | videoID, service |
|
||||
|
||||
### userFeatures
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| userID | TEXT | not null |
|
||||
| feature | INTEGER | not null |
|
||||
| issuerUserID | TEXT | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
|
||||
| constraint | field |
|
||||
| -- | :--: |
|
||||
| primary key | userID, feature |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| userFeatures_userID | userID, feature |
|
||||
|
||||
### shadowBannedIPs
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| hashedIP | TEXT | not null, primary key |
|
||||
|
||||
### titles
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| videoID | TEXT | not null |
|
||||
| title | TEXT | not null |
|
||||
| original | INTEGER | default 0 |
|
||||
| userID | TEXT | not null
|
||||
| service | TEXT | not null |
|
||||
| hashedVideoID | TEXT | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
| UUID | TEXT | not null, primary key
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| titles_timeSubmitted | timeSubmitted |
|
||||
| titles_userID_timeSubmitted | videoID, service, userID, timeSubmitted |
|
||||
| titles_videoID | videoID, service |
|
||||
| titles_hashedVideoID_2 | service, hashedVideoID, timeSubmitted |
|
||||
|
||||
### titleVotes
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| UUID | TEXT | not null, primary key |
|
||||
| votes | INTEGER | not null, default 0 |
|
||||
| locked | INTEGER | not null, default 0 |
|
||||
| shadowHidden | INTEGER | not null, default 0 |
|
||||
| verification | INTEGER | default 0 |
|
||||
| downvotes | INTEGER | default 0 |
|
||||
| removed | INTEGER | default 0 |
|
||||
|
||||
| constraint | field |
|
||||
| -- | :--: |
|
||||
| foreign key | UUID references "titles"("UUID")
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| titleVotes_votes | UUID, votes
|
||||
|
||||
### thumbnails
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| original | INTEGER | default 0 |
|
||||
| userID | TEXT | not null |
|
||||
| service | TEXT | not null |
|
||||
| hashedVideoID | TEXT | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
| UUID | TEXT | not null, primary key |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| thumbnails_timeSubmitted | timeSubmitted |
|
||||
| thumbnails_votes_timeSubmitted | videoID, service, userID, timeSubmitted |
|
||||
| thumbnails_videoID | videoID, service |
|
||||
| thumbnails_hashedVideoID_2 | service, hashedVideoID, timeSubmitted |
|
||||
|
||||
### thumbnailTimestamps
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| UUID | TEXT | not null, primary key
|
||||
| timestamp | INTEGER | not null, default 0
|
||||
|
||||
| constraint | field |
|
||||
| -- | :--: |
|
||||
| foreign key | UUID references "thumbnails"("UUID")
|
||||
|
||||
### thumbnailVotes
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| UUID | TEXT | not null, primary key |
|
||||
| votes | INTEGER | not null, default 0 |
|
||||
| locked | INTEGER |not null, default 0 |
|
||||
| shadowHidden | INTEGER | not null, default 0 |
|
||||
| downvotes | INTEGER | default 0 |
|
||||
| removed | INTEGER | default 0 |
|
||||
|
||||
| constraint | field |
|
||||
| -- | :--: |
|
||||
| foreign key | UUID references "thumbnails"("UUID")
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| thumbnailVotes_votes | UUID, votes
|
||||
|
||||
# Private
|
||||
|
||||
[votes](#votes)
|
||||
[categoryVotes](#categoryVotes)
|
||||
[sponsorTimes](#sponsorTimes)
|
||||
[config](#config)
|
||||
[ratings](#ratings)
|
||||
[tempVipLog](#tempVipLog)
|
||||
[userNameLogs](#userNameLogs)
|
||||
- [votes](#votes)
|
||||
- [categoryVotes](#categoryVotes)
|
||||
- [sponsorTimes](#sponsorTimes)
|
||||
- [config](#config)
|
||||
- [ratings](#ratings)
|
||||
- [tempVipLog](#tempVipLog)
|
||||
- [userNameLogs](#userNameLogs)
|
||||
|
||||
### votes
|
||||
|
||||
@@ -209,6 +339,8 @@
|
||||
| userID | TEXT | not null |
|
||||
| hashedIP | TEXT | not null |
|
||||
| type | INTEGER | not null |
|
||||
| originalVoteType | INTEGER | not null | # Since type was reused to also specify the number of votes removed when less than 0, this is being used for the actual type
|
||||
| id | SERIAL | primary key |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
@@ -223,10 +355,11 @@
|
||||
| hashedIP | TEXT | not null |
|
||||
| category | TEXT | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
| id | SERIAL | primary key |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| categoryVotes_UUID | UUID, userID, hasedIP, category |
|
||||
| categoryVotes_UUID | UUID, userID, hashedIP, category |
|
||||
|
||||
### sponsorTimes
|
||||
|
||||
@@ -236,17 +369,17 @@
|
||||
| hashedIP | TEXT | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
| service | TEXT | not null, default 'YouTube' |
|
||||
| id | SERIAL | primary key |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
| sponsorTimes_hashedIP | hashedIP |
|
||||
| privateDB_sponsorTimes_videoID_v2 | videoID, service |
|
||||
| privateDB_sponsorTimes_v4 | videoID, service, timeSubmitted |
|
||||
|
||||
### config
|
||||
|
||||
| Name | Type | |
|
||||
| -- | :--: | -- |
|
||||
| key | TEXT | not null |
|
||||
| key | TEXT | not null, primary key |
|
||||
| value | TEXT | not null |
|
||||
|
||||
### ratings
|
||||
@@ -259,6 +392,7 @@
|
||||
| type | INTEGER | not null |
|
||||
| timeSubmitted | INTEGER | not null |
|
||||
| hashedIP | TEXT | not null |
|
||||
| id | SERIAL | primary key |
|
||||
|
||||
| index | field |
|
||||
| -- | :--: |
|
||||
@@ -271,6 +405,7 @@
|
||||
| targetUserID | TEXT | not null |
|
||||
| enabled | BOOLEAN | not null |
|
||||
| updatedAt | INTEGER | not null |
|
||||
| id | SERIAL | primary key |
|
||||
|
||||
### userNameLogs
|
||||
|
||||
@@ -281,3 +416,4 @@
|
||||
| oldUserName | TEXT | not null |
|
||||
| updatedByAdmin | BOOLEAN | not null |
|
||||
| updatedAt | INTEGER | not null |
|
||||
| id | SERIAL | primary key |
|
||||
10
Dockerfile
10
Dockerfile
@@ -1,16 +1,16 @@
|
||||
FROM node:16-alpine as builder
|
||||
FROM node:18-alpine as builder
|
||||
RUN apk add --no-cache --virtual .build-deps python3 make g++
|
||||
COPY package.json package-lock.json tsconfig.json entrypoint.sh ./
|
||||
COPY src src
|
||||
RUN npm ci && npm run tsc
|
||||
|
||||
FROM node:16-alpine as app
|
||||
FROM node:18-alpine as app
|
||||
WORKDIR /usr/src/app
|
||||
RUN apk add git postgresql-client
|
||||
RUN apk add --no-cache git postgresql-client
|
||||
COPY --from=builder ./node_modules ./node_modules
|
||||
COPY --from=builder ./dist ./dist
|
||||
COPY ./.git ./.git
|
||||
COPY ./.git/ ./.git
|
||||
COPY entrypoint.sh .
|
||||
COPY databases/*.sql databases/
|
||||
EXPOSE 8080
|
||||
CMD ./entrypoint.sh
|
||||
CMD ./entrypoint.sh
|
||||
|
||||
674
LICENSE
674
LICENSE
@@ -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
27
LICENSE.old
Normal 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.
|
||||
@@ -35,3 +35,7 @@ If you want to make changes, run `npm run dev` to automatically reload the serve
|
||||
# API Docs
|
||||
|
||||
Available [here](https://wiki.sponsor.ajay.app/index.php/API_Docs)
|
||||
|
||||
# License
|
||||
|
||||
This is licensed under AGPL-3.0-only.
|
||||
24
ci.json
24
ci.json
@@ -4,11 +4,12 @@
|
||||
"globalSalt": "testSalt",
|
||||
"adminUserID": "4bdfdc9cddf2c7d07a8a87b57bf6d25389fb75d1399674ee0e0938a6a60f4c3b",
|
||||
"newLeafURLs": ["placeholder"],
|
||||
"discordReportChannelWebhookURL": "http://127.0.0.1:8081/ReportChannelWebhook",
|
||||
"discordFirstTimeSubmissionsWebhookURL": "http://127.0.0.1:8081/FirstTimeSubmissionsWebhook",
|
||||
"discordCompletelyIncorrectReportWebhookURL": "http://127.0.0.1:8081/CompletelyIncorrectReportWebhook",
|
||||
"discordNeuralBlockRejectWebhookURL": "http://127.0.0.1:8081/NeuralBlockRejectWebhook",
|
||||
"discordReportChannelWebhookURL": "http://127.0.0.1:8081/webhook/ReportChannel",
|
||||
"discordFirstTimeSubmissionsWebhookURL": "http://127.0.0.1:8081/webhook/FirstTimeSubmissions",
|
||||
"discordCompletelyIncorrectReportWebhookURL": "http://127.0.0.1:8081/webhook/CompletelyIncorrectReport",
|
||||
"discordNeuralBlockRejectWebhookURL": "http://127.0.0.1:8081/webhook/NeuralBlockReject",
|
||||
"neuralBlockURL": "http://127.0.0.1:8081/NeuralBlock",
|
||||
"userCounterURL": "http://127.0.0.1:8081/UserCounter",
|
||||
"behindProxy": true,
|
||||
"postgres": {
|
||||
"user": "ci_db_user",
|
||||
@@ -17,10 +18,12 @@
|
||||
"port": 5432
|
||||
},
|
||||
"redis": {
|
||||
"enabled": true,
|
||||
"socket": {
|
||||
"host": "localhost",
|
||||
"port": 6379
|
||||
}
|
||||
},
|
||||
"expiryTime": 86400
|
||||
},
|
||||
"createDatabaseIfNotExist": true,
|
||||
"schemaFolder": "./databases",
|
||||
@@ -53,8 +56,6 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"maxNumberOfActiveWarnings": 3,
|
||||
"hoursAfterWarningExpires": 24,
|
||||
"rateLimit": {
|
||||
"vote": {
|
||||
"windowMs": 900000,
|
||||
@@ -67,5 +68,12 @@
|
||||
"max": 20,
|
||||
"statusCode": 200
|
||||
}
|
||||
}
|
||||
},
|
||||
"patreon": {
|
||||
"clientId": "testClientID",
|
||||
"clientSecret": "testClientSecret",
|
||||
"redirectUri": "http://127.0.0.1/fake/callback"
|
||||
},
|
||||
"minReputationToSubmitFiller": -1,
|
||||
"minUserIDLength": 0
|
||||
}
|
||||
|
||||
9
codecov.yml
Normal file
9
codecov.yml
Normal file
@@ -0,0 +1,9 @@
|
||||
comment: false
|
||||
coverage:
|
||||
status:
|
||||
project:
|
||||
default:
|
||||
informational: true
|
||||
patch:
|
||||
default:
|
||||
informational: true
|
||||
@@ -25,8 +25,6 @@
|
||||
"webhooks": [],
|
||||
"categoryList": ["sponsor", "intro", "outro", "interaction", "selfpromo", "preview", "music_offtopic", "poi_highlight"], // List of supported categories any other category will be rejected
|
||||
"getTopUsersCacheTimeMinutes": 5, // cacheTime for getTopUsers result in minutes
|
||||
"maxNumberOfActiveWarnings": 3, // Users with this number of warnings will be blocked until warnings expire
|
||||
"hoursAfterWarningExpire": 24,
|
||||
"rateLimit": {
|
||||
"vote": {
|
||||
"windowMs": 900000, // 15 minutes
|
||||
@@ -66,5 +64,6 @@
|
||||
{
|
||||
"name": "vipUsers"
|
||||
}]
|
||||
}
|
||||
},
|
||||
"minUserIDLength": 30 // minimum length of UserID to be accepted
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
FROM alpine
|
||||
RUN apk add postgresql-client
|
||||
RUN apk add restic --repository http://dl-cdn.alpinelinux.org/alpine/latest-stable/community/
|
||||
FROM alpine as builder
|
||||
WORKDIR /scripts
|
||||
COPY ./backup.sh ./backup.sh
|
||||
COPY ./forget.sh ./forget.sh
|
||||
|
||||
COPY ./backup.sh /usr/src/app/backup.sh
|
||||
RUN chmod +x /usr/src/app/backup.sh
|
||||
COPY ./backup.sh /usr/src/app/forget.sh
|
||||
RUN chmod +x /usr/src/app/forget.sh
|
||||
FROM alpine
|
||||
RUN apk add --no-cache postgresql-client restic
|
||||
COPY --from=builder --chmod=755 /scripts /usr/src/app/
|
||||
|
||||
RUN echo '30 * * * * /usr/src/app/backup.sh' >> /etc/crontabs/root
|
||||
RUN echo '10 0 * * 1 /usr/src/app/forget.sh' >> /etc/crontabs/root
|
||||
RUN echo '10 0 * * */2 /usr/src/app/forget.sh' >> /etc/crontabs/root
|
||||
|
||||
CMD crond -l 2 -f
|
||||
CMD crond -l 2 -f
|
||||
|
||||
@@ -1 +1 @@
|
||||
restic forget --prune --keep-last 48 --keep-daily 7 --keep-weekly 8
|
||||
restic forget --prune --keep-hourly 24 --keep-daily 7 --keep-weekly 8
|
||||
4
containers/error-server/Dockerfile
Normal file
4
containers/error-server/Dockerfile
Normal file
@@ -0,0 +1,4 @@
|
||||
FROM nginx as app
|
||||
EXPOSE 80
|
||||
COPY nginx.conf /etc/nginx/nginx.conf
|
||||
COPY default.conf /etc/nginx/conf.d/default.conf
|
||||
9
containers/error-server/default.conf
Normal file
9
containers/error-server/default.conf
Normal file
@@ -0,0 +1,9 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name localhost;
|
||||
|
||||
location / {
|
||||
return 503;
|
||||
}
|
||||
}
|
||||
19
containers/error-server/nginx.conf
Normal file
19
containers/error-server/nginx.conf
Normal file
@@ -0,0 +1,19 @@
|
||||
user nginx;
|
||||
worker_processes auto;
|
||||
|
||||
error_log /var/log/nginx/error.log notice;
|
||||
pid /var/run/nginx.pid;
|
||||
|
||||
events {
|
||||
worker_connections 4096;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
access_log off;
|
||||
error_log /dev/null crit;
|
||||
|
||||
include /etc/nginx/conf.d/*.conf;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
FROM ghcr.io/ajayyy/sb-server:latest
|
||||
EXPOSE 873/tcp
|
||||
RUN apk add rsync>3.2.4-r0
|
||||
RUN apk add rsync>3.4.1-r0
|
||||
RUN mkdir /usr/src/app/database-export
|
||||
|
||||
CMD rsync --no-detach --daemon & ./entrypoint.sh
|
||||
CMD rsync --no-detach --daemon & ./entrypoint.sh
|
||||
|
||||
@@ -26,4 +26,33 @@ CREATE TABLE IF NOT EXISTS "config" (
|
||||
"value" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "titleVotes" (
|
||||
"id" SERIAL PRIMARY KEY,
|
||||
"videoID" TEXT NOT NULL,
|
||||
"UUID" TEXT NOT NULL,
|
||||
"userID" TEXT NOT NULL,
|
||||
"hashedIP" TEXT NOT NULL,
|
||||
"type" INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "thumbnailVotes" (
|
||||
"id" SERIAL PRIMARY KEY,
|
||||
"videoID" TEXT NOT NULL,
|
||||
"UUID" TEXT NOT NULL,
|
||||
"userID" TEXT NOT NULL,
|
||||
"hashedIP" TEXT NOT NULL,
|
||||
"type" INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "casualVotes" (
|
||||
"UUID" SERIAL PRIMARY KEY,
|
||||
"videoID" TEXT NOT NULL,
|
||||
"service" TEXT NOT NULL,
|
||||
"userID" TEXT NOT NULL,
|
||||
"hashedIP" TEXT NOT NULL,
|
||||
"category" TEXT NOT NULL,
|
||||
"type" INTEGER NOT NULL,
|
||||
"timeSubmitted" INTEGER NOT NULL
|
||||
);
|
||||
|
||||
COMMIT;
|
||||
|
||||
@@ -23,4 +23,16 @@ CREATE INDEX IF NOT EXISTS "categoryVotes_UUID"
|
||||
CREATE INDEX IF NOT EXISTS "ratings_videoID"
|
||||
ON public."ratings" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, service COLLATE pg_catalog."default" ASC NULLS LAST, "userID" COLLATE pg_catalog."default" ASC NULLS LAST, "timeSubmitted" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
-- casualVotes
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "casualVotes_videoID"
|
||||
ON public."casualVotes" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST, "userID" COLLATE pg_catalog."default" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "casualVotes_userID"
|
||||
ON public."casualVotes" USING btree
|
||||
("userID" COLLATE pg_catalog."default" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
@@ -32,11 +32,78 @@ CREATE TABLE IF NOT EXISTS "categoryVotes" (
|
||||
"votes" INTEGER NOT NULL default 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "shadowBannedIPs" (
|
||||
"hashedIP" TEXT NOT NULL PRIMARY KEY
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "config" (
|
||||
"key" TEXT NOT NULL UNIQUE,
|
||||
"value" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "titles" (
|
||||
"videoID" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"original" INTEGER default 0,
|
||||
"userID" TEXT NOT NULL,
|
||||
"service" TEXT NOT NULL,
|
||||
"hashedVideoID" TEXT NOT NULL,
|
||||
"timeSubmitted" INTEGER NOT NULL,
|
||||
"UUID" TEXT NOT NULL PRIMARY KEY
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "titleVotes" (
|
||||
"UUID" TEXT NOT NULL PRIMARY KEY,
|
||||
"votes" INTEGER NOT NULL default 0,
|
||||
"locked" INTEGER NOT NULL default 0,
|
||||
"shadowHidden" INTEGER NOT NULL default 0,
|
||||
FOREIGN KEY("UUID") REFERENCES "titles"("UUID")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "thumbnails" (
|
||||
"videoID" TEXT NOT NULL,
|
||||
"original" INTEGER default 0,
|
||||
"userID" TEXT NOT NULL,
|
||||
"service" TEXT NOT NULL,
|
||||
"hashedVideoID" TEXT NOT NULL,
|
||||
"timeSubmitted" INTEGER NOT NULL,
|
||||
"UUID" TEXT NOT NULL PRIMARY KEY
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "thumbnailTimestamps" (
|
||||
"UUID" TEXT NOT NULL PRIMARY KEY,
|
||||
"timestamp" INTEGER NOT NULL default 0,
|
||||
FOREIGN KEY("UUID") REFERENCES "thumbnails"("UUID")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "thumbnailVotes" (
|
||||
"UUID" TEXT NOT NULL PRIMARY KEY,
|
||||
"votes" INTEGER NOT NULL default 0,
|
||||
"locked" INTEGER NOT NULL default 0,
|
||||
"shadowHidden" INTEGER NOT NULL default 0,
|
||||
FOREIGN KEY("UUID") REFERENCES "thumbnails"("UUID")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "casualVotes" (
|
||||
"UUID" TEXT PRIMARY KEY,
|
||||
"videoID" TEXT NOT NULL,
|
||||
"service" TEXT NOT NULL,
|
||||
"hashedVideoID" TEXT NOT NULL,
|
||||
"category" TEXT NOT NULL,
|
||||
"upvotes" INTEGER NOT NULL default 0,
|
||||
"downvotes" INTEGER NOT NULL default 0,
|
||||
"timeSubmitted" INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "casualVoteTitles" (
|
||||
"videoID" TEXT NOT NULL,
|
||||
"service" TEXT NOT NULL,
|
||||
"id" INTEGER NOT NULL,
|
||||
"hashedVideoID" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
PRIMARY KEY("videoID", "service", "id")
|
||||
);
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto; --!sqlite-ignore
|
||||
CREATE EXTENSION IF NOT EXISTS pg_trgm; --!sqlite-ignore
|
||||
|
||||
|
||||
@@ -25,6 +25,11 @@ CREATE INDEX IF NOT EXISTS "sponsorTimes_videoID"
|
||||
(service COLLATE pg_catalog."default" ASC NULLS LAST, "videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "startTime" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "sponsorTimes_videoID_category"
|
||||
ON public."sponsorTimes" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "category" COLLATE pg_catalog."default" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "sponsorTimes_description_gin"
|
||||
ON public."sponsorTimes" USING gin
|
||||
("description" COLLATE pg_catalog."default" gin_trgm_ops, category COLLATE pg_catalog."default" gin_trgm_ops)
|
||||
@@ -103,4 +108,91 @@ CREATE INDEX IF NOT EXISTS "ratings_hashedVideoID"
|
||||
CREATE INDEX IF NOT EXISTS "ratings_videoID"
|
||||
ON public."ratings" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, service COLLATE pg_catalog."default" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
--- userFeatures
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "userFeatures_userID"
|
||||
ON public."userFeatures" USING btree
|
||||
("userID" COLLATE pg_catalog."default" ASC NULLS LAST, "feature" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
-- titles
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "titles_timeSubmitted"
|
||||
ON public."titles" USING btree
|
||||
("timeSubmitted" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "titles_userID_timeSubmitted"
|
||||
ON public."titles" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST, "userID" COLLATE pg_catalog."default" DESC NULLS LAST, "timeSubmitted" DESC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "titles_videoID"
|
||||
ON public."titles" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "titles_hashedVideoID_2"
|
||||
ON public."titles" USING btree
|
||||
(service COLLATE pg_catalog."default" ASC NULLS LAST, "hashedVideoID" text_pattern_ops ASC NULLS LAST, "timeSubmitted" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
-- titleVotes
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "titleVotes_votes"
|
||||
ON public."titleVotes" USING btree
|
||||
("UUID" COLLATE pg_catalog."default" ASC NULLS LAST, "votes" DESC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
-- thumbnails
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "thumbnails_timeSubmitted"
|
||||
ON public."thumbnails" USING btree
|
||||
("timeSubmitted" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "thumbnails_votes_timeSubmitted"
|
||||
ON public."thumbnails" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST, "userID" COLLATE pg_catalog."default" DESC NULLS LAST, "timeSubmitted" DESC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "thumbnails_videoID"
|
||||
ON public."thumbnails" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "thumbnails_hashedVideoID_2"
|
||||
ON public."thumbnails" USING btree
|
||||
(service COLLATE pg_catalog."default" ASC NULLS LAST, "hashedVideoID" text_pattern_ops ASC NULLS LAST, "timeSubmitted" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
-- thumbnailVotes
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "thumbnailVotes_votes"
|
||||
ON public."thumbnailVotes" USING btree
|
||||
("UUID" COLLATE pg_catalog."default" ASC NULLS LAST, "votes" DESC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
-- casualVotes
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "casualVotes_timeSubmitted"
|
||||
ON public."casualVotes" USING btree
|
||||
("timeSubmitted" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "casualVotes_userID_timeSubmitted"
|
||||
ON public."casualVotes" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST, "timeSubmitted" DESC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "casualVotes_videoID"
|
||||
ON public."casualVotes" USING btree
|
||||
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "casualVotes_hashedVideoID_2"
|
||||
ON public."casualVotes" USING btree
|
||||
(service COLLATE pg_catalog."default" ASC NULLS LAST, "hashedVideoID" text_pattern_ops ASC NULLS LAST, "timeSubmitted" ASC NULLS LAST)
|
||||
TABLESPACE pg_default;
|
||||
9
databases/_upgrade_private_10.sql
Normal file
9
databases/_upgrade_private_10.sql
Normal 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;
|
||||
18
databases/_upgrade_private_11.sql
Normal file
18
databases/_upgrade_private_11.sql
Normal 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;
|
||||
7
databases/_upgrade_private_12.sql
Normal file
7
databases/_upgrade_private_12.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "casualVotes" DROP COLUMN "type";
|
||||
|
||||
UPDATE "config" SET value = 12 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
7
databases/_upgrade_private_13.sql
Normal file
7
databases/_upgrade_private_13.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "casualVotes" ADD "titleID" INTEGER default 0;
|
||||
|
||||
UPDATE "config" SET value = 13 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
13
databases/_upgrade_sponsorTimes_33.sql
Normal file
13
databases/_upgrade_sponsorTimes_33.sql
Normal 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;
|
||||
7
databases/_upgrade_sponsorTimes_34.sql
Normal file
7
databases/_upgrade_sponsorTimes_34.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "videoInfo" DROP COLUMN "genreUrl";
|
||||
|
||||
UPDATE "config" SET value = 34 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
7
databases/_upgrade_sponsorTimes_35.sql
Normal file
7
databases/_upgrade_sponsorTimes_35.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "titleVotes" ADD "verification" INTEGER default 0;
|
||||
|
||||
UPDATE "config" SET value = 35 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
7
databases/_upgrade_sponsorTimes_36.sql
Normal file
7
databases/_upgrade_sponsorTimes_36.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "warnings" ADD "type" INTEGER default 0;
|
||||
|
||||
UPDATE "config" SET value = 36 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
7
databases/_upgrade_sponsorTimes_37.sql
Normal file
7
databases/_upgrade_sponsorTimes_37.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "titles" ADD UNIQUE ("videoID", "title"); --!sqlite-ignore
|
||||
|
||||
UPDATE "config" SET value = 37 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
11
databases/_upgrade_sponsorTimes_38.sql
Normal file
11
databases/_upgrade_sponsorTimes_38.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
UPDATE "titleVotes" SET "shadowHidden" = 1
|
||||
WHERE "UUID" IN (SELECT "UUID" FROM "titles" INNER JOIN "shadowBannedUsers" "bans" ON "titles"."userID" = "bans"."userID");
|
||||
|
||||
UPDATE "thumbnailVotes" SET "shadowHidden" = 1
|
||||
WHERE "UUID" IN (SELECT "UUID" FROM "thumbnails" INNER JOIN "shadowBannedUsers" "bans" ON "thumbnails"."userID" = "bans"."userID");
|
||||
|
||||
UPDATE "config" SET value = 38 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
11
databases/_upgrade_sponsorTimes_39.sql
Normal file
11
databases/_upgrade_sponsorTimes_39.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "titleVotes" ADD "downvotes" INTEGER default 0;
|
||||
ALTER TABLE "titleVotes" ADD "removed" INTEGER default 0;
|
||||
|
||||
ALTER TABLE "thumbnailVotes" ADD "downvotes" INTEGER default 0;
|
||||
ALTER TABLE "thumbnailVotes" ADD "removed" INTEGER default 0;
|
||||
|
||||
UPDATE "config" SET value = 39 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
8
databases/_upgrade_sponsorTimes_40.sql
Normal file
8
databases/_upgrade_sponsorTimes_40.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
DROP INDEX IF EXISTS "titles_hashedVideoID";
|
||||
DROP INDEX IF EXISTS "thumbnails_hashedVideoID";
|
||||
|
||||
UPDATE "config" SET value = 40 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
8
databases/_upgrade_sponsorTimes_41.sql
Normal file
8
databases/_upgrade_sponsorTimes_41.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "titles" ADD "casualMode" INTEGER default 0;
|
||||
ALTER TABLE "thumbnails" ADD "casualMode" INTEGER default 0;
|
||||
|
||||
UPDATE "config" SET value = 41 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
7
databases/_upgrade_sponsorTimes_42.sql
Normal file
7
databases/_upgrade_sponsorTimes_42.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "casualVotes" DROP COLUMN "downvotes";
|
||||
|
||||
UPDATE "config" SET value = 42 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
7
databases/_upgrade_sponsorTimes_43.sql
Normal file
7
databases/_upgrade_sponsorTimes_43.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "casualVotes" ADD "titleID" INTEGER default 0;
|
||||
|
||||
UPDATE "config" SET value = 43 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
8
databases/_upgrade_sponsorTimes_44.sql
Normal file
8
databases/_upgrade_sponsorTimes_44.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "titles" ADD "userAgent" TEXT NOT NULL default '';
|
||||
ALTER TABLE "thumbnails" ADD "userAgent" TEXT NOT NULL default '';
|
||||
|
||||
UPDATE "config" SET value = 44 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
7
databases/_upgrade_sponsorTimes_45.sql
Normal file
7
databases/_upgrade_sponsorTimes_45.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
ALTER TABLE "warnings" ADD "disableTime" INTEGER NULL;
|
||||
|
||||
UPDATE "config" SET value = 45 WHERE key = 'version';
|
||||
|
||||
COMMIT;
|
||||
@@ -1,6 +1,6 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
/* Add new voting field */
|
||||
/* Add 'locked' field */
|
||||
CREATE TABLE "sqlb_temp_table_6" (
|
||||
"videoID" TEXT NOT NULL,
|
||||
"startTime" REAL NOT NULL,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
/* Add Service field */
|
||||
/* Add 'videoDuration' field */
|
||||
CREATE TABLE "sqlb_temp_table_8" (
|
||||
"videoID" TEXT NOT NULL,
|
||||
"startTime" REAL NOT NULL,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
/* Add Service field */
|
||||
/* Change 'videoDuration' field from INTEGER to REAL */
|
||||
CREATE TABLE "sqlb_temp_table_9" (
|
||||
"videoID" TEXT NOT NULL,
|
||||
"startTime" REAL NOT NULL,
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
maxmemory-policy allkeys-lru
|
||||
maxmemory 6500mb
|
||||
maxmemory 6000mb
|
||||
|
||||
appendonly no
|
||||
save ""
|
||||
@@ -4,9 +4,9 @@ echo 'Entrypoint script'
|
||||
cd /usr/src/app
|
||||
|
||||
# blank config, use defaults
|
||||
cat <<EOF > config.json
|
||||
test -e config.json || cat <<EOF > config.json
|
||||
{
|
||||
}
|
||||
EOF
|
||||
|
||||
node dist/src/index.js
|
||||
node dist/src/index.js
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<!--# echo var="status"--> <!--# echo var="status_text"--> https://status.sponsor.ajay.app
|
||||
@@ -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';
|
||||
}
|
||||
317
nginx/nginx.conf
317
nginx/nginx.conf
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
proxy_redirect off;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Connection "";
|
||||
client_max_body_size 10m;
|
||||
client_body_buffer_size 128k;
|
||||
proxy_connect_timeout 5s;
|
||||
#proxy_send_timeout 10;
|
||||
proxy_read_timeout 30s;
|
||||
proxy_buffers 32 4k;
|
||||
proxy_http_version 1.1;
|
||||
8249
package-lock.json
generated
8249
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
64
package.json
64
package.json
@@ -5,49 +5,59 @@
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"test": "npm run tsc && ts-node test/test.ts",
|
||||
"cover": "nyc npm test",
|
||||
"cover:report": "nyc report",
|
||||
"dev": "nodemon",
|
||||
"dev:bash": "nodemon -x 'npm test ; npm start'",
|
||||
"postgres:docker": "docker run --rm -p 5432:5432 -e POSTGRES_USER=ci_db_user -e POSTGRES_PASSWORD=ci_db_pass postgres:alpine",
|
||||
"redis:docker": "docker run --rm -p 6379:6379 redis:alpine",
|
||||
"postgres:docker": "docker run --init -it --rm -p 5432:5432 -e POSTGRES_USER=ci_db_user -e POSTGRES_PASSWORD=ci_db_pass postgres:14-alpine",
|
||||
"redis:docker": "docker run --init -it --rm -p 6379:6379 redis:7-alpine --save '' --appendonly no",
|
||||
"start": "ts-node src/index.ts",
|
||||
"tsc": "tsc -p tsconfig.json",
|
||||
"lint": "eslint src test",
|
||||
"lint:fix": "eslint src test --fix"
|
||||
},
|
||||
"author": "Ajay Ramachandran",
|
||||
"license": "MIT",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"axios": "^0.24.0",
|
||||
"better-sqlite3": "^7.4.5",
|
||||
"cron": "^1.8.2",
|
||||
"express": "^4.17.1",
|
||||
"axios": "^1.12.1",
|
||||
"better-sqlite3": "^11.2.1",
|
||||
"cron": "^2.1.0",
|
||||
"express": "^4.21.2",
|
||||
"express-promise-router": "^4.1.1",
|
||||
"express-rate-limit": "^6.3.0",
|
||||
"express-rate-limit": "^6.7.0",
|
||||
"form-data": "^4.0.4",
|
||||
"lodash": "^4.17.21",
|
||||
"pg": "^8.7.1",
|
||||
"lru-cache": "^10.2.0",
|
||||
"lz4-napi": "^2.2.0",
|
||||
"pg": "^8.8.0",
|
||||
"rate-limit-redis": "^3.0.1",
|
||||
"redis": "^4.0.6",
|
||||
"sync-mysql": "^3.0.1"
|
||||
"redis": "^4.6.13",
|
||||
"seedrandom": "^3.0.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.4.1",
|
||||
"@types/cron": "^1.7.3",
|
||||
"@types/express": "^4.17.13",
|
||||
"@types/lodash": "^4.14.178",
|
||||
"@types/mocha": "^9.0.0",
|
||||
"@types/node": "^16.11.11",
|
||||
"@types/pg": "^8.6.1",
|
||||
"@typescript-eslint/eslint-plugin": "^5.5.0",
|
||||
"@typescript-eslint/parser": "^5.5.0",
|
||||
"eslint": "^8.3.0",
|
||||
"mocha": "^9.1.3",
|
||||
"nodemon": "^2.0.15",
|
||||
"sinon": "^12.0.1",
|
||||
"@istanbuljs/nyc-config-typescript": "^1.0.2",
|
||||
"@types/better-sqlite3": "^7.6.2",
|
||||
"@types/cron": "^2.0.0",
|
||||
"@types/express": "^4.17.14",
|
||||
"@types/lodash": "^4.14.189",
|
||||
"@types/mocha": "^10.0.0",
|
||||
"@types/node": "^18.11.9",
|
||||
"@types/pg": "^8.6.5",
|
||||
"@types/seedrandom": "^3.0.5",
|
||||
"@types/sinon": "^10.0.13",
|
||||
"@typescript-eslint/eslint-plugin": "^5.44.0",
|
||||
"@typescript-eslint/parser": "^5.44.0",
|
||||
"axios-mock-adapter": "^1.21.2",
|
||||
"eslint": "^8.28.0",
|
||||
"mocha": "^10.8.2",
|
||||
"nodemon": "^3.1.9",
|
||||
"nyc": "^15.1.0",
|
||||
"sinon": "^14.0.2",
|
||||
"ts-mock-imports": "^1.3.8",
|
||||
"ts-node": "^10.4.0",
|
||||
"typescript": "^4.5.2"
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "^4.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
|
||||
84
src/app.ts
84
src/app.ts
@@ -1,7 +1,6 @@
|
||||
import express, { Request, RequestHandler, Response, Router } from "express";
|
||||
import { config } from "./config";
|
||||
import { oldSubmitSponsorTimes } from "./routes/oldSubmitSponsorTimes";
|
||||
import { oldGetVideoSponsorTimes } from "./routes/oldGetVideoSponsorTimes";
|
||||
import { postSegmentShift } from "./routes/postSegmentShift";
|
||||
import { postWarning } from "./routes/postWarning";
|
||||
import { getIsUserVIP } from "./routes/getIsUserVIP";
|
||||
@@ -21,13 +20,13 @@ import { viewedVideoSponsorTime } from "./routes/viewedVideoSponsorTime";
|
||||
import { voteOnSponsorTime, getUserID as voteGetUserID } from "./routes/voteOnSponsorTime";
|
||||
import { getSkipSegmentsByHash } from "./routes/getSkipSegmentsByHash";
|
||||
import { postSkipSegments } from "./routes/postSkipSegments";
|
||||
import { endpoint as getSkipSegments } from "./routes/getSkipSegments";
|
||||
import { getSkipSegments, oldGetVideoSponsorTimes } from "./routes/getSkipSegments";
|
||||
import { userCounter } from "./middleware/userCounter";
|
||||
import { loggerMiddleware } from "./middleware/logger";
|
||||
import { corsMiddleware } from "./middleware/cors";
|
||||
import { apiCspMiddleware } from "./middleware/apiCsp";
|
||||
import { rateLimitMiddleware } from "./middleware/requestRateLimit";
|
||||
import dumpDatabase, { appExportPath, downloadFile } from "./routes/dumpDatabase";
|
||||
import dumpDatabase from "./routes/dumpDatabase";
|
||||
import { endpoint as getSegmentInfo } from "./routes/getSegmentInfo";
|
||||
import { postClearCache } from "./routes/postClearCache";
|
||||
import { addUnlistedVideo } from "./routes/addUnlistedVideo";
|
||||
@@ -43,11 +42,26 @@ import ExpressPromiseRouter from "express-promise-router";
|
||||
import { Server } from "http";
|
||||
import { youtubeApiProxy } from "./routes/youtubeApiProxy";
|
||||
import { getChapterNames } from "./routes/getChapterNames";
|
||||
import { postRating } from "./routes/ratings/postRating";
|
||||
import { getRating } from "./routes/ratings/getRating";
|
||||
import { postClearCache as ratingPostClearCache } from "./routes/ratings/postClearCache";
|
||||
import { getTopCategoryUsers } from "./routes/getTopCategoryUsers";
|
||||
import { addUserAsTempVIP } from "./routes/addUserAsTempVIP";
|
||||
import { endpoint as getVideoLabels } from "./routes/getVideoLabel";
|
||||
import { getVideoLabelsByHash } from "./routes/getVideoLabelByHash";
|
||||
import { addFeature } from "./routes/addFeature";
|
||||
import { generateTokenRequest } from "./routes/generateToken";
|
||||
import { verifyTokenRequest } from "./routes/verifyToken";
|
||||
import { getBranding, getBrandingByHashEndpoint } from "./routes/getBranding";
|
||||
import { postBranding } from "./routes/postBranding";
|
||||
import { cacheMiddlware } from "./middleware/etag";
|
||||
import { hostHeader } from "./middleware/hostHeader";
|
||||
import { getBrandingStats } from "./routes/getBrandingStats";
|
||||
import { getTopBrandingUsers } from "./routes/getTopBrandingUsers";
|
||||
import { getFeatureFlag } from "./routes/getFeatureFlag";
|
||||
import { getReady } from "./routes/getReady";
|
||||
import { getMetrics } from "./routes/getMetrics";
|
||||
import { getSegmentID } from "./routes/getSegmentID";
|
||||
import { postCasual } from "./routes/postCasual";
|
||||
import { getConfigEndpoint } from "./routes/getConfig";
|
||||
import { setConfig } from "./routes/setConfig";
|
||||
|
||||
export function createServer(callback: () => void): Server {
|
||||
// Create a service (the app object is just a callback).
|
||||
@@ -55,11 +69,14 @@ export function createServer(callback: () => void): Server {
|
||||
|
||||
const router = ExpressPromiseRouter();
|
||||
app.use(router);
|
||||
app.set("etag", false); // disable built in etag
|
||||
|
||||
//setup CORS correctly
|
||||
router.use(corsMiddleware);
|
||||
router.use(loggerMiddleware);
|
||||
router.use("/api/", apiCspMiddleware);
|
||||
router.use(hostHeader);
|
||||
router.use(cacheMiddlware);
|
||||
router.use(express.json());
|
||||
|
||||
if (config.userCounterURL) router.use(userCounter);
|
||||
@@ -70,20 +87,21 @@ export function createServer(callback: () => void): Server {
|
||||
// Set production mode
|
||||
app.set("env", config.mode || "production");
|
||||
|
||||
setupRoutes(router);
|
||||
const server = app.listen(config.port, callback);
|
||||
|
||||
return app.listen(config.port, callback);
|
||||
setupRoutes(router, server);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
function setupRoutes(router: Router) {
|
||||
/* eslint-disable @typescript-eslint/no-misused-promises */
|
||||
function setupRoutes(router: Router, server: Server) {
|
||||
// Rate limit endpoint lists
|
||||
const voteEndpoints: RequestHandler[] = [voteOnSponsorTime];
|
||||
const viewEndpoints: RequestHandler[] = [viewedVideoSponsorTime];
|
||||
const postRateEndpoints: RequestHandler[] = [postRating];
|
||||
if (config.rateLimit) {
|
||||
if (config.rateLimit && config.redisRateLimit) {
|
||||
if (config.rateLimit.vote) voteEndpoints.unshift(rateLimitMiddleware(config.rateLimit.vote, voteGetUserID));
|
||||
if (config.rateLimit.view) viewEndpoints.unshift(rateLimitMiddleware(config.rateLimit.view));
|
||||
if (config.rateLimit.rate) postRateEndpoints.unshift(rateLimitMiddleware(config.rateLimit.rate));
|
||||
}
|
||||
|
||||
//add the get function
|
||||
@@ -108,6 +126,8 @@ function setupRoutes(router: Router) {
|
||||
router.get("/api/viewedVideoSponsorTime", ...viewEndpoints);
|
||||
router.post("/api/viewedVideoSponsorTime", ...viewEndpoints);
|
||||
|
||||
router.get("/api/segmentID", getSegmentID);
|
||||
|
||||
//To set your username for the stats view
|
||||
router.post("/api/setUsername", setUsername);
|
||||
|
||||
@@ -133,11 +153,14 @@ function setupRoutes(router: Router) {
|
||||
|
||||
router.get("/api/getTopUsers", getTopUsers);
|
||||
router.get("/api/getTopCategoryUsers", getTopCategoryUsers);
|
||||
router.get("/api/getTopBrandingUsers", getTopBrandingUsers);
|
||||
|
||||
//send out totals
|
||||
//send the total submissions, total views and total minutes saved
|
||||
router.get("/api/getTotalStats", getTotalStats);
|
||||
|
||||
router.get("/api/brandingStats", getBrandingStats);
|
||||
|
||||
router.get("/api/getUserInfo", getUserInfo);
|
||||
router.get("/api/userInfo", getUserInfo);
|
||||
|
||||
@@ -187,8 +210,11 @@ function setupRoutes(router: Router) {
|
||||
router.get("/api/chapterNames", getChapterNames);
|
||||
|
||||
// get status
|
||||
router.get("/api/status/:value", getStatus);
|
||||
router.get("/api/status", getStatus);
|
||||
router.get("/api/status/:value", (req, res) => getStatus(req, res, server));
|
||||
router.get("/api/status", (req, res) => getStatus(req, res, server));
|
||||
router.get("/metrics", (req, res) => getMetrics(req, res, server));
|
||||
|
||||
router.get("/api/ready", (req, res) => getReady(req, res, server));
|
||||
|
||||
router.get("/api/youtubeApiProxy", youtubeApiProxy);
|
||||
// get user category stats
|
||||
@@ -196,20 +222,36 @@ function setupRoutes(router: Router) {
|
||||
|
||||
router.get("/api/lockReason", getLockReason);
|
||||
|
||||
// ratings
|
||||
router.get("/api/ratings/rate/:prefix", getRating);
|
||||
router.get("/api/ratings/rate", getRating);
|
||||
router.post("/api/ratings/rate", postRateEndpoints);
|
||||
router.post("/api/ratings/clearCache", ratingPostClearCache);
|
||||
router.post("/api/feature", addFeature);
|
||||
|
||||
router.get("/api/featureFlag/:name", getFeatureFlag);
|
||||
|
||||
router.get("/api/generateToken/:type", generateTokenRequest);
|
||||
router.get("/api/verifyToken", verifyTokenRequest);
|
||||
|
||||
// labels
|
||||
router.get("/api/videoLabels", getVideoLabels);
|
||||
router.get("/api/videoLabels/:prefix", getVideoLabelsByHash);
|
||||
|
||||
router.get("/api/branding", getBranding);
|
||||
router.get("/api/branding/:prefix", getBrandingByHashEndpoint);
|
||||
router.post("/api/branding", postBranding);
|
||||
|
||||
router.get("/api/config", getConfigEndpoint);
|
||||
router.post("/api/config", setConfig);
|
||||
|
||||
router.post("/api/casual", postCasual);
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (config.postgres?.enabled) {
|
||||
router.get("/database", (req, res) => dumpDatabase(req, res, true));
|
||||
router.get("/database.json", (req, res) => dumpDatabase(req, res, false));
|
||||
router.get("/database/*", downloadFile);
|
||||
router.use("/download", express.static(appExportPath));
|
||||
router.get("/database/*", (req, res) => res.status(404).send("CSV downloads disabled. Please use sb-mirror rsync"));
|
||||
router.use("/download", (req, res) => res.status(404).send("CSV downloads disabled. Please use sb-mirror rsync"));
|
||||
} else {
|
||||
router.get("/database.db", function (req: Request, res: Response) {
|
||||
res.sendFile("./databases/sponsorTimes.db", { root: "./" });
|
||||
});
|
||||
}
|
||||
}
|
||||
/* eslint-enable @typescript-eslint/no-misused-promises */
|
||||
|
||||
125
src/config.ts
125
src/config.ts
@@ -1,7 +1,6 @@
|
||||
import fs from "fs";
|
||||
import { SBSConfig } from "./types/config.model";
|
||||
import packageJson from "../package.json";
|
||||
import { isBoolean, isNumber } from "lodash";
|
||||
|
||||
const isTestMode = process.env.npm_lifecycle_script === packageJson.scripts.test;
|
||||
const configFile = process.env.TEST_POSTGRES ? "ci.json"
|
||||
@@ -20,7 +19,8 @@ addDefaults(config, {
|
||||
privateDBSchema: "./databases/_private.db.sql",
|
||||
readOnly: false,
|
||||
webhooks: [],
|
||||
categoryList: ["sponsor", "selfpromo", "exclusive_access", "interaction", "intro", "outro", "preview", "music_offtopic", "filler", "poi_highlight"],
|
||||
categoryList: ["sponsor", "selfpromo", "exclusive_access", "interaction", "intro", "outro", "preview", "hook", "music_offtopic", "filler", "poi_highlight", "chapter"],
|
||||
casualCategoryList: ["funny", "creative", "clever", "descriptive", "other"],
|
||||
categorySupport: {
|
||||
sponsor: ["skip", "mute", "full"],
|
||||
selfpromo: ["skip", "mute", "full"],
|
||||
@@ -29,19 +29,27 @@ addDefaults(config, {
|
||||
intro: ["skip", "mute"],
|
||||
outro: ["skip", "mute"],
|
||||
preview: ["skip", "mute"],
|
||||
hook: ["skip", "mute"],
|
||||
filler: ["skip", "mute"],
|
||||
music_offtopic: ["skip"],
|
||||
poi_highlight: ["poi"],
|
||||
chapter: ["chapter"]
|
||||
},
|
||||
maxNumberOfActiveWarnings: 1,
|
||||
hoursAfterWarningExpires: 16300000,
|
||||
deArrowTypes: ["title", "thumbnail"],
|
||||
maxTitleLength: 110,
|
||||
adminUserID: "",
|
||||
discordCompletelyIncorrectReportWebhookURL: null,
|
||||
discordFirstTimeSubmissionsWebhookURL: null,
|
||||
discordNeuralBlockRejectWebhookURL: null,
|
||||
discordFailedReportChannelWebhookURL: null,
|
||||
discordReportChannelWebhookURL: null,
|
||||
discordMaliciousReportWebhookURL: null,
|
||||
discordDeArrowLockedWebhookURL: null,
|
||||
discordDeArrowWarnedWebhookURL: null,
|
||||
discordNewUserWebhookURL: null,
|
||||
discordRejectedNewUserWebhookURL: null,
|
||||
minReputationToSubmitChapter: 0,
|
||||
minReputationToSubmitFiller: 0,
|
||||
getTopUsersCacheTimeMinutes: 240,
|
||||
globalSalt: null,
|
||||
mode: "",
|
||||
@@ -59,15 +67,11 @@ addDefaults(config, {
|
||||
max: 10,
|
||||
statusCode: 200,
|
||||
message: "OK",
|
||||
},
|
||||
rate: {
|
||||
windowMs: 900000,
|
||||
max: 20,
|
||||
statusCode: 200,
|
||||
message: "Success",
|
||||
}
|
||||
},
|
||||
requestValidatorRules: [],
|
||||
userCounterURL: null,
|
||||
userCounterRatio: 10,
|
||||
newLeafURLs: null,
|
||||
maxRewardTimePerSegmentInSeconds: 600,
|
||||
poiMinimumStartTime: 2,
|
||||
@@ -76,8 +80,30 @@ addDefaults(config, {
|
||||
user: "",
|
||||
host: "",
|
||||
password: "",
|
||||
port: 5432
|
||||
port: 5432,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 10000,
|
||||
maxTries: 3,
|
||||
maxActiveRequests: 0,
|
||||
timeout: 60000,
|
||||
highLoadThreshold: 10,
|
||||
redisTimeoutThreshold: 1000
|
||||
},
|
||||
postgresReadOnly: {
|
||||
enabled: false,
|
||||
weight: 1,
|
||||
user: "",
|
||||
host: "",
|
||||
password: "",
|
||||
port: 5432,
|
||||
readTimeout: 250,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 10000,
|
||||
maxTries: 3,
|
||||
fallbackOnFail: true,
|
||||
stopRetryThreshold: 800
|
||||
},
|
||||
postgresPrivateMax: 10,
|
||||
dumpDatabase: {
|
||||
enabled: false,
|
||||
minTimeBetweenMs: 180000,
|
||||
@@ -110,6 +136,28 @@ addDefaults(config, {
|
||||
},
|
||||
{
|
||||
name: "ratings"
|
||||
},
|
||||
{
|
||||
name: "titles"
|
||||
},
|
||||
{
|
||||
name: "titleVotes"
|
||||
},
|
||||
{
|
||||
name: "thumbnails"
|
||||
},
|
||||
{
|
||||
name: "thumbnailTimestamps"
|
||||
},
|
||||
{
|
||||
name: "thumbnailVotes"
|
||||
},
|
||||
{
|
||||
name: "casualVotes",
|
||||
order: "timeSubmitted"
|
||||
},
|
||||
{
|
||||
name: "casualVoteTitles"
|
||||
}]
|
||||
},
|
||||
diskCacheURL: null,
|
||||
@@ -120,7 +168,52 @@ addDefaults(config, {
|
||||
host: "",
|
||||
port: 0
|
||||
},
|
||||
disableOfflineQueue: true
|
||||
disableOfflineQueue: true,
|
||||
expiryTime: 24 * 60 * 60,
|
||||
getTimeout: 40,
|
||||
maxConnections: 15000,
|
||||
maxWriteConnections: 1000,
|
||||
commandsQueueMaxLength: 3000,
|
||||
stopWritingAfterResponseTime: 50,
|
||||
responseTimePause: 1000,
|
||||
maxReadResponseTime: 500,
|
||||
disableHashCache: false,
|
||||
clientCacheSize: 2000,
|
||||
useCompression: false,
|
||||
dragonflyMode: false
|
||||
},
|
||||
redisRead: {
|
||||
enabled: false,
|
||||
socket: {
|
||||
host: "",
|
||||
port: 0
|
||||
},
|
||||
disableOfflineQueue: true,
|
||||
weight: 1
|
||||
},
|
||||
redisRateLimit: true,
|
||||
patreon: {
|
||||
clientId: "",
|
||||
clientSecret: "",
|
||||
minPrice: 0,
|
||||
redirectUri: "https://sponsor.ajay.app/api/generateToken/patreon"
|
||||
},
|
||||
gumroad: {
|
||||
productPermalinks: ["sponsorblock"]
|
||||
},
|
||||
tokenSeed: "",
|
||||
minUserIDLength: 30,
|
||||
deArrowPaywall: false,
|
||||
useCacheForSegmentGroups: false,
|
||||
maxConnections: 100,
|
||||
maxResponseTime: 1000,
|
||||
maxResponseTimeWhileLoadingCache: 2000,
|
||||
etagExpiry: 5000,
|
||||
youTubeKeys: {
|
||||
visitorData: null,
|
||||
poToken: null,
|
||||
floatieUrl: null,
|
||||
floatieAuth: null
|
||||
}
|
||||
});
|
||||
loadFromEnv(config);
|
||||
@@ -169,15 +262,17 @@ function loadFromEnv(config: SBSConfig, prefix = "") {
|
||||
loadFromEnv(data, fullKey);
|
||||
} else if (process.env[fullKey]) {
|
||||
const value = process.env[fullKey];
|
||||
if (isNumber(value)) {
|
||||
config[key] = parseInt(value, 10);
|
||||
if (value !== "" && !isNaN(value as unknown as number)) {
|
||||
config[key] = parseFloat(value);
|
||||
} else if (value.toLowerCase() === "true" || value.toLowerCase() === "false") {
|
||||
config[key] = value === "true";
|
||||
} else if (key === "newLeafURLs") {
|
||||
config[key] = [value];
|
||||
} else if (key === "requestValidatorRules") {
|
||||
config[key] = JSON.parse(value) ?? [];
|
||||
} else {
|
||||
config[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { CronJob } from "cron";
|
||||
import { config as serverConfig } from "../config";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { db } from "../databases/databases";
|
||||
import { DBSegment } from "../types/segments.model";
|
||||
|
||||
const jobConfig = serverConfig?.crons?.downvoteSegmentArchive;
|
||||
|
||||
@@ -14,18 +13,18 @@ export const archiveDownvoteSegment = async (dayLimit: number, voteLimit: number
|
||||
Logger.info(`DownvoteSegmentArchiveJob starts at ${timeNow}`);
|
||||
try {
|
||||
// insert into archive sponsorTime
|
||||
await db.prepare(
|
||||
"run",
|
||||
`INSERT INTO "archivedSponsorTimes"
|
||||
SELECT *
|
||||
FROM "sponsorTimes"
|
||||
WHERE "votes" < ? AND (? - "timeSubmitted") > ?`,
|
||||
[
|
||||
voteLimit,
|
||||
timeNow,
|
||||
threshold
|
||||
]
|
||||
) as DBSegment[];
|
||||
await db.prepare(
|
||||
"run",
|
||||
`INSERT INTO "archivedSponsorTimes"
|
||||
SELECT *
|
||||
FROM "sponsorTimes"
|
||||
WHERE "votes" < ? AND (? - "timeSubmitted") > ?`,
|
||||
[
|
||||
voteLimit,
|
||||
timeNow,
|
||||
threshold
|
||||
]
|
||||
);
|
||||
|
||||
} catch (err) {
|
||||
Logger.error("Execption when insert segment in archivedSponsorTimes");
|
||||
@@ -35,15 +34,15 @@ export const archiveDownvoteSegment = async (dayLimit: number, voteLimit: number
|
||||
|
||||
// remove from sponsorTime
|
||||
try {
|
||||
await db.prepare(
|
||||
"run",
|
||||
'DELETE FROM "sponsorTimes" WHERE "votes" < ? AND (? - "timeSubmitted") > ?',
|
||||
[
|
||||
voteLimit,
|
||||
timeNow,
|
||||
threshold
|
||||
]
|
||||
) as DBSegment[];
|
||||
await db.prepare(
|
||||
"run",
|
||||
'DELETE FROM "sponsorTimes" WHERE "votes" < ? AND (? - "timeSubmitted") > ?',
|
||||
[
|
||||
voteLimit,
|
||||
timeNow,
|
||||
threshold
|
||||
]
|
||||
);
|
||||
|
||||
} catch (err) {
|
||||
Logger.error("Execption when deleting segment in sponsorTimes");
|
||||
@@ -57,7 +56,7 @@ export const archiveDownvoteSegment = async (dayLimit: number, voteLimit: number
|
||||
|
||||
const DownvoteSegmentArchiveJob = new CronJob(
|
||||
jobConfig?.schedule || "0 0 * * * 0",
|
||||
() => archiveDownvoteSegment(jobConfig?.timeThresholdInDays, jobConfig?.voteThreshold)
|
||||
() => void archiveDownvoteSegment(jobConfig?.timeThresholdInDays, jobConfig?.voteThreshold)
|
||||
);
|
||||
|
||||
if (serverConfig?.crons?.enabled && jobConfig && !jobConfig.schedule) {
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
export interface QueryOption {
|
||||
useReplica?: boolean;
|
||||
forceReplica?: boolean;
|
||||
}
|
||||
|
||||
export interface IDatabase {
|
||||
init(): Promise<void>;
|
||||
|
||||
prepare(type: QueryType, query: string, params?: any[]): Promise<any | any[] | void>;
|
||||
prepare(type: "run", query: string, params?: any[], options?: QueryOption): Promise<void>;
|
||||
prepare(type: "get", query: string, params?: any[], options?: QueryOption): Promise<any>;
|
||||
prepare(type: "all", query: string, params?: any[], options?: QueryOption): Promise<any[]>;
|
||||
prepare(type: QueryType, query: string, params?: any[], options?: QueryOption): Promise<any>;
|
||||
|
||||
highLoad(): boolean;
|
||||
|
||||
shouldUseRedisTimeout(): boolean;
|
||||
}
|
||||
|
||||
export type QueryType = "get" | "all" | "run";
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { Logger } from "../utils/logger";
|
||||
import { IDatabase, QueryType } from "./IDatabase";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import MysqlInterface from "sync-mysql";
|
||||
|
||||
export class Mysql implements IDatabase {
|
||||
private connection: any;
|
||||
|
||||
constructor(private config: unknown) {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line require-await
|
||||
async init(): Promise<void> {
|
||||
this.connection = new MysqlInterface(this.config);
|
||||
}
|
||||
|
||||
prepare(type: QueryType, query: string, params?: any[]): Promise<any[]> {
|
||||
Logger.debug(`prepare (mysql): type: ${type}, query: ${query}, params: ${params}`);
|
||||
const queryResult = this.connection.query(query, params);
|
||||
|
||||
switch (type) {
|
||||
case "get": {
|
||||
return queryResult[0];
|
||||
}
|
||||
case "all": {
|
||||
return queryResult;
|
||||
}
|
||||
case "run": {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Logger } from "../utils/logger";
|
||||
import { IDatabase, QueryType } from "./IDatabase";
|
||||
import { Client, Pool, PoolClient, types } from "pg";
|
||||
import { IDatabase, QueryOption, QueryType } from "./IDatabase";
|
||||
import { Client, Pool, QueryResult, types } from "pg";
|
||||
|
||||
import fs from "fs";
|
||||
import { CustomPostgresReadOnlyConfig, CustomWritePostgresConfig } from "../types/config.model";
|
||||
import { timeoutPomise, PromiseWithState, savePromiseState, nextFulfilment } from "../utils/promise";
|
||||
|
||||
// return numeric (pg_type oid=1700) as float
|
||||
types.setTypeParser(1700, function(val) {
|
||||
@@ -14,13 +16,77 @@ types.setTypeParser(20, function(val) {
|
||||
return parseInt(val, 10);
|
||||
});
|
||||
|
||||
interface PostgresStats {
|
||||
activeRequests: number;
|
||||
avgReadTime: number;
|
||||
avgWriteTime: number;
|
||||
avgFailedTime: number;
|
||||
pool: {
|
||||
total: number;
|
||||
idle: number;
|
||||
waiting: number;
|
||||
}
|
||||
}
|
||||
|
||||
export interface DatabaseConfig {
|
||||
dbSchemaFileName: string,
|
||||
dbSchemaFolder: string,
|
||||
fileNamePrefix: string,
|
||||
readOnly: boolean,
|
||||
createDbIfNotExists: boolean,
|
||||
postgres: CustomWritePostgresConfig,
|
||||
postgresReadOnly: CustomPostgresReadOnlyConfig
|
||||
}
|
||||
|
||||
export class Postgres implements IDatabase {
|
||||
private pool: Pool;
|
||||
private lastPoolFail = 0;
|
||||
|
||||
constructor(private config: Record<string, any>) {}
|
||||
private poolRead: Pool;
|
||||
private lastPoolReadFail = 0;
|
||||
|
||||
activePostgresRequests = 0;
|
||||
readResponseTime: number[] = [];
|
||||
writeResponseTime: number[] = [];
|
||||
failedResponseTime: number[] = [];
|
||||
maxStoredTimes = 200;
|
||||
|
||||
constructor(private config: DatabaseConfig) {}
|
||||
|
||||
async init(): Promise<void> {
|
||||
this.pool = new Pool(this.config.postgres);
|
||||
this.pool = new Pool({
|
||||
...this.config.postgres
|
||||
});
|
||||
this.pool.on("error", (err, client) => {
|
||||
Logger.error(err.stack);
|
||||
this.lastPoolFail = Date.now();
|
||||
|
||||
try {
|
||||
client.release(true);
|
||||
} catch (err) {
|
||||
Logger.error(`pool (postgres): ${err}`);
|
||||
}
|
||||
});
|
||||
|
||||
if (this.config.postgresReadOnly && this.config.postgresReadOnly.enabled) {
|
||||
try {
|
||||
this.poolRead = new Pool({
|
||||
...this.config.postgresReadOnly
|
||||
});
|
||||
this.poolRead.on("error", (err, client) => {
|
||||
Logger.error(err.stack);
|
||||
this.lastPoolReadFail = Date.now();
|
||||
|
||||
try {
|
||||
client.release(true);
|
||||
} catch (err) {
|
||||
Logger.error(`poolRead (postgres): ${err}`);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
Logger.error(`poolRead (postgres): ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.config.readOnly) {
|
||||
if (this.config.createDbIfNotExists) {
|
||||
@@ -43,7 +109,7 @@ export class Postgres implements IDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
async prepare(type: QueryType, query: string, params?: any[]): Promise<any[]> {
|
||||
async prepare(type: QueryType, query: string, params?: any[], options: QueryOption = {}): Promise<any> {
|
||||
// Convert query to use numbered parameters
|
||||
let count = 1;
|
||||
for (let char = 0; char < query.length; char++) {
|
||||
@@ -55,31 +121,86 @@ export class Postgres implements IDatabase {
|
||||
|
||||
Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`);
|
||||
|
||||
let client: PoolClient;
|
||||
try {
|
||||
client = await this.pool.connect();
|
||||
const queryResult = await client.query({ text: query, values: params });
|
||||
|
||||
switch (type) {
|
||||
case "get": {
|
||||
const value = queryResult.rows[0];
|
||||
Logger.debug(`result (postgres): ${JSON.stringify(value)}`);
|
||||
return value;
|
||||
}
|
||||
case "all": {
|
||||
const values = queryResult.rows;
|
||||
Logger.debug(`result (postgres): ${JSON.stringify(values)}`);
|
||||
return values;
|
||||
}
|
||||
case "run": {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
Logger.error(`prepare (postgres): ${err}`);
|
||||
} finally {
|
||||
client?.release();
|
||||
if (this.config.postgres.maxActiveRequests && this.isReadQuery(type)
|
||||
&& this.activePostgresRequests > this.config.postgres.maxActiveRequests) {
|
||||
throw new Error("Too many active postgres requests");
|
||||
}
|
||||
|
||||
const start = Date.now();
|
||||
const pendingQueries: PromiseWithState<QueryResult<any>>[] = [];
|
||||
let tries = 0;
|
||||
let lastPool: Pool = null;
|
||||
const maxTries = () => (lastPool === this.pool
|
||||
? this.config.postgres.maxTries : this.config.postgresReadOnly.maxTries);
|
||||
do {
|
||||
tries++;
|
||||
|
||||
try {
|
||||
this.activePostgresRequests++;
|
||||
lastPool = this.getPool(type, options);
|
||||
|
||||
pendingQueries.push(savePromiseState(lastPool.query({ text: query, values: params })));
|
||||
const currentPromises = [...pendingQueries];
|
||||
if (options.useReplica && maxTries() - tries > 1) currentPromises.push(savePromiseState(timeoutPomise(this.config.postgresReadOnly.readTimeout)));
|
||||
else if (this.config.postgres.timeout) currentPromises.push(savePromiseState(timeoutPomise(this.config.postgres.timeout)));
|
||||
const queryResult = await nextFulfilment(currentPromises);
|
||||
|
||||
this.updateResponseTime(type, start);
|
||||
|
||||
this.activePostgresRequests--;
|
||||
switch (type) {
|
||||
case "get": {
|
||||
const value = queryResult.rows[0];
|
||||
Logger.debug(`result (postgres): ${JSON.stringify(value)}`);
|
||||
return value;
|
||||
}
|
||||
case "all": {
|
||||
const values = queryResult.rows;
|
||||
Logger.debug(`result (postgres): ${JSON.stringify(values)}`);
|
||||
return values;
|
||||
}
|
||||
case "run": {
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (lastPool === this.pool) {
|
||||
// Only applies if it is get or all request
|
||||
options.forceReplica = true;
|
||||
} else if (lastPool === this.poolRead) {
|
||||
this.lastPoolReadFail = Date.now();
|
||||
|
||||
if (maxTries() - tries <= 1) {
|
||||
options.useReplica = false;
|
||||
}
|
||||
}
|
||||
|
||||
this.updateResponseTime(type, start, this.failedResponseTime);
|
||||
this.activePostgresRequests--;
|
||||
Logger.error(`prepare (postgres) try ${tries}: ${err}`);
|
||||
}
|
||||
} while (this.isReadQuery(type) && tries < maxTries()
|
||||
&& this.activePostgresRequests < this.config.postgresReadOnly.stopRetryThreshold);
|
||||
|
||||
throw new Error(`prepare (postgres): ${type} ${query} failed after ${tries} tries`);
|
||||
}
|
||||
|
||||
private getPool(type: string, options: QueryOption): Pool {
|
||||
const readAvailable = this.poolRead && options.useReplica && this.isReadQuery(type);
|
||||
const ignoreReadDueToFailure = this.config.postgresReadOnly.fallbackOnFail
|
||||
&& this.lastPoolReadFail > Date.now() - 1000 * 30;
|
||||
const readDueToFailure = this.config.postgresReadOnly.fallbackOnFail
|
||||
&& this.lastPoolFail > Date.now() - 1000 * 30;
|
||||
if (readAvailable && !ignoreReadDueToFailure && (options.forceReplica || readDueToFailure ||
|
||||
Math.random() > 1 / (this.config.postgresReadOnly.weight + 1))) {
|
||||
return this.poolRead;
|
||||
} else {
|
||||
return this.pool;
|
||||
}
|
||||
}
|
||||
|
||||
private isReadQuery(type: string): boolean {
|
||||
return type === "get" || type === "all";
|
||||
}
|
||||
|
||||
private async createDB() {
|
||||
@@ -98,7 +219,7 @@ export class Postgres implements IDatabase {
|
||||
);
|
||||
}
|
||||
|
||||
client.end();
|
||||
client.end().catch(err => Logger.error(`closing db (postgres): ${err}`));
|
||||
}
|
||||
|
||||
private async upgradeDB(fileNamePrefix: string, schemaFolder: string) {
|
||||
@@ -134,4 +255,36 @@ export class Postgres implements IDatabase {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private updateResponseTime(type: string, start: number, customArray?: number[]): void {
|
||||
const responseTime = Date.now() - start;
|
||||
|
||||
const array = customArray ?? (this.isReadQuery(type) ?
|
||||
this.readResponseTime : this.writeResponseTime);
|
||||
|
||||
array.push(responseTime);
|
||||
if (array.length > this.maxStoredTimes) array.shift();
|
||||
}
|
||||
|
||||
getStats(): PostgresStats {
|
||||
return {
|
||||
activeRequests: this.activePostgresRequests,
|
||||
avgReadTime: this.readResponseTime.length > 0 ? this.readResponseTime.reduce((a, b) => a + b, 0) / this.readResponseTime.length : 0,
|
||||
avgWriteTime: this.writeResponseTime.length > 0 ? this.writeResponseTime.reduce((a, b) => a + b, 0) / this.writeResponseTime.length : 0,
|
||||
avgFailedTime: this.failedResponseTime.length > 0 ? this.failedResponseTime.reduce((a, b) => a + b, 0) / this.failedResponseTime.length : 0,
|
||||
pool: {
|
||||
total: this.pool.totalCount,
|
||||
idle: this.pool.idleCount,
|
||||
waiting: this.pool.waitingCount
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
highLoad() {
|
||||
return this.activePostgresRequests > this.config.postgres.highLoadThreshold;
|
||||
}
|
||||
|
||||
shouldUseRedisTimeout() {
|
||||
return this.activePostgresRequests < this.config.postgres.redisTimeoutThreshold;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export class Sqlite implements IDatabase {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line require-await
|
||||
async prepare(type: QueryType, query: string, params: any[] = []): Promise<any[]> {
|
||||
async prepare(type: QueryType, query: string, params: any[] = []): Promise<any> {
|
||||
// Logger.debug(`prepare (sqlite): type: ${type}, query: ${query}, params: ${params}`);
|
||||
const preparedQuery = this.db.prepare(Sqlite.processQuery(query));
|
||||
|
||||
@@ -72,6 +72,15 @@ export class Sqlite implements IDatabase {
|
||||
}
|
||||
|
||||
private static processQuery(query: string): string {
|
||||
if (query.includes("DISTINCT ON")) {
|
||||
const column = query.match(/DISTINCT ON \((.*)\) (.*)/)[1];
|
||||
query = query.replace(/DISTINCT ON \((.*)\)/g, "");
|
||||
|
||||
const parts = query.split("ORDER BY");
|
||||
|
||||
query = `${parts[0]} GROUP BY ${column} ORDER BY ${parts[1]}`;
|
||||
}
|
||||
|
||||
return query.replace(/ ~\* /g, " REGEXP ");
|
||||
}
|
||||
|
||||
@@ -93,7 +102,17 @@ export class Sqlite implements IDatabase {
|
||||
}
|
||||
|
||||
private static processUpgradeQuery(query: string): string {
|
||||
return query.replace(/^.*--!sqlite-ignore/gm, "");
|
||||
return query
|
||||
.replace(/SERIAL PRIMARY KEY/gi, "INTEGER PRIMARY KEY AUTOINCREMENT")
|
||||
.replace(/^.*--!sqlite-ignore/gm, "");
|
||||
}
|
||||
|
||||
highLoad() {
|
||||
return false;
|
||||
}
|
||||
|
||||
shouldUseRedisTimeout() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import { config } from "../config";
|
||||
import { Sqlite } from "./Sqlite";
|
||||
import { Mysql } from "./Mysql";
|
||||
import { Postgres } from "./Postgres";
|
||||
import { IDatabase } from "./IDatabase";
|
||||
|
||||
let db: IDatabase;
|
||||
let privateDB: IDatabase;
|
||||
if (config.mysql) {
|
||||
db = new Mysql(config.mysql);
|
||||
privateDB = new Mysql(config.privateMysql);
|
||||
} else if (config.postgres?.enabled) {
|
||||
if (config.postgres?.enabled) {
|
||||
db = new Postgres({
|
||||
dbSchemaFileName: config.dbSchema,
|
||||
dbSchemaFolder: config.schemaFolder,
|
||||
@@ -17,12 +13,13 @@ if (config.mysql) {
|
||||
readOnly: config.readOnly,
|
||||
createDbIfNotExists: config.createDatabaseIfNotExist,
|
||||
postgres: {
|
||||
user: config.postgres?.user,
|
||||
host: config.postgres?.host,
|
||||
...config.postgres,
|
||||
database: "sponsorTimes",
|
||||
password: config.postgres?.password,
|
||||
port: config.postgres?.port,
|
||||
}
|
||||
},
|
||||
postgresReadOnly: config.postgresReadOnly ? {
|
||||
...config.postgresReadOnly,
|
||||
database: "sponsorTimes"
|
||||
} : null
|
||||
});
|
||||
|
||||
privateDB = new Postgres({
|
||||
@@ -32,12 +29,14 @@ if (config.mysql) {
|
||||
readOnly: config.readOnly,
|
||||
createDbIfNotExists: config.createDatabaseIfNotExist,
|
||||
postgres: {
|
||||
user: config.postgres?.user,
|
||||
host: config.postgres?.host,
|
||||
database: "privateDB",
|
||||
password: config.postgres?.password,
|
||||
port: config.postgres?.port,
|
||||
}
|
||||
...config.postgres,
|
||||
max: config.postgresPrivateMax ?? config.postgres.max,
|
||||
database: "privateDB"
|
||||
},
|
||||
postgresReadOnly: config.postgresReadOnly ? {
|
||||
...config.postgresReadOnly,
|
||||
database: "privateDB"
|
||||
} : null
|
||||
});
|
||||
} else {
|
||||
db = new Sqlite({
|
||||
|
||||
18
src/index.ts
18
src/index.ts
@@ -4,15 +4,27 @@ import { createServer } from "./app";
|
||||
import { Logger } from "./utils/logger";
|
||||
import { startAllCrons } from "./cronjob";
|
||||
import { getCommit } from "./utils/getCommit";
|
||||
import { connectionPromise } from "./utils/redis";
|
||||
|
||||
async function init() {
|
||||
process.on("unhandledRejection", (error: any) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.dir(error?.stack);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
await initDb();
|
||||
process.on("uncaughtExceptions", (error: any) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.dir(error?.stack);
|
||||
});
|
||||
|
||||
try {
|
||||
await initDb();
|
||||
await connectionPromise;
|
||||
} catch (e) {
|
||||
Logger.error(`Init Db: ${e}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// edge case clause for creating compatible .db files, do not enable
|
||||
if (config.mode === "init-db-and-exit") process.exit(0);
|
||||
// do not enable init-db-only mode for usage.
|
||||
@@ -27,4 +39,4 @@ async function init() {
|
||||
}).setTimeout(15000);
|
||||
}
|
||||
|
||||
init();
|
||||
init().catch((err) => Logger.error(`Index.js: ${err}`));
|
||||
@@ -3,6 +3,6 @@ import { NextFunction, Request, Response } from "express";
|
||||
export function corsMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||
res.header("Access-Control-Allow-Origin", "*");
|
||||
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
|
||||
res.header("Access-Control-Allow-Headers", "Content-Type");
|
||||
res.header("Access-Control-Allow-Headers", "Content-Type, If-None-Match, x-client-name");
|
||||
next();
|
||||
}
|
||||
|
||||
53
src/middleware/etag.ts
Normal file
53
src/middleware/etag.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { VideoID, VideoIDHash, Service } from "../types/segments.model";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import { brandingHashKey, brandingKey, skipSegmentsHashKey, skipSegmentsKey, skipSegmentsLargerHashKey, videoLabelsHashKey, videoLabelsKey, videoLabelsLargerHashKey } from "../utils/redisKeys";
|
||||
|
||||
type hashType = "skipSegments" | "skipSegmentsHash" | "skipSegmentsLargerHash" | "videoLabel" | "videoLabelHash" | "videoLabelsLargerHash" | "branding" | "brandingHash";
|
||||
type ETag = `"${hashType};${VideoIDHash};${Service};${number}"`;
|
||||
type hashKey = string | VideoID | VideoIDHash;
|
||||
|
||||
export function cacheMiddlware(req: Request, res: Response, next: NextFunction): void {
|
||||
const reqEtag = req.get("If-None-Match") as string;
|
||||
// if weak etag, do not handle
|
||||
if (!reqEtag || reqEtag.startsWith("W/")) return next();
|
||||
// split into components
|
||||
const [hashType, hashKey, service, lastModified] = reqEtag.replace(/^"|"$/g, "").split(";");
|
||||
// fetch last-modified
|
||||
getLastModified(hashType as hashType, hashKey as VideoIDHash, service as Service)
|
||||
.then(redisLastModified => {
|
||||
if (redisLastModified <= new Date(Number(lastModified) + 1000)) {
|
||||
// match cache, generate etag
|
||||
const etag = `"${hashType};${hashKey};${service};${redisLastModified.getTime()}"` as ETag;
|
||||
res.status(304).set("etag", etag).send();
|
||||
}
|
||||
else next();
|
||||
})
|
||||
.catch(next);
|
||||
}
|
||||
|
||||
function getLastModified(hashType: hashType, hashKey: hashKey, service: Service): Promise<Date | null> {
|
||||
let redisKey: string | null;
|
||||
if (hashType === "skipSegments") redisKey = skipSegmentsKey(hashKey as VideoID, service);
|
||||
else if (hashType === "skipSegmentsHash") redisKey = skipSegmentsHashKey(hashKey as VideoIDHash, service);
|
||||
else if (hashType === "skipSegmentsLargerHash") redisKey = skipSegmentsLargerHashKey(hashKey as VideoIDHash, service);
|
||||
else if (hashType === "videoLabel") redisKey = videoLabelsKey(hashKey as VideoID, service);
|
||||
else if (hashType === "videoLabelHash") redisKey = videoLabelsHashKey(hashKey as VideoIDHash, service);
|
||||
else if (hashType === "videoLabelsLargerHash") redisKey = videoLabelsLargerHashKey(hashKey as VideoIDHash, service);
|
||||
else if (hashType === "branding") redisKey = brandingKey(hashKey as VideoID, service);
|
||||
else if (hashType === "brandingHash") redisKey = brandingHashKey(hashKey as VideoIDHash, service);
|
||||
else return Promise.reject();
|
||||
return QueryCacher.getKeyLastModified(redisKey);
|
||||
}
|
||||
|
||||
export async function getEtag(hashType: hashType, hashKey: hashKey, service: Service): Promise<ETag> {
|
||||
const lastModified = await getLastModified(hashType, hashKey, service);
|
||||
return `"${hashType};${hashKey};${service};${lastModified.getTime()}"` as ETag;
|
||||
}
|
||||
|
||||
/* example usage
|
||||
import { getEtag } from "../middleware/etag";
|
||||
await getEtag(hashType, hashPrefix, service)
|
||||
.then(etag => res.set("ETag", etag))
|
||||
.catch(() => null);
|
||||
*/
|
||||
7
src/middleware/hostHeader.ts
Normal file
7
src/middleware/hostHeader.ts
Normal 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();
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +2,20 @@ import axios from "axios";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { config } from "../config";
|
||||
import { getIP } from "../utils/getIP";
|
||||
import { getHash } from "../utils/getHash";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { Agent } from "http";
|
||||
|
||||
const httpAgent = new Agent({ keepAlive: true });
|
||||
|
||||
export function userCounter(req: Request, res: Response, next: NextFunction): void {
|
||||
if (req.method !== "OPTIONS") {
|
||||
axios.post(`${config.userCounterURL}/api/v1/addIP?hashedIP=${getHash(getIP(req), 1)}`)
|
||||
.catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
|
||||
if (Math.random() < 1 / config.userCounterRatio) {
|
||||
axios({
|
||||
method: "post",
|
||||
url: `${config.userCounterURL}/api/v1/addIP?hashedIP=${getIP(req)}`,
|
||||
httpAgent
|
||||
}).catch(() => /* instanbul skip next */ Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
|
||||
81
src/routes/addFeature.ts
Normal file
81
src/routes/addFeature.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
import { db } from "../databases/databases";
|
||||
import { config } from "../config";
|
||||
import { Request, Response } from "express";
|
||||
import { isUserVIP } from "../utils/isUserVIP";
|
||||
import { Feature, HashedUserID, UserID } from "../types/user.model";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import { getVerificationValue, verifyOldSubmissions } from "./postBranding";
|
||||
|
||||
interface AddFeatureRequest extends Request {
|
||||
body: {
|
||||
userID: HashedUserID;
|
||||
adminUserID: string;
|
||||
feature: string;
|
||||
enabled: string;
|
||||
}
|
||||
}
|
||||
|
||||
const allowedFeatures = {
|
||||
vip: [
|
||||
Feature.ChapterSubmitter,
|
||||
Feature.FillerSubmitter,
|
||||
Feature.DeArrowTitleSubmitter,
|
||||
],
|
||||
admin: [
|
||||
Feature.ChapterSubmitter,
|
||||
Feature.FillerSubmitter,
|
||||
Feature.DeArrowTitleSubmitter,
|
||||
]
|
||||
};
|
||||
|
||||
export async function addFeature(req: AddFeatureRequest, res: Response): Promise<Response> {
|
||||
const { body: { userID, adminUserID } } = req;
|
||||
const feature = parseInt(req.body.feature) as Feature;
|
||||
const enabled = req.body?.enabled !== "false";
|
||||
|
||||
if (!userID || !adminUserID) {
|
||||
// invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
// hash the userID
|
||||
const adminUserIDInput = await getHashCache(adminUserID as UserID);
|
||||
const isAdmin = adminUserIDInput === config.adminUserID;
|
||||
const isVIP = (await isUserVIP(adminUserIDInput)) || isAdmin;
|
||||
|
||||
if (!isVIP) {
|
||||
// not authorized
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
|
||||
try {
|
||||
const currentAllowedFeatures = isAdmin ? allowedFeatures.admin : allowedFeatures.vip;
|
||||
if (currentAllowedFeatures.includes(feature)) {
|
||||
if (enabled) {
|
||||
const featureAdded = await db.prepare("get", 'SELECT "feature" from "userFeatures" WHERE "userID" = ? AND "feature" = ?', [userID, feature]);
|
||||
if (!featureAdded) {
|
||||
await db.prepare("run", 'INSERT INTO "userFeatures" ("userID", "feature", "issuerUserID", "timeSubmitted") VALUES(?, ?, ?, ?)'
|
||||
, [userID, feature, adminUserID, Date.now()]);
|
||||
}
|
||||
|
||||
if (feature === Feature.DeArrowTitleSubmitter) {
|
||||
await verifyOldSubmissions(userID, await getVerificationValue(userID, false));
|
||||
}
|
||||
} else {
|
||||
await db.prepare("run", 'DELETE FROM "userFeatures" WHERE "userID" = ? AND "feature" = ?', [userID, feature]);
|
||||
}
|
||||
|
||||
QueryCacher.clearFeatureCache(userID, feature);
|
||||
} else {
|
||||
return res.status(400).send("Invalid feature");
|
||||
}
|
||||
|
||||
return res.sendStatus(200);
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { config } from "../config";
|
||||
import { Request, Response } from "express";
|
||||
import { isUserVIP } from "../utils/isUserVIP";
|
||||
import { HashedUserID } from "../types/user.model";
|
||||
import { Logger } from "../utils/logger";
|
||||
|
||||
interface AddUserAsVIPRequest extends Request {
|
||||
query: {
|
||||
@@ -34,15 +35,21 @@ export async function addUserAsVIP(req: AddUserAsVIPRequest, res: Response): Pro
|
||||
// check to see if this user is already a vip
|
||||
const userIsVIP = await isUserVIP(userID);
|
||||
|
||||
if (enabled && !userIsVIP) {
|
||||
// add them to the vip list
|
||||
await db.prepare("run", 'INSERT INTO "vipUsers" VALUES(?)', [userID]);
|
||||
try {
|
||||
if (enabled && !userIsVIP) {
|
||||
// add them to the vip list
|
||||
await db.prepare("run", 'INSERT INTO "vipUsers" VALUES(?)', [userID]);
|
||||
}
|
||||
|
||||
if (!enabled && userIsVIP) {
|
||||
//remove them from the shadow ban list
|
||||
await db.prepare("run", 'DELETE FROM "vipUsers" WHERE "userID" = ?', [userID]);
|
||||
}
|
||||
|
||||
return res.sendStatus(200);
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
if (!enabled && userIsVIP) {
|
||||
//remove them from the shadow ban list
|
||||
await db.prepare("run", 'DELETE FROM "vipUsers" WHERE "userID" = ?', [userID]);
|
||||
}
|
||||
|
||||
return res.sendStatus(200);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ActionType, Category, Service, VideoID } from "../types/segments.model"
|
||||
import { UserID } from "../types/user.model";
|
||||
import { getService } from "../utils/getService";
|
||||
import { config } from "../config";
|
||||
import { Logger } from "../utils/logger";
|
||||
|
||||
interface DeleteLockCategoriesRequest extends Request {
|
||||
body: {
|
||||
@@ -35,6 +36,7 @@ export async function deleteLockCategoriesEndpoint(req: DeleteLockCategoriesRequ
|
||||
|| !categories
|
||||
|| !Array.isArray(categories)
|
||||
|| categories.length === 0
|
||||
|| actionTypes && !Array.isArray(actionTypes)
|
||||
|| actionTypes.length === 0
|
||||
) {
|
||||
return res.status(400).json({
|
||||
@@ -48,11 +50,16 @@ export async function deleteLockCategoriesEndpoint(req: DeleteLockCategoriesRequ
|
||||
|
||||
if (!userIsVIP) {
|
||||
return res.status(403).json({
|
||||
message: "Must be a VIP to mark videos.",
|
||||
message: "Must be a VIP to lock videos.",
|
||||
});
|
||||
}
|
||||
|
||||
await deleteLockCategories(videoID, categories, actionTypes, getService(service));
|
||||
try {
|
||||
await deleteLockCategories(videoID, categories, actionTypes, getService(service));
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
return res.status(500);
|
||||
}
|
||||
|
||||
return res.status(200).json({ message: `Removed lock categories entries for video ${videoID}` });
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { config } from "../config";
|
||||
import util from "util";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { ChildProcess, exec, ExecOptions, spawn } from "child_process";
|
||||
import { exec, ExecOptions } from "child_process";
|
||||
const unlink = util.promisify(fs.unlink);
|
||||
|
||||
const ONE_MINUTE = 1000 * 60;
|
||||
@@ -44,7 +44,7 @@ const credentials: ExecOptions = {
|
||||
PGPASSWORD: String(config.postgres.password),
|
||||
PGDATABASE: "sponsorTimes",
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
interface TableDumpList {
|
||||
fileName: string;
|
||||
@@ -75,6 +75,7 @@ function removeOutdatedDumps(exportPath: string): Promise<void> {
|
||||
}, {});
|
||||
|
||||
// read files in export directory
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
fs.readdir(exportPath, async (err: any, files: string[]) => {
|
||||
if (err) Logger.error(err);
|
||||
if (err) return resolve();
|
||||
@@ -95,10 +96,12 @@ function removeOutdatedDumps(exportPath: string): Promise<void> {
|
||||
for (const tableName in tableFiles) {
|
||||
const files = tableFiles[tableName].sort((a, b) => b.timestamp - a.timestamp);
|
||||
for (let i = 2; i < files.length; i++) {
|
||||
// remove old file
|
||||
await unlink(files[i].file).catch((error: any) => {
|
||||
Logger.error(`[dumpDatabase] Garbage collection failed ${error}`);
|
||||
});
|
||||
if (!latestDumpFiles.some((file) => file.fileName === files[i].file.match(/[^/]+$/)[0])) {
|
||||
// remove old file
|
||||
await unlink(files[i].file).catch((error: any) => {
|
||||
Logger.error(`[dumpDatabase] Garbage collection failed ${error}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
resolve();
|
||||
@@ -123,7 +126,7 @@ export default async function dumpDatabase(req: Request, res: Response, showPage
|
||||
if (showPage) {
|
||||
res.send(`${styleHeader}
|
||||
<h1>SponsorBlock database dumps</h1>${licenseHeader}
|
||||
<h3>How this works</h3>
|
||||
<s><h3>How this works</h3>
|
||||
|
||||
Send a request to <code>https://sponsor.ajay.app/database.json</code>, or visit this page to get a list of urls and the update status database dump to run.
|
||||
Then, you can download the csv files below, or use the links returned from the JSON request.
|
||||
@@ -134,6 +137,11 @@ export default async function dumpDatabase(req: Request, res: Response, showPage
|
||||
If you want a live dump, please do not continually fetch this url.
|
||||
Please instead use the <a href="https://github.com/mchangrh/sb-mirror">sb-mirror</a> project.
|
||||
This can automatically fetch new data and will not require a redownload each time, saving bandwidth.
|
||||
</s>
|
||||
|
||||
<h3>Please use sb-mirror</h3>
|
||||
|
||||
For bandwidth reasons, CSV downloads have been disabled. Please use the <a href="https://github.com/mchangrh/sb-mirror">sb-mirror</a> project.
|
||||
|
||||
<h3>Links</h3>
|
||||
<table>
|
||||
@@ -158,18 +166,23 @@ export default async function dumpDatabase(req: Request, res: Response, showPage
|
||||
<hr/>
|
||||
${updateQueued ? `Update queued.` : ``} Last updated: ${lastUpdate ? new Date(lastUpdate).toUTCString() : `Unknown`}`);
|
||||
} else {
|
||||
res.send({
|
||||
dbVersion: await getDbVersion(),
|
||||
lastUpdated: lastUpdate,
|
||||
updateQueued,
|
||||
links: latestDumpFiles.map((item:any) => {
|
||||
return {
|
||||
table: item.tableName,
|
||||
url: `/database/${item.tableName}.csv`,
|
||||
size: item.fileSize,
|
||||
};
|
||||
}),
|
||||
});
|
||||
try {
|
||||
res.send({
|
||||
dbVersion: await getDbVersion(),
|
||||
lastUpdated: lastUpdate,
|
||||
updateQueued,
|
||||
links: latestDumpFiles.map((item:any) => {
|
||||
return {
|
||||
table: item.tableName,
|
||||
url: `/database/${item.tableName}.csv`,
|
||||
size: item.fileSize,
|
||||
};
|
||||
}),
|
||||
});
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
|
||||
await queueDump();
|
||||
@@ -223,16 +236,16 @@ async function queueDump(): Promise<void> {
|
||||
const fileName = `${table.name}_${startTime}.csv`;
|
||||
const file = `${appExportPath}/${fileName}`;
|
||||
|
||||
await new Promise<string>((resolve) => {
|
||||
await new Promise<string>((resolve, reject) => {
|
||||
exec(`psql -c "\\copy (SELECT * FROM \\"${table.name}\\"${table.order ? ` ORDER BY \\"${table.order}\\"` : ``})`
|
||||
+ ` TO '${file}' WITH (FORMAT CSV, HEADER true);"`, credentials, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
Logger.error(`[dumpDatabase] Failed to dump ${table.name} to ${file} due to ${stderr}`);
|
||||
reject(`[dumpDatabase] Failed to dump ${table.name} to ${file} due to ${stderr}`);
|
||||
}
|
||||
|
||||
resolve(error ? stderr : stdout);
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
dumpFiles.push({
|
||||
fileName,
|
||||
@@ -242,10 +255,10 @@ async function queueDump(): Promise<void> {
|
||||
latestDumpFiles = [...dumpFiles];
|
||||
|
||||
lastUpdate = startTime;
|
||||
updateQueued = false;
|
||||
} catch(e) {
|
||||
Logger.error(e as string);
|
||||
} finally {
|
||||
updateQueued = false;
|
||||
updateRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
68
src/routes/generateToken.ts
Normal file
68
src/routes/generateToken.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { Request, Response } from "express";
|
||||
import { config } from "../config";
|
||||
import { createAndSaveToken, TokenType } from "../utils/tokenUtils";
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
|
||||
interface GenerateTokenRequest extends Request {
|
||||
query: {
|
||||
code: string;
|
||||
adminUserID?: string;
|
||||
total?: string;
|
||||
key?: string;
|
||||
},
|
||||
params: {
|
||||
type: TokenType;
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateTokenRequest(req: GenerateTokenRequest, res: Response): Promise<Response> {
|
||||
const { query: { code, adminUserID, total, key }, params: { type } } = req;
|
||||
const adminUserIDHash = adminUserID ? (await getHashCache(adminUserID)) : null;
|
||||
|
||||
if (!type || (!code && type === TokenType.patreon)) {
|
||||
return res.status(400).send("Invalid request");
|
||||
}
|
||||
|
||||
if (type === TokenType.free && (!key || Math.abs(Date.now() - parseInt(key)) > 1000 * 60 * 60 * 24)) {
|
||||
return res.status(400).send("Invalid request");
|
||||
}
|
||||
|
||||
if (type === TokenType.patreon
|
||||
|| ([TokenType.local, TokenType.gift].includes(type) && adminUserIDHash === config.adminUserID)
|
||||
|| type === TokenType.free) {
|
||||
const licenseKeys = await createAndSaveToken(type, code, adminUserIDHash === config.adminUserID ? parseInt(total) : 1);
|
||||
|
||||
/* istanbul ignore else */
|
||||
if (licenseKeys) {
|
||||
if (type === TokenType.patreon) {
|
||||
return res.status(200).send(`
|
||||
<h1>
|
||||
Your license key:
|
||||
</h1>
|
||||
<p>
|
||||
<b>
|
||||
${licenseKeys[0]}
|
||||
</b>
|
||||
</p>
|
||||
<p>
|
||||
Copy this into the textbox in the other tab
|
||||
</p>
|
||||
`);
|
||||
} else if (type === TokenType.free) {
|
||||
return res.status(200).send({
|
||||
licenseKey: licenseKeys[0]
|
||||
});
|
||||
} else {
|
||||
return res.status(200).send(licenseKeys.join("<br/>"));
|
||||
}
|
||||
} else {
|
||||
return res.status(401).send(`
|
||||
<h1>
|
||||
Failed to generate an license key
|
||||
</h1>
|
||||
`);
|
||||
}
|
||||
} else {
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
}
|
||||
377
src/routes/getBranding.ts
Normal file
377
src/routes/getBranding.ts
Normal file
@@ -0,0 +1,377 @@
|
||||
import { Request, Response } from "express";
|
||||
import { isEmpty } from "lodash";
|
||||
import { config } from "../config";
|
||||
import { db, privateDB } from "../databases/databases";
|
||||
import { Postgres } from "../databases/Postgres";
|
||||
import { BrandingDBSubmission, BrandingDBSubmissionData, BrandingHashDBResult, BrandingResult, BrandingSegmentDBResult, BrandingSegmentHashDBResult, CasualVoteDBResult, CasualVoteHashDBResult, ThumbnailDBResult, ThumbnailResult, TitleDBResult, TitleResult } from "../types/branding.model";
|
||||
import { HashedIP, IPAddress, Service, VideoID, VideoIDHash, Visibility } from "../types/segments.model";
|
||||
import { shuffleArray } from "../utils/array";
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
import { getIP } from "../utils/getIP";
|
||||
import { getService } from "../utils/getService";
|
||||
import { hashPrefixTester } from "../utils/hashPrefixTester";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { promiseOrTimeout } from "../utils/promise";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import { brandingHashKey, brandingIPKey, brandingKey } from "../utils/redisKeys";
|
||||
import * as SeedRandom from "seedrandom";
|
||||
import { getEtag } from "../middleware/etag";
|
||||
|
||||
enum BrandingSubmissionType {
|
||||
Title = "title",
|
||||
Thumbnail = "thumbnail"
|
||||
}
|
||||
|
||||
export async function getVideoBranding(res: Response, videoID: VideoID, service: Service, ip: IPAddress, returnUserID: boolean, fetchAll: boolean): Promise<BrandingResult> {
|
||||
const getTitles = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "titles"."title", "titles"."original", "titleVotes"."votes", "titleVotes"."downvotes", "titleVotes"."locked", "titleVotes"."shadowHidden", "titles"."UUID", "titles"."videoID", "titles"."hashedVideoID", "titleVotes"."verification", "titles"."userID"
|
||||
FROM "titles" JOIN "titleVotes" ON "titles"."UUID" = "titleVotes"."UUID"
|
||||
WHERE "titles"."videoID" = ? AND "titles"."service" = ? AND "titleVotes"."votes" > -1 AND "titleVotes"."votes" - "titleVotes"."downvotes" > -2 AND "titleVotes"."removed" = 0`,
|
||||
[videoID, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<TitleDBResult[]>;
|
||||
|
||||
const getThumbnails = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "thumbnailTimestamps"."timestamp", "thumbnails"."original", "thumbnailVotes"."votes", "thumbnailVotes"."downvotes", "thumbnailVotes"."locked", "thumbnailVotes"."shadowHidden", "thumbnails"."UUID", "thumbnails"."videoID", "thumbnails"."hashedVideoID", "thumbnails"."userID"
|
||||
FROM "thumbnails" LEFT JOIN "thumbnailVotes" ON "thumbnails"."UUID" = "thumbnailVotes"."UUID" LEFT JOIN "thumbnailTimestamps" ON "thumbnails"."UUID" = "thumbnailTimestamps"."UUID"
|
||||
WHERE "thumbnails"."videoID" = ? AND "thumbnails"."service" = ? AND "thumbnailVotes"."votes" - "thumbnailVotes"."downvotes" > -2 AND "thumbnailVotes"."removed" = 0
|
||||
ORDER BY "thumbnails"."timeSubmitted" ASC`,
|
||||
[videoID, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<ThumbnailDBResult[]>;
|
||||
|
||||
const getSegments = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "startTime", "endTime", "category", "videoDuration" FROM "sponsorTimes"
|
||||
WHERE "votes" > -2 AND "shadowHidden" = 0 AND "hidden" = 0 AND "actionType" = 'skip' AND "videoID" = ? AND "service" = ?
|
||||
ORDER BY "timeSubmitted" ASC`,
|
||||
[videoID, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<BrandingSegmentDBResult[]>;
|
||||
|
||||
const getCasualVotes = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "casualVotes"."category", "casualVotes"."upvotes", "casualVoteTitles"."title"
|
||||
FROM "casualVotes" LEFT JOIN "casualVoteTitles" ON "casualVotes"."videoID" = "casualVoteTitles"."videoID" AND "casualVotes"."service" = "casualVoteTitles"."service" AND "casualVotes"."titleID" = "casualVoteTitles"."id"
|
||||
WHERE "casualVotes"."videoID" = ? AND "casualVotes"."service" = ?
|
||||
ORDER BY "casualVotes"."timeSubmitted" ASC`,
|
||||
[videoID, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<CasualVoteDBResult[]>;
|
||||
|
||||
const getBranding = async () => {
|
||||
const titles = getTitles();
|
||||
const thumbnails = getThumbnails();
|
||||
const segments = getSegments();
|
||||
const casualVotes = getCasualVotes();
|
||||
|
||||
for (const title of await titles) {
|
||||
title.title = title.title.replaceAll("<", "‹");
|
||||
}
|
||||
|
||||
return {
|
||||
titles: await titles,
|
||||
thumbnails: await thumbnails,
|
||||
segments: await segments,
|
||||
casualVotes: await casualVotes
|
||||
};
|
||||
};
|
||||
|
||||
const brandingTrace = await QueryCacher.getTraced(getBranding, brandingKey(videoID, service));
|
||||
const branding = brandingTrace.data;
|
||||
|
||||
// Add trace info to request for debugging purposes
|
||||
res.setHeader("X-Start-Time", brandingTrace.startTime);
|
||||
if (brandingTrace.dbStartTime) res.setHeader("X-DB-Start-Time", brandingTrace.dbStartTime);
|
||||
res.setHeader("X-End-Time", brandingTrace.endTime);
|
||||
const stats = (db as Postgres)?.getStats?.();
|
||||
if (stats) {
|
||||
res.setHeader("X-DB-Pool-Total", stats.pool.total);
|
||||
res.setHeader("X-DB-Pool-Idle", stats.pool.idle);
|
||||
res.setHeader("X-DB-Pool-Waiting", stats.pool.waiting);
|
||||
}
|
||||
|
||||
const cache = {
|
||||
currentIP: null as Promise<HashedIP> | null
|
||||
};
|
||||
|
||||
return filterAndSortBranding(videoID, returnUserID, fetchAll, branding.titles,
|
||||
branding.thumbnails, branding.segments, branding.casualVotes, ip, cache);
|
||||
}
|
||||
|
||||
export async function getVideoBrandingByHash(videoHashPrefix: VideoIDHash, service: Service, ip: IPAddress, returnUserID: boolean, fetchAll: boolean): Promise<Record<VideoID, BrandingResult>> {
|
||||
const getTitles = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "titles"."title", "titles"."original", "titleVotes"."votes", "titleVotes"."downvotes", "titleVotes"."locked", "titleVotes"."shadowHidden", "titles"."UUID", "titles"."videoID", "titles"."hashedVideoID", "titleVotes"."verification"
|
||||
FROM "titles" JOIN "titleVotes" ON "titles"."UUID" = "titleVotes"."UUID"
|
||||
WHERE "titles"."hashedVideoID" LIKE ? AND "titles"."service" = ? AND "titleVotes"."votes" > -1 AND "titleVotes"."votes" - "titleVotes"."downvotes" > -2 AND "titleVotes"."removed" = 0`,
|
||||
[`${videoHashPrefix}%`, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<TitleDBResult[]>;
|
||||
|
||||
const getThumbnails = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "thumbnailTimestamps"."timestamp", "thumbnails"."original", "thumbnailVotes"."votes", "thumbnailVotes"."downvotes", "thumbnailVotes"."locked", "thumbnailVotes"."shadowHidden", "thumbnails"."UUID", "thumbnails"."videoID", "thumbnails"."hashedVideoID"
|
||||
FROM "thumbnails" LEFT JOIN "thumbnailVotes" ON "thumbnails"."UUID" = "thumbnailVotes"."UUID" LEFT JOIN "thumbnailTimestamps" ON "thumbnails"."UUID" = "thumbnailTimestamps"."UUID"
|
||||
WHERE "thumbnails"."hashedVideoID" LIKE ? AND "thumbnails"."service" = ? AND "thumbnailVotes"."votes" - "thumbnailVotes"."downvotes" > -2 AND "thumbnailVotes"."removed" = 0
|
||||
ORDER BY "thumbnails"."timeSubmitted" ASC`,
|
||||
[`${videoHashPrefix}%`, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<ThumbnailDBResult[]>;
|
||||
|
||||
const getSegments = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "videoID", "startTime", "endTime", "category", "videoDuration" FROM "sponsorTimes"
|
||||
WHERE "votes" > -2 AND "shadowHidden" = 0 AND "hidden" = 0 AND "actionType" = 'skip' AND "hashedVideoID" LIKE ? AND "service" = ?
|
||||
ORDER BY "timeSubmitted" ASC`,
|
||||
[`${videoHashPrefix}%`, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<BrandingSegmentHashDBResult[]>;
|
||||
|
||||
const getCasualVotes = () => db.prepare(
|
||||
"all",
|
||||
`SELECT "casualVotes"."videoID", "casualVotes"."category", "casualVotes"."upvotes", "casualVoteTitles"."title"
|
||||
FROM "casualVotes" LEFT JOIN "casualVoteTitles" ON "casualVotes"."videoID" = "casualVoteTitles"."videoID" AND "casualVotes"."service" = "casualVoteTitles"."service" AND "casualVotes"."titleID" = "casualVoteTitles"."id"
|
||||
WHERE "casualVotes"."hashedVideoID" LIKE ? AND "casualVotes"."service" = ?
|
||||
ORDER BY "casualVotes"."timeSubmitted" ASC`,
|
||||
[`${videoHashPrefix}%`, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<CasualVoteHashDBResult[]>;
|
||||
|
||||
const branding = await QueryCacher.get(async () => {
|
||||
// Make sure they are both called in parallel
|
||||
const branding = {
|
||||
titles: getTitles(),
|
||||
thumbnails: getThumbnails(),
|
||||
segments: getSegments(),
|
||||
casualVotes: getCasualVotes()
|
||||
};
|
||||
|
||||
const dbResult: Record<VideoID, BrandingHashDBResult> = {};
|
||||
const initResult = (submission: BrandingDBSubmissionData) => {
|
||||
dbResult[submission.videoID] = dbResult[submission.videoID] || {
|
||||
titles: [],
|
||||
thumbnails: [],
|
||||
segments: [],
|
||||
casualVotes: []
|
||||
};
|
||||
};
|
||||
|
||||
(await branding.titles).forEach((title) => {
|
||||
title.title = title.title.replaceAll("<", "‹");
|
||||
|
||||
initResult(title);
|
||||
dbResult[title.videoID].titles.push(title);
|
||||
});
|
||||
(await branding.thumbnails).forEach((thumbnail) => {
|
||||
initResult(thumbnail);
|
||||
dbResult[thumbnail.videoID].thumbnails.push(thumbnail);
|
||||
});
|
||||
|
||||
(await branding.segments).forEach((segment) => {
|
||||
initResult(segment);
|
||||
dbResult[segment.videoID].segments.push(segment);
|
||||
});
|
||||
|
||||
(await branding.casualVotes).forEach((casualVote) => {
|
||||
initResult(casualVote);
|
||||
dbResult[casualVote.videoID].casualVotes.push(casualVote);
|
||||
});
|
||||
|
||||
return dbResult;
|
||||
}, brandingHashKey(videoHashPrefix, service));
|
||||
|
||||
|
||||
const cache = {
|
||||
currentIP: null as Promise<HashedIP> | null
|
||||
};
|
||||
|
||||
const processedResult: Record<VideoID, BrandingResult> = {};
|
||||
await Promise.all(Object.keys(branding).map(async (key) => {
|
||||
const castedKey = key as VideoID;
|
||||
processedResult[castedKey] = await filterAndSortBranding(castedKey, returnUserID, fetchAll, branding[castedKey].titles,
|
||||
branding[castedKey].thumbnails, branding[castedKey].segments, branding[castedKey].casualVotes, ip, cache);
|
||||
}));
|
||||
|
||||
return processedResult;
|
||||
}
|
||||
|
||||
async function filterAndSortBranding(videoID: VideoID, returnUserID: boolean, fetchAll: boolean, dbTitles: TitleDBResult[],
|
||||
dbThumbnails: ThumbnailDBResult[], dbSegments: BrandingSegmentDBResult[], dbCasualVotes: CasualVoteDBResult[],
|
||||
ip: IPAddress, cache: { currentIP: Promise<HashedIP> | null }): Promise<BrandingResult> {
|
||||
|
||||
const shouldKeepTitles = shouldKeepSubmission(dbTitles, BrandingSubmissionType.Title, ip, cache);
|
||||
const shouldKeepThumbnails = shouldKeepSubmission(dbThumbnails, BrandingSubmissionType.Thumbnail, ip, cache);
|
||||
|
||||
const titles = shuffleArray(dbTitles.filter(await shouldKeepTitles))
|
||||
.map((r) => ({
|
||||
title: r.title,
|
||||
original: r.original === 1,
|
||||
votes: r.votes + r.verification - r.downvotes,
|
||||
locked: r.locked === 1,
|
||||
UUID: r.UUID,
|
||||
userID: returnUserID ? r.userID : undefined
|
||||
}))
|
||||
.filter((a) => fetchAll || a.votes >= 0 || a.locked)
|
||||
.sort((a, b) => b.votes - a.votes)
|
||||
.sort((a, b) => +b.locked - +a.locked) as TitleResult[];
|
||||
|
||||
const thumbnails = dbThumbnails.filter(await shouldKeepThumbnails)
|
||||
.sort((a, b) => +a.original - +b.original)
|
||||
.sort((a, b) => b.votes - a.votes)
|
||||
.sort((a, b) => b.locked - a.locked)
|
||||
.map((r) => ({
|
||||
timestamp: r.timestamp,
|
||||
original: r.original === 1,
|
||||
votes: r.votes - r.downvotes,
|
||||
locked: r.locked === 1,
|
||||
UUID: r.UUID,
|
||||
userID: returnUserID ? r.userID : undefined
|
||||
}))
|
||||
.filter((a) => (fetchAll && !a.original) || a.votes >= 1 || (a.votes >= 0 && !a.original) || a.locked) as ThumbnailResult[];
|
||||
|
||||
const casualDownvotes = dbCasualVotes.filter((r) => r.category === "downvote")[0];
|
||||
const casualVotes = dbCasualVotes.filter((r) => r.category !== "downvote").map((r) => ({
|
||||
id: r.category,
|
||||
count: r.upvotes - (casualDownvotes?.upvotes ?? 0),
|
||||
title: r.title
|
||||
})).filter((a) => a.count > 0);
|
||||
|
||||
const videoDuration = dbSegments.filter(s => s.videoDuration !== 0)[0]?.videoDuration ?? null;
|
||||
|
||||
return {
|
||||
titles,
|
||||
thumbnails,
|
||||
casualVotes,
|
||||
randomTime: findRandomTime(videoID, dbSegments, videoDuration),
|
||||
videoDuration: videoDuration,
|
||||
};
|
||||
}
|
||||
|
||||
async function shouldKeepSubmission(submissions: BrandingDBSubmission[], type: BrandingSubmissionType, ip: IPAddress,
|
||||
cache: { currentIP: Promise<HashedIP> | null }): Promise<(_: unknown, index: number) => boolean> {
|
||||
|
||||
const shouldKeep = await Promise.all(submissions.map(async (s) => {
|
||||
if (s.shadowHidden === Visibility.VISIBLE) return true;
|
||||
const table = type === BrandingSubmissionType.Title ? "titleVotes" : "thumbnailVotes";
|
||||
const fetchData = () => privateDB.prepare("get", `SELECT "hashedIP" FROM "${table}" WHERE "UUID" = ?`,
|
||||
[s.UUID], { useReplica: true }) as Promise<{ hashedIP: HashedIP }>;
|
||||
try {
|
||||
const submitterIP = await promiseOrTimeout(QueryCacher.get(fetchData, brandingIPKey(s.UUID)), 150);
|
||||
if (cache.currentIP === null) cache.currentIP = getHashCache((ip + config.globalSalt) as IPAddress);
|
||||
const hashedIP = await cache.currentIP;
|
||||
|
||||
return submitterIP?.hashedIP === hashedIP;
|
||||
} catch (e) {
|
||||
// give up on shadow hide for now
|
||||
Logger.error(`getBranding: Error while trying to find IP: ${e}`);
|
||||
|
||||
return false;
|
||||
}
|
||||
}));
|
||||
|
||||
return (_, index) => shouldKeep[index];
|
||||
}
|
||||
|
||||
export function findRandomTime(videoID: VideoID, segments: BrandingSegmentDBResult[], videoDuration: number): number {
|
||||
let randomTime = SeedRandom.alea(videoID)();
|
||||
|
||||
// Don't allow random times past 90% of the video if no endcard
|
||||
if (!segments.some((s) => s.category === "outro") && randomTime > 0.9) {
|
||||
randomTime -= 0.9;
|
||||
}
|
||||
|
||||
if (segments.length === 0) return randomTime;
|
||||
|
||||
videoDuration ||= Math.max(...segments.map((s) => s.endTime)); // use highest end time as a fallback here
|
||||
|
||||
// There are segments, treat this as a relative time in the chopped up video
|
||||
const sorted = segments.sort((a, b) => a.startTime - b.startTime);
|
||||
const emptySegments: [number, number][] = [];
|
||||
let totalTime = 0;
|
||||
|
||||
let nextEndTime = 0;
|
||||
for (const segment of sorted) {
|
||||
if (segment.startTime > nextEndTime) {
|
||||
emptySegments.push([nextEndTime, segment.startTime]);
|
||||
totalTime += segment.startTime - nextEndTime;
|
||||
}
|
||||
|
||||
nextEndTime = Math.max(segment.endTime, nextEndTime);
|
||||
}
|
||||
|
||||
if (nextEndTime < videoDuration) {
|
||||
emptySegments.push([nextEndTime, videoDuration]);
|
||||
totalTime += videoDuration - nextEndTime;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
for (const segment of emptySegments) {
|
||||
const duration = segment[1] - segment[0];
|
||||
|
||||
if (cursor + duration >= randomTime * totalTime) {
|
||||
// Found it
|
||||
return (segment[0] + (randomTime * totalTime - cursor)) / videoDuration;
|
||||
}
|
||||
|
||||
cursor += duration;
|
||||
}
|
||||
|
||||
// Fallback to just the random time
|
||||
return randomTime;
|
||||
}
|
||||
|
||||
export async function getBranding(req: Request, res: Response) {
|
||||
const videoID: VideoID = req.query.videoID as VideoID;
|
||||
const service: Service = getService(req.query.service as string);
|
||||
const returnUserID = req.query.returnUserID === "true";
|
||||
const fetchAll = req.query.fetchAll === "true";
|
||||
|
||||
if (!videoID) {
|
||||
return res.status(400).send("Missing parameter: videoID");
|
||||
}
|
||||
|
||||
const ip = getIP(req);
|
||||
try {
|
||||
const result = await getVideoBranding(res, videoID, service, ip, returnUserID, fetchAll);
|
||||
|
||||
await getEtag("branding", (videoID as string), service)
|
||||
.then(etag => res.set("ETag", etag))
|
||||
.catch(() => null);
|
||||
|
||||
const status = result.titles.length > 0 || result.thumbnails.length > 0 || result.casualVotes.length > 0 ? 200 : 404;
|
||||
return res.status(status).json(result);
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
return res.status(500).send("Internal server error");
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBrandingByHashEndpoint(req: Request, res: Response) {
|
||||
let hashPrefix = req.params.prefix as VideoIDHash;
|
||||
if (!hashPrefix || !hashPrefixTester(hashPrefix) || hashPrefix.length !== 4) {
|
||||
return res.status(400).send("Hash prefix does not match format requirements."); // Exit early on faulty prefix
|
||||
}
|
||||
hashPrefix = hashPrefix.toLowerCase() as VideoIDHash;
|
||||
|
||||
const service: Service = getService(req.query.service as string);
|
||||
const ip = getIP(req);
|
||||
const returnUserID = req.query.returnUserID === "true";
|
||||
const fetchAll = req.query.fetchAll === "true";
|
||||
|
||||
try {
|
||||
const result = await getVideoBrandingByHash(hashPrefix, service, ip, returnUserID, fetchAll);
|
||||
|
||||
await getEtag("brandingHash", (hashPrefix as string), service)
|
||||
.then(etag => res.set("ETag", etag))
|
||||
.catch(() => null);
|
||||
|
||||
const status = !isEmpty(result) ? 200 : 404;
|
||||
return res.status(status).json(result);
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
return res.status(500).send([]);
|
||||
}
|
||||
}
|
||||
82
src/routes/getBrandingStats.ts
Normal file
82
src/routes/getBrandingStats.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
/* istanbul ignore file */
|
||||
|
||||
import { db } from "../databases/databases";
|
||||
import { Request, Response } from "express";
|
||||
import axios from "axios";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { getCWSUsers, getChromeUsers } from "../utils/getCWSUsers";
|
||||
|
||||
// A cache of the number of chrome web store users
|
||||
let chromeUsersCache = 30000;
|
||||
let firefoxUsersCache = 0;
|
||||
|
||||
interface DBStatsData {
|
||||
userCount: number,
|
||||
titles: number,
|
||||
thumbnails: number,
|
||||
}
|
||||
|
||||
let lastFetch: DBStatsData = {
|
||||
userCount: 0,
|
||||
titles: 0,
|
||||
thumbnails: 0
|
||||
};
|
||||
|
||||
updateExtensionUsers();
|
||||
|
||||
export async function getBrandingStats(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const row = await getStats();
|
||||
lastFetch = row;
|
||||
|
||||
/* istanbul ignore if */
|
||||
if (!row) res.sendStatus(500);
|
||||
const extensionUsers = chromeUsersCache + firefoxUsersCache;
|
||||
|
||||
//send this result
|
||||
res.send({
|
||||
userCount: row.userCount ?? 0,
|
||||
activeUsers: extensionUsers,
|
||||
titles: row.titles,
|
||||
thumbnails: row.thumbnails,
|
||||
});
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
|
||||
async function getStats(): Promise<DBStatsData> {
|
||||
if (db.highLoad()) {
|
||||
return Promise.resolve(lastFetch);
|
||||
} else {
|
||||
const userCount = (await db.prepare("get", `SELECT COUNT(DISTINCT "userID") as "userCount" FROM titles`, []))?.userCount;
|
||||
const titles = (await db.prepare("get", `SELECT COUNT(*) as "titles" FROM titles`, []))?.titles;
|
||||
const thumbnails = (await db.prepare("get", `SELECT COUNT(*) as "thumbnails" FROM thumbnails`, []))?.thumbnails;
|
||||
|
||||
return {
|
||||
userCount: userCount ?? 0,
|
||||
titles: titles ?? 0,
|
||||
thumbnails: thumbnails ?? 0
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function updateExtensionUsers() {
|
||||
const mozillaAddonsUrl = "https://addons.mozilla.org/api/v3/addons/addon/dearrow/";
|
||||
const chromeExtensionUrl = "https://chromewebstore.google.com/detail/dearrow-better-titles-and/enamippconapkdmgfgjchkhakpfinmaj";
|
||||
const chromeExtId = "enamippconapkdmgfgjchkhakpfinmaj";
|
||||
|
||||
axios.get(mozillaAddonsUrl)
|
||||
.then(res => firefoxUsersCache = res.data.average_daily_users )
|
||||
.catch( /* istanbul ignore next */ () => {
|
||||
Logger.debug(`Failing to connect to ${mozillaAddonsUrl}`);
|
||||
return 0;
|
||||
});
|
||||
getCWSUsers(chromeExtId)
|
||||
.then(res => chromeUsersCache = res)
|
||||
.catch(/* istanbul ignore next */ () =>
|
||||
getChromeUsers(chromeExtensionUrl)
|
||||
.then(res => chromeUsersCache = res)
|
||||
);
|
||||
}
|
||||
@@ -22,15 +22,16 @@ export async function getChapterNames(req: Request, res: Response): Promise<Resp
|
||||
const descriptions = await db.prepare("all", `
|
||||
SELECT "description"
|
||||
FROM "sponsorTimes"
|
||||
WHERE ("votes" > 0 OR ("views" > 100 AND "votes" >= 0)) AND "videoID" IN (
|
||||
WHERE ("locked" = 1 OR "votes" >= 0) AND "videoID" IN (
|
||||
SELECT "videoID"
|
||||
FROM "videoInfo"
|
||||
WHERE "channelID" = ?
|
||||
) AND "description" != ''
|
||||
AND similarity("description", ?) >= 0.1
|
||||
GROUP BY "description"
|
||||
ORDER BY SUM("votes"), similarity("description", ?) DESC
|
||||
LIMIT 5;`
|
||||
, [channelID, description]) as { description: string }[];
|
||||
, [channelID, description, description]) as { description: string }[];
|
||||
|
||||
if (descriptions?.length > 0) {
|
||||
return res.status(200).json(descriptions.map(d => ({
|
||||
|
||||
35
src/routes/getConfig.ts
Normal file
35
src/routes/getConfig.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
import { Request, Response } from "express";
|
||||
import { isUserVIP } from "../utils/isUserVIP";
|
||||
import { UserID } from "../types/user.model";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { getServerConfig } from "../utils/serverConfig";
|
||||
|
||||
export async function getConfigEndpoint(req: Request, res: Response): Promise<Response> {
|
||||
const userID = req.query.userID as string;
|
||||
const key = req.query.key as string;
|
||||
|
||||
if (!userID || !key) {
|
||||
// invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
// hash the userID
|
||||
const hashedUserID = await getHashCache(userID as UserID);
|
||||
const isVIP = (await isUserVIP(hashedUserID));
|
||||
|
||||
if (!isVIP) {
|
||||
// not authorized
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
|
||||
try {
|
||||
return res.status(200).json({
|
||||
value: await getServerConfig(key)
|
||||
});
|
||||
} catch (e) {
|
||||
Logger.error(e as string);
|
||||
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,23 @@
|
||||
import { db } from "../databases/databases";
|
||||
import { Request, Response } from "express";
|
||||
import { Logger } from "../utils/logger";
|
||||
|
||||
export async function getDaysSavedFormatted(req: Request, res: Response): Promise<Response> {
|
||||
const row = await db.prepare("get", 'SELECT SUM(("endTime" - "startTime") / 60 / 60 / 24 * "views") as "daysSaved" from "sponsorTimes" where "shadowHidden" != 1', []);
|
||||
try {
|
||||
const row = await db.prepare("get", 'SELECT SUM(("endTime" - "startTime") / 60 / 60 / 24 * "views") as "daysSaved" from "sponsorTimes" where "shadowHidden" != 1', []);
|
||||
|
||||
if (row !== undefined) {
|
||||
//send this result
|
||||
return res.send({
|
||||
daysSaved: row.daysSaved.toFixed(2),
|
||||
});
|
||||
if (row !== undefined) {
|
||||
//send this result
|
||||
return res.send({
|
||||
daysSaved: row.daysSaved?.toFixed(2) ?? "0",
|
||||
});
|
||||
} else {
|
||||
return res.send({
|
||||
daysSaved: 0
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
|
||||
15
src/routes/getFeatureFlag.ts
Normal file
15
src/routes/getFeatureFlag.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { config } from "../config";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export function getFeatureFlag(req: Request, res: Response): Response {
|
||||
const { params: { name } } = req;
|
||||
|
||||
switch (name) {
|
||||
case "deArrowPaywall":
|
||||
return res.status(200).json({
|
||||
enabled: config.deArrowPaywall,
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(404).json();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -2,9 +2,8 @@ import { db } from "../databases/databases";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { Request, Response } from "express";
|
||||
import { Category, VideoID, ActionType } from "../types/segments.model";
|
||||
import { config } from "../config";
|
||||
import { filterInvalidCategoryActionType, parseActionTypes, parseCategories } from "../utils/parseParams";
|
||||
|
||||
const categorySupportList = config.categorySupport;
|
||||
interface lockArray {
|
||||
category: Category;
|
||||
locked: number,
|
||||
@@ -13,61 +12,19 @@ interface lockArray {
|
||||
userName: string,
|
||||
}
|
||||
|
||||
const filterActionType = (actionTypes: ActionType[]) => {
|
||||
const filterCategories = new Set();
|
||||
for (const [key, value] of Object.entries(categorySupportList)) {
|
||||
for (const type of actionTypes) {
|
||||
if (value.includes(type)) {
|
||||
filterCategories.add(key as Category);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...filterCategories];
|
||||
};
|
||||
|
||||
export async function getLockReason(req: Request, res: Response): Promise<Response> {
|
||||
const videoID = req.query.videoID as VideoID;
|
||||
if (!videoID) {
|
||||
// invalid request
|
||||
return res.status(400).send("No videoID provided");
|
||||
}
|
||||
let categories: Category[] = [];
|
||||
const actionTypes: ActionType[] = req.query.actionTypes
|
||||
? JSON.parse(req.query.actionTypes as string)
|
||||
: req.query.actionType
|
||||
? Array.isArray(req.query.actionType)
|
||||
? req.query.actionType
|
||||
: [req.query.actionType]
|
||||
: [ActionType.Skip, ActionType.Mute];
|
||||
const possibleCategories = filterActionType(actionTypes);
|
||||
if (!Array.isArray(actionTypes)) {
|
||||
//invalid request
|
||||
return res.status(400).send("actionTypes parameter does not match format requirements");
|
||||
}
|
||||
try {
|
||||
categories = req.query.categories
|
||||
? JSON.parse(req.query.categories as string)
|
||||
: req.query.category
|
||||
? Array.isArray(req.query.category)
|
||||
? req.query.category
|
||||
: [req.query.category]
|
||||
: []; // default to empty, will be set to all
|
||||
if (!Array.isArray(categories)) {
|
||||
return res.status(400).send("Categories parameter does not match format requirements.");
|
||||
}
|
||||
} catch(error) {
|
||||
return res.status(400).send("Bad parameter: categories (invalid JSON)");
|
||||
}
|
||||
// only take valid categories
|
||||
const searchCategories = (categories.length === 0 )
|
||||
? possibleCategories
|
||||
: categories.filter(x =>
|
||||
possibleCategories.includes(x));
|
||||
const actionTypes = parseActionTypes(req, [ActionType.Skip, ActionType.Mute]);
|
||||
const categories = parseCategories(req, []);
|
||||
|
||||
if (!videoID || !Array.isArray(actionTypes)) {
|
||||
//invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
// invalid requests
|
||||
const errors = [];
|
||||
if (!videoID) errors.push("No videoID provided");
|
||||
if (!Array.isArray(actionTypes)) errors.push("actionTypes parameter does not match format requirements");
|
||||
if (!Array.isArray(categories)) errors.push("Categories parameter does not match format requirements.");
|
||||
if (errors.length) return res.status(400).send(errors.join(", "));
|
||||
// only take valid categories
|
||||
const searchCategories = filterInvalidCategoryActionType(categories, actionTypes);
|
||||
|
||||
try {
|
||||
// Get existing lock categories markers
|
||||
@@ -115,7 +72,7 @@ export async function getLockReason(req: Request, res: Response): Promise<Respon
|
||||
}
|
||||
|
||||
return res.send(results);
|
||||
} catch (err) {
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
Logger.error(err as string);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
106
src/routes/getMetrics.ts
Normal file
106
src/routes/getMetrics.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { db, privateDB } from "../databases/databases";
|
||||
import { Request, Response } from "express";
|
||||
import os from "os";
|
||||
import redis, { getRedisStats } from "../utils/redis";
|
||||
import { Postgres } from "../databases/Postgres";
|
||||
import { Server } from "http";
|
||||
|
||||
export async function getMetrics(req: Request, res: Response, server: Server): Promise<Response> {
|
||||
const redisStats = getRedisStats();
|
||||
|
||||
return res.type("text").send([
|
||||
`# HELP sb_uptime Uptime of this instance`,
|
||||
`# TYPE sb_uptime counter`,
|
||||
`sb_uptime ${process.uptime()}`,
|
||||
`# HELP sb_db_version The version of the database`,
|
||||
`# TYPE sb_db_version counter`,
|
||||
`sb_db_version ${await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"]).then(e => e.value).catch(() => -1)}`,
|
||||
`# HELP sb_start_time The time this instance was started`,
|
||||
`# TYPE sb_start_time gauge`,
|
||||
`sb_start_time ${Date.now()}`,
|
||||
`# HELP sb_loadavg_5 The 5 minute load average of the system`,
|
||||
`# TYPE sb_loadavg_5 gauge`,
|
||||
`sb_loadavg_5 ${os.loadavg()[0]}`,
|
||||
`# HELP sb_loadavg_15 The 15 minute load average of the system`,
|
||||
`# TYPE sb_loadavg_15 gauge`,
|
||||
`sb_loadavg_15 ${os.loadavg()[1]}`,
|
||||
`# HELP sb_connections The number of connections to this instance`,
|
||||
`# TYPE sb_connections gauge`,
|
||||
`sb_connections ${await new Promise((resolve) => server.getConnections((_, count) => resolve(count)) as any)}`,
|
||||
`# HELP sb_status_requests The number of status requests made to this instance`,
|
||||
`# TYPE sb_status_requests gauge`,
|
||||
`sb_status_requests ${await redis.increment("statusRequest").then(e => e[0]).catch(() => -1)}`,
|
||||
`# HELP sb_postgres_active_requests The number of active requests to the postgres database`,
|
||||
`# TYPE sb_postgres_active_requests gauge`,
|
||||
`sb_postgres_active_requests ${(db as Postgres)?.getStats?.()?.activeRequests ?? -1}`,
|
||||
`# HELP sb_postgres_avg_read_time The average read time of the postgres database`,
|
||||
`# TYPE sb_postgres_avg_read_time gauge`,
|
||||
`sb_postgres_avg_read_time ${(db as Postgres)?.getStats?.()?.avgReadTime ?? -1}`,
|
||||
`# HELP sb_postgres_avg_write_time The average write time of the postgres database`,
|
||||
`# TYPE sb_postgres_avg_write_time gauge`,
|
||||
`sb_postgres_avg_write_time ${(db as Postgres)?.getStats?.()?.avgWriteTime ?? -1}`,
|
||||
`# HELP sb_postgres_avg_failed_time The average failed time of the postgres database`,
|
||||
`# TYPE sb_postgres_avg_failed_time gauge`,
|
||||
`sb_postgres_avg_failed_time ${(db as Postgres)?.getStats?.()?.avgFailedTime ?? -1}`,
|
||||
`# HELP sb_postgres_pool_total The total number of connections in the postgres pool`,
|
||||
`# TYPE sb_postgres_pool_total gauge`,
|
||||
`sb_postgres_pool_total ${(db as Postgres)?.getStats?.()?.pool?.total ?? -1}`,
|
||||
`# HELP sb_postgres_pool_idle The number of idle connections in the postgres pool`,
|
||||
`# TYPE sb_postgres_pool_idle gauge`,
|
||||
`sb_postgres_pool_idle ${(db as Postgres)?.getStats?.()?.pool?.idle ?? -1}`,
|
||||
`# HELP sb_postgres_pool_waiting The number of connections waiting in the postgres pool`,
|
||||
`# TYPE sb_postgres_pool_waiting gauge`,
|
||||
`sb_postgres_pool_waiting ${(db as Postgres)?.getStats?.()?.pool?.waiting ?? -1}`,
|
||||
`# HELP sb_postgres_private_active_requests The number of active requests to the private postgres database`,
|
||||
`# TYPE sb_postgres_private_active_requests gauge`,
|
||||
`sb_postgres_private_active_requests ${(privateDB as Postgres)?.getStats?.()?.activeRequests ?? -1}`,
|
||||
`# HELP sb_postgres_private_avg_read_time The average read time of the private postgres database`,
|
||||
`# TYPE sb_postgres_private_avg_read_time gauge`,
|
||||
`sb_postgres_private_avg_read_time ${(privateDB as Postgres)?.getStats?.()?.avgReadTime ?? -1}`,
|
||||
`# HELP sb_postgres_private_avg_write_time The average write time of the private postgres database`,
|
||||
`# TYPE sb_postgres_private_avg_write_time gauge`,
|
||||
`sb_postgres_private_avg_write_time ${(privateDB as Postgres)?.getStats?.()?.avgWriteTime ?? -1}`,
|
||||
`# HELP sb_postgres_private_avg_failed_time The average failed time of the private postgres database`,
|
||||
`# TYPE sb_postgres_private_avg_failed_time gauge`,
|
||||
`sb_postgres_private_avg_failed_time ${(privateDB as Postgres)?.getStats?.()?.avgFailedTime ?? -1}`,
|
||||
`# HELP sb_postgres_private_pool_total The total number of connections in the private postgres pool`,
|
||||
`# TYPE sb_postgres_private_pool_total gauge`,
|
||||
`sb_postgres_private_pool_total ${(privateDB as Postgres)?.getStats?.()?.pool?.total ?? -1}`,
|
||||
`# HELP sb_postgres_private_pool_idle The number of idle connections in the private postgres pool`,
|
||||
`# TYPE sb_postgres_private_pool_idle gauge`,
|
||||
`sb_postgres_private_pool_idle ${(privateDB as Postgres)?.getStats?.()?.pool?.idle ?? -1}`,
|
||||
`# HELP sb_postgres_private_pool_waiting The number of connections waiting in the private postgres pool`,
|
||||
`# TYPE sb_postgres_private_pool_waiting gauge`,
|
||||
`sb_postgres_private_pool_waiting ${(privateDB as Postgres)?.getStats?.()?.pool?.waiting ?? -1}`,
|
||||
`# HELP sb_redis_active_requests The number of active requests to redis`,
|
||||
`# TYPE sb_redis_active_requests gauge`,
|
||||
`sb_redis_active_requests ${redisStats.activeRequests}`,
|
||||
`# HELP sb_redis_write_requests The number of write requests to redis`,
|
||||
`# TYPE sb_redis_write_requests gauge`,
|
||||
`sb_redis_write_requests ${redisStats.writeRequests}`,
|
||||
`# HELP sb_redis_avg_read_time The average read time of redis`,
|
||||
`# TYPE sb_redis_avg_read_time gauge`,
|
||||
`sb_redis_avg_read_time ${redisStats?.avgReadTime}`,
|
||||
`# HELP sb_redis_avg_write_time The average write time of redis`,
|
||||
`# TYPE sb_redis_avg_write_time gauge`,
|
||||
`sb_redis_avg_write_time ${redisStats.avgWriteTime}`,
|
||||
`# HELP sb_redis_memory_cache_hits The cache hit ratio in redis`,
|
||||
`# TYPE sb_redis_memory_cache_hits gauge`,
|
||||
`sb_redis_memory_cache_hits ${redisStats.memoryCacheHits}`,
|
||||
`# HELP sb_redis_memory_cache_total_hits The cache hit ratio in redis including uncached items`,
|
||||
`# TYPE sb_redis_memory_cache_total_hits gauge`,
|
||||
`sb_redis_memory_cache_total_hits ${redisStats.memoryCacheTotalHits}`,
|
||||
`# HELP sb_redis_memory_cache_length The length of the memory cache in redis`,
|
||||
`# TYPE sb_redis_memory_cache_length gauge`,
|
||||
`sb_redis_memory_cache_length ${redisStats.memoryCacheLength}`,
|
||||
`# HELP sb_redis_memory_cache_size The size of the memory cache in redis`,
|
||||
`# TYPE sb_redis_memory_cache_size gauge`,
|
||||
`sb_redis_memory_cache_size ${redisStats.memoryCacheSize}`,
|
||||
`# HELP sb_redis_last_invalidation The time of the last successful invalidation in redis`,
|
||||
`# TYPE sb_redis_last_invalidation gauge`,
|
||||
`sb_redis_last_invalidation ${redisStats.lastInvalidation}`,
|
||||
`# HELP sb_redis_last_invalidation_message The time of the last invalidation message in redis`,
|
||||
`# TYPE sb_redis_last_invalidation_message gauge`,
|
||||
`sb_redis_last_invalidation_message ${redisStats.lastInvalidationMessage}`,
|
||||
].join("\n"));
|
||||
}
|
||||
26
src/routes/getReady.ts
Normal file
26
src/routes/getReady.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Request, Response } from "express";
|
||||
import { Server } from "http";
|
||||
import { config } from "../config";
|
||||
import { getRedisStats } from "../utils/redis";
|
||||
import { Postgres } from "../databases/Postgres";
|
||||
import { db } from "../databases/databases";
|
||||
|
||||
export async function getReady(req: Request, res: Response, server: Server): Promise<Response> {
|
||||
const connections = await new Promise((resolve) => server.getConnections((_, count) => resolve(count))) as number;
|
||||
|
||||
const redisStats = getRedisStats();
|
||||
const postgresStats = (db as Postgres).getStats?.();
|
||||
|
||||
if (!connections
|
||||
|| (connections < config.maxConnections
|
||||
&& (!config.redis || redisStats.activeRequests < config.redis.maxConnections * 0.8)
|
||||
&& (!config.redis || redisStats.activeRequests < 1 || redisStats.avgReadTime < config.maxResponseTime
|
||||
|| (redisStats.memoryCacheSize < config.redis.clientCacheSize * 0.8 && redisStats.avgReadTime < config.maxResponseTimeWhileLoadingCache))
|
||||
&& (!config.postgres || postgresStats.activeRequests < config.postgres.maxActiveRequests * 0.8)
|
||||
&& (!config.postgres || postgresStats.avgReadTime < config.maxResponseTime
|
||||
|| (redisStats.memoryCacheSize < config.redis.clientCacheSize * 0.8 && postgresStats.avgReadTime < config.maxResponseTimeWhileLoadingCache)))) {
|
||||
return res.sendStatus(200);
|
||||
} else {
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
20
src/routes/getSegmentID.ts
Normal file
20
src/routes/getSegmentID.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { db } from "../databases/databases";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export async function getSegmentID(req: Request, res: Response): Promise<Response> {
|
||||
const partialUUID = req.query?.UUID;
|
||||
const videoID = req.query?.videoID;
|
||||
|
||||
if (!partialUUID || !videoID) {
|
||||
//invalid request
|
||||
return res.sendStatus(400);
|
||||
}
|
||||
|
||||
const data = await db.prepare("get", `SELECT "UUID" from "sponsorTimes" WHERE "UUID" LIKE ? AND "videoID" = ?`, [`${partialUUID}%`, videoID]);
|
||||
|
||||
if (data) {
|
||||
return res.status(200).send(data.UUID);
|
||||
} else {
|
||||
return res.sendStatus(404);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Request, Response } from "express";
|
||||
import { partition } from "lodash";
|
||||
import { config } from "../config";
|
||||
import { db, privateDB } from "../databases/databases";
|
||||
import { skipSegmentsHashKey, skipSegmentsKey, skipSegmentGroupsKey, shadowHiddenIPKey } from "../utils/redisKeys";
|
||||
import { skipSegmentsHashKey, skipSegmentsKey, skipSegmentGroupsKey, shadowHiddenIPKey, skipSegmentsLargerHashKey } from "../utils/redisKeys";
|
||||
import { SBRecord } from "../types/lib.model";
|
||||
import { ActionType, Category, DBSegment, HashedIP, IPAddress, OverlappingSegmentGroup, Segment, SegmentCache, SegmentUUID, Service, VideoData, VideoID, VideoIDHash, Visibility, VotableObject } from "../types/segments.model";
|
||||
import { getHashCache } from "../utils/getHashCache";
|
||||
@@ -11,36 +11,76 @@ import { Logger } from "../utils/logger";
|
||||
import { QueryCacher } from "../utils/queryCacher";
|
||||
import { getReputation } from "../utils/reputation";
|
||||
import { getService } from "../utils/getService";
|
||||
|
||||
import { promiseOrTimeout } from "../utils/promise";
|
||||
import { parseSkipSegments } from "../utils/parseSkipSegments";
|
||||
import { getEtag } from "../middleware/etag";
|
||||
import { shuffleArray } from "../utils/array";
|
||||
import { Postgres } from "../databases/Postgres";
|
||||
import { getRedisStats } from "../utils/redis";
|
||||
|
||||
async function prepareCategorySegments(req: Request, videoID: VideoID, service: Service, segments: DBSegment[], cache: SegmentCache = { shadowHiddenSegmentIPs: {} }, useCache: boolean): Promise<Segment[]> {
|
||||
const shouldFilter: boolean[] = await Promise.all(segments.map(async (segment) => {
|
||||
if (segment.votes < -1 && !segment.required) {
|
||||
if (segment.required) {
|
||||
return true; //required - always send
|
||||
}
|
||||
|
||||
if (segment.hidden
|
||||
|| segment.votes < -1
|
||||
|| segment.shadowHidden === Visibility.MORE_HIDDEN) {
|
||||
return false; //too untrustworthy, just ignore it
|
||||
}
|
||||
|
||||
//check if shadowHidden
|
||||
//this means it is hidden to everyone but the original ip that submitted it
|
||||
if (segment.shadowHidden != Visibility.HIDDEN) {
|
||||
if (segment.shadowHidden === Visibility.VISIBLE) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (cache.shadowHiddenSegmentIPs[videoID] === undefined) cache.shadowHiddenSegmentIPs[videoID] = {};
|
||||
if (cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] === undefined) {
|
||||
if (cache.userHashedIP === undefined && cache.userHashedIPPromise === undefined) {
|
||||
cache.userHashedIPPromise = getHashCache((getIP(req) + config.globalSalt) as IPAddress);
|
||||
}
|
||||
|
||||
const service = getService(req?.query?.service as string);
|
||||
const fetchData = () => privateDB.prepare("all", 'SELECT "hashedIP" FROM "sponsorTimes" WHERE "videoID" = ? AND "timeSubmitted" = ? AND "service" = ?',
|
||||
[videoID, segment.timeSubmitted, service]) as Promise<{ hashedIP: HashedIP }[]>;
|
||||
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = await QueryCacher.get(fetchData, shadowHiddenIPKey(videoID, segment.timeSubmitted, service));
|
||||
[videoID, segment.timeSubmitted, service], { useReplica: true }) as Promise<{ hashedIP: HashedIP }[]>;
|
||||
try {
|
||||
if (db.highLoad() || privateDB.highLoad()) {
|
||||
Logger.error("High load, not handling shadowhide");
|
||||
if (db instanceof Postgres && privateDB instanceof Postgres) {
|
||||
Logger.error(`Postgres stats: ${JSON.stringify(db.getStats())}`);
|
||||
Logger.error(`Postgres private stats: ${JSON.stringify(privateDB.getStats())}`);
|
||||
}
|
||||
Logger.error(`Redis stats: ${JSON.stringify(getRedisStats())}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = promiseOrTimeout(QueryCacher.get(fetchData, shadowHiddenIPKey(videoID, segment.timeSubmitted, service)), 150);
|
||||
} catch (e) {
|
||||
// give up on shadowhide for now
|
||||
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = null;
|
||||
}
|
||||
}
|
||||
|
||||
const ipList = cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted];
|
||||
let ipList = [];
|
||||
try {
|
||||
ipList = await cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted];
|
||||
} catch (e) {
|
||||
Logger.error(`skipSegments: Error while trying to find IP: ${e}`);
|
||||
if (db instanceof Postgres && privateDB instanceof Postgres) {
|
||||
Logger.error(`Postgres stats: ${JSON.stringify(db.getStats())}`);
|
||||
Logger.error(`Postgres private stats: ${JSON.stringify(privateDB.getStats())}`);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ipList?.length > 0 && cache.userHashedIP === undefined) {
|
||||
//hash the IP only if it's strictly necessary
|
||||
cache.userHashedIP = await getHashCache((getIP(req) + config.globalSalt) as IPAddress);
|
||||
cache.userHashedIP = await cache.userHashedIPPromise;
|
||||
}
|
||||
//if this isn't their ip, don't send it to them
|
||||
const shouldShadowHide = cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted]?.some(
|
||||
const shouldShadowHide = ipList?.some(
|
||||
(shadowHiddenSegment) => shadowHiddenSegment.hashedIP === cache.userHashedIP) ?? false;
|
||||
|
||||
if (shouldShadowHide) useCache = false;
|
||||
@@ -73,9 +113,6 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
|
||||
}
|
||||
|
||||
try {
|
||||
categories = categories.filter((category) => !/[^a-z|_|-]/.test(category));
|
||||
if (categories.length === 0) return null;
|
||||
|
||||
const segments: DBSegment[] = (await getSegmentsFromDBByVideoID(videoID, service))
|
||||
.map((segment: DBSegment) => {
|
||||
if (filterRequiredSegments(segment.UUID, requiredSegments)) segment.required = true;
|
||||
@@ -84,7 +121,17 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
|
||||
|
||||
const canUseCache = requiredSegments.length === 0;
|
||||
let processedSegments: Segment[] = (await prepareCategorySegments(req, videoID, service, segments, cache, canUseCache))
|
||||
.filter((segment: Segment) => categories.includes(segment?.category) && (actionTypes.includes(segment?.actionType)));
|
||||
.filter((segment: Segment) => categories.includes(segment?.category) && (actionTypes.includes(segment?.actionType)))
|
||||
.map((segment: Segment) => ({
|
||||
category: segment.category,
|
||||
actionType: segment.actionType,
|
||||
segment: segment.segment,
|
||||
UUID: segment.UUID,
|
||||
videoDuration: segment.videoDuration,
|
||||
locked: segment.locked,
|
||||
votes: segment.votes,
|
||||
description: segment.description
|
||||
}));
|
||||
|
||||
if (forcePoiAsSkip) {
|
||||
processedSegments = processedSegments.map((segment) => ({
|
||||
@@ -94,7 +141,7 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
|
||||
}
|
||||
|
||||
return processedSegments;
|
||||
} catch (err) {
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
if (err) {
|
||||
Logger.error(err as string);
|
||||
return null;
|
||||
@@ -103,7 +150,7 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
|
||||
}
|
||||
|
||||
async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categories: Category[],
|
||||
actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise<SBRecord<VideoID, VideoData>> {
|
||||
actionTypes: ActionType[], trimUUIDs: number, requiredSegments: SegmentUUID[], service: Service): Promise<SBRecord<VideoID, VideoData>> {
|
||||
const cache: SegmentCache = { shadowHiddenSegmentIPs: {} };
|
||||
const segments: SBRecord<VideoID, VideoData> = {};
|
||||
|
||||
@@ -114,15 +161,11 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
|
||||
}
|
||||
|
||||
try {
|
||||
type SegmentWithHashPerVideoID = SBRecord<VideoID, { hash: VideoIDHash, segments: DBSegment[] }>;
|
||||
type SegmentPerVideoID = SBRecord<VideoID, { segments: DBSegment[] }>;
|
||||
|
||||
categories = categories.filter((category) => !(/[^a-z|_|-]/.test(category)));
|
||||
if (categories.length === 0) return null;
|
||||
|
||||
const segmentPerVideoID: SegmentWithHashPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service))
|
||||
.reduce((acc: SegmentWithHashPerVideoID, segment: DBSegment) => {
|
||||
const segmentPerVideoID: SegmentPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service))
|
||||
.reduce((acc: SegmentPerVideoID, segment: DBSegment) => {
|
||||
acc[segment.videoID] = acc[segment.videoID] || {
|
||||
hash: segment.hashedVideoID,
|
||||
segments: []
|
||||
};
|
||||
if (filterRequiredSegments(segment.UUID, requiredSegments)) segment.required = true;
|
||||
@@ -133,16 +176,44 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
for (const [videoID, videoData] of Object.entries(segmentPerVideoID)) {
|
||||
await Promise.all(Object.entries(segmentPerVideoID).map(async ([videoID, videoData]) => {
|
||||
const data: VideoData = {
|
||||
hash: videoData.hash,
|
||||
segments: [],
|
||||
};
|
||||
|
||||
const canUseCache = requiredSegments.length === 0;
|
||||
data.segments = (await prepareCategorySegments(req, videoID as VideoID, service, videoData.segments, cache, canUseCache))
|
||||
const filteredSegments = (await prepareCategorySegments(req, videoID as VideoID, service, videoData.segments, cache, canUseCache))
|
||||
.filter((segment: Segment) => categories.includes(segment?.category) && actionTypes.includes(segment?.actionType));
|
||||
|
||||
// Make sure no hash duplicates exist
|
||||
if (trimUUIDs) {
|
||||
const seen = new Set<string>();
|
||||
for (const segment of filteredSegments) {
|
||||
const shortUUID = segment.UUID.substring(0, trimUUIDs);
|
||||
if (seen.has(shortUUID)) {
|
||||
// Duplicate found, disable trimming
|
||||
trimUUIDs = undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
seen.add(shortUUID);
|
||||
}
|
||||
|
||||
seen.clear();
|
||||
}
|
||||
|
||||
data.segments = filteredSegments
|
||||
.map((segment) => ({
|
||||
category: segment.category,
|
||||
actionType: segment.actionType,
|
||||
segment: segment.segment,
|
||||
UUID: trimUUIDs ? segment.UUID.substring(0, trimUUIDs) as SegmentUUID : segment.UUID,
|
||||
videoDuration: segment.videoDuration,
|
||||
locked: segment.locked,
|
||||
votes: segment.votes,
|
||||
description: segment.description
|
||||
}));
|
||||
|
||||
if (forcePoiAsSkip) {
|
||||
data.segments = data.segments.map((segment) => ({
|
||||
...segment,
|
||||
@@ -153,11 +224,11 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
|
||||
if (data.segments.length > 0) {
|
||||
segments[videoID] = data;
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
return segments;
|
||||
} catch (err) {
|
||||
Logger.error(err as string);
|
||||
} catch (err) /* istanbul ignore next */ {
|
||||
Logger.error(`get segments by hash error: ${err}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -166,13 +237,16 @@ async function getSegmentsFromDBByHash(hashedVideoIDPrefix: VideoIDHash, service
|
||||
const fetchFromDB = () => db
|
||||
.prepare(
|
||||
"all",
|
||||
`SELECT "videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "videoDuration", "reputation", "shadowHidden", "hashedVideoID", "timeSubmitted", "description" FROM "sponsorTimes"
|
||||
WHERE "hashedVideoID" LIKE ? AND "service" = ? AND "hidden" = 0 ORDER BY "startTime"`,
|
||||
[`${hashedVideoIDPrefix}%`, service]
|
||||
`SELECT "videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "videoDuration", "hidden", "reputation", "shadowHidden", "hashedVideoID", "timeSubmitted", "description" FROM "sponsorTimes"
|
||||
WHERE "hashedVideoID" LIKE ? AND "service" = ? ORDER BY "startTime"`,
|
||||
[`${hashedVideoIDPrefix}%`, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<DBSegment[]>;
|
||||
|
||||
if (hashedVideoIDPrefix.length === 4) {
|
||||
return await QueryCacher.get(fetchFromDB, skipSegmentsHashKey(hashedVideoIDPrefix, service));
|
||||
} else if (hashedVideoIDPrefix.length === 5) {
|
||||
return await QueryCacher.get(fetchFromDB, skipSegmentsLargerHashKey(hashedVideoIDPrefix, service));
|
||||
}
|
||||
|
||||
return await fetchFromDB();
|
||||
@@ -182,19 +256,20 @@ async function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): P
|
||||
const fetchFromDB = () => db
|
||||
.prepare(
|
||||
"all",
|
||||
`SELECT "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "videoDuration", "reputation", "shadowHidden", "timeSubmitted", "description" FROM "sponsorTimes"
|
||||
WHERE "videoID" = ? AND "service" = ? AND "hidden" = 0 ORDER BY "startTime"`,
|
||||
[videoID, service]
|
||||
`SELECT "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "videoDuration", "hidden", "reputation", "shadowHidden", "timeSubmitted", "description" FROM "sponsorTimes"
|
||||
WHERE "videoID" = ? AND "service" = ? ORDER BY "startTime"`,
|
||||
[videoID, service],
|
||||
{ useReplica: true }
|
||||
) as Promise<DBSegment[]>;
|
||||
|
||||
return await QueryCacher.get(fetchFromDB, skipSegmentsKey(videoID, service));
|
||||
}
|
||||
|
||||
// Gets a weighted random choice from the choices array based on their `votes` property.
|
||||
// Gets the best choice from the choices array based on their `votes` property.
|
||||
// amountOfChoices specifies the maximum amount of choices to return, 1 or more.
|
||||
// Choices are unique
|
||||
// If a predicate is given, it will only filter choices following it, and will leave the rest in the list
|
||||
function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOfChoices: number, filterLocked = false, predicate?: (choice: T) => void): T[] {
|
||||
function getBestChoice<T extends VotableObject>(choices: T[], amountOfChoices: number, filterLocked = false, predicate?: (choice: T) => void): T[] {
|
||||
//trivial case: no need to go through the whole process
|
||||
if (amountOfChoices >= choices.length) {
|
||||
return choices;
|
||||
@@ -217,39 +292,22 @@ function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOf
|
||||
}
|
||||
|
||||
//assign a weight to each choice
|
||||
let totalWeight = 0;
|
||||
const choicesWithWeights: TWithWeight[] = filteredChoices.map(choice => {
|
||||
const boost = Math.min(choice.reputation, 4);
|
||||
|
||||
//The 3 makes -2 the minimum votes before being ignored completely
|
||||
//this can be changed if this system increases in popularity.
|
||||
const repFactor = choice.votes > 0 ? Math.max(1, choice.reputation + 1) : 1;
|
||||
const weight = Math.exp(choice.votes * repFactor + 3 + boost);
|
||||
totalWeight += Math.max(weight, 0);
|
||||
const choicesWithWeights: TWithWeight[] = shuffleArray(filteredChoices.map(choice => {
|
||||
const boost = choice.reputation;
|
||||
|
||||
const weight = choice.votes + boost;
|
||||
return { ...choice, weight };
|
||||
});
|
||||
})).sort((a, b) => b.weight - a.weight);
|
||||
|
||||
// Nothing to filter for
|
||||
if (amountOfChoices >= choicesWithWeights.length) {
|
||||
return [...forceIncludedChoices, ...filteredChoices];
|
||||
}
|
||||
|
||||
//iterate and find amountOfChoices choices
|
||||
// Pick the top options
|
||||
const chosen = [...forceIncludedChoices];
|
||||
while (amountOfChoices-- > 0) {
|
||||
//weighted random draw of one element of choices
|
||||
const randomNumber = Math.random() * totalWeight;
|
||||
let stackWeight = choicesWithWeights[0].weight;
|
||||
let i = 0;
|
||||
while (stackWeight < randomNumber) {
|
||||
stackWeight += choicesWithWeights[++i].weight;
|
||||
}
|
||||
|
||||
//add it to the chosen ones and remove it from the choices before the next iteration
|
||||
for (let i = 0; i < amountOfChoices; i++) {
|
||||
chosen.push(choicesWithWeights[i]);
|
||||
totalWeight -= choicesWithWeights[i].weight;
|
||||
choicesWithWeights.splice(i, 1);
|
||||
}
|
||||
|
||||
return chosen;
|
||||
@@ -258,23 +316,26 @@ function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOf
|
||||
async function chooseSegments(videoID: VideoID, service: Service, segments: DBSegment[], useCache: boolean): Promise<DBSegment[]> {
|
||||
const fetchData = async () => await buildSegmentGroups(segments);
|
||||
|
||||
const groups = useCache
|
||||
const groups = useCache && config.useCacheForSegmentGroups
|
||||
? await QueryCacher.get(fetchData, skipSegmentGroupsKey(videoID, service))
|
||||
: await fetchData();
|
||||
|
||||
// Filter for only 1 item for POI categories and Full video
|
||||
let chosenGroups = getWeightedRandomChoice(groups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Full);
|
||||
chosenGroups = getWeightedRandomChoice(chosenGroups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Poi);
|
||||
return chosenGroups.map(//randomly choose 1 good segment per group and return them
|
||||
group => getWeightedRandomChoice(group.segments, 1)[0]
|
||||
let chosenGroups = getBestChoice(groups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Full);
|
||||
chosenGroups = getBestChoice(chosenGroups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Poi);
|
||||
return chosenGroups.map(// choose 1 good segment per group and return them
|
||||
group => getBestChoice(group.segments, 1)[0]
|
||||
);
|
||||
}
|
||||
|
||||
//This function will find segments that are contained inside of eachother, called similar segments
|
||||
//Only one similar time will be returned, randomly generated based on the sqrt of votes.
|
||||
//Only one similar time will be returned, based on its score
|
||||
//This allows new less voted items to still sometimes appear to give them a chance at getting votes.
|
||||
//Segments with less than -1 votes are already ignored before this function is called
|
||||
async function buildSegmentGroups(segments: DBSegment[]): Promise<OverlappingSegmentGroup[]> {
|
||||
const reputationPromises = segments.map(segment =>
|
||||
segment.userID && !db.highLoad() ? getReputation(segment.userID).catch((e) => Logger.error(e)) : null);
|
||||
|
||||
//Create groups of segments that are similar to eachother
|
||||
//Segments must be sorted by their startTime so that we can build groups chronologically:
|
||||
//1. As long as the segments' startTime fall inside the currentGroup, we keep adding them to that group
|
||||
@@ -283,7 +344,8 @@ async function buildSegmentGroups(segments: DBSegment[]): Promise<OverlappingSeg
|
||||
let overlappingSegmentsGroups: OverlappingSegmentGroup[] = [];
|
||||
let currentGroup: OverlappingSegmentGroup;
|
||||
let cursor = -1; //-1 to make sure that, even if the 1st segment starts at 0, a new group is created
|
||||
for (const segment of segments) {
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
const segment = segments[i];
|
||||
if (segment.startTime >= cursor) {
|
||||
currentGroup = { segments: [], votes: 0, reputation: 0, locked: false, required: false };
|
||||
overlappingSegmentsGroups.push(currentGroup);
|
||||
@@ -295,7 +357,7 @@ async function buildSegmentGroups(segments: DBSegment[]): Promise<OverlappingSeg
|
||||
currentGroup.votes += segment.votes;
|
||||
}
|
||||
|
||||
if (segment.userID) segment.reputation = Math.min(segment.reputation, await getReputation(segment.userID));
|
||||
if (segment.userID) segment.reputation = Math.min(segment.reputation, (await reputationPromises[i]) || Infinity);
|
||||
if (segment.reputation > 0) {
|
||||
currentGroup.reputation += segment.reputation;
|
||||
}
|
||||
@@ -359,75 +421,59 @@ function splitPercentOverlap(groups: OverlappingSegmentGroup[]): OverlappingSegm
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Returns what would be sent to the client.
|
||||
* Will respond with errors if required. Returns false if it errors.
|
||||
*
|
||||
* @param req
|
||||
* @param res
|
||||
*
|
||||
* @returns
|
||||
*/
|
||||
async function handleGetSegments(req: Request, res: Response): Promise<Segment[] | false> {
|
||||
async function getSkipSegments(req: Request, res: Response): Promise<Response> {
|
||||
const videoID = req.query.videoID as VideoID;
|
||||
if (!videoID) {
|
||||
res.status(400).send("videoID not specified");
|
||||
return false;
|
||||
}
|
||||
// Default to sponsor
|
||||
// If using params instead of JSON, only one category can be pulled
|
||||
const categories: Category[] = req.query.categories
|
||||
? JSON.parse(req.query.categories as string)
|
||||
: req.query.category
|
||||
? Array.isArray(req.query.category)
|
||||
? req.query.category
|
||||
: [req.query.category]
|
||||
: ["sponsor"];
|
||||
if (!Array.isArray(categories)) {
|
||||
res.status(400).send("Categories parameter does not match format requirements.");
|
||||
return false;
|
||||
return res.status(400).send("videoID not specified");
|
||||
}
|
||||
|
||||
const actionTypes: ActionType[] = req.query.actionTypes
|
||||
? JSON.parse(req.query.actionTypes as string)
|
||||
: req.query.actionType
|
||||
? Array.isArray(req.query.actionType)
|
||||
? req.query.actionType
|
||||
: [req.query.actionType]
|
||||
: [ActionType.Skip];
|
||||
if (!Array.isArray(actionTypes)) {
|
||||
res.status(400).send("actionTypes parameter does not match format requirements.");
|
||||
return false;
|
||||
const parseResult = parseSkipSegments(req);
|
||||
if (parseResult.errors.length > 0) {
|
||||
return res.status(400).send(parseResult.errors);
|
||||
}
|
||||
|
||||
const requiredSegments: SegmentUUID[] = req.query.requiredSegments
|
||||
? JSON.parse(req.query.requiredSegments as string)
|
||||
: req.query.requiredSegment
|
||||
? Array.isArray(req.query.requiredSegment)
|
||||
? req.query.requiredSegment
|
||||
: [req.query.requiredSegment]
|
||||
: [];
|
||||
if (!Array.isArray(requiredSegments)) {
|
||||
res.status(400).send("requiredSegments parameter does not match format requirements.");
|
||||
return false;
|
||||
}
|
||||
|
||||
const service = getService(req.query.service, req.body.service);
|
||||
|
||||
const { categories, actionTypes, requiredSegments, service } = parseResult;
|
||||
const segments = await getSegmentsByVideoID(req, videoID, categories, actionTypes, requiredSegments, service);
|
||||
|
||||
if (segments === null || segments === undefined) {
|
||||
res.sendStatus(500);
|
||||
return false;
|
||||
return res.sendStatus(500);
|
||||
} else if (segments.length === 0) {
|
||||
return res.sendStatus(404);
|
||||
}
|
||||
|
||||
if (segments.length === 0) {
|
||||
res.sendStatus(404);
|
||||
return false;
|
||||
await getEtag("skipSegments", (videoID as string), service)
|
||||
.then(etag => res.set("ETag", etag))
|
||||
.catch(() => ({}));
|
||||
return res.send(segments);
|
||||
}
|
||||
|
||||
async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise<Response> {
|
||||
const videoID = req.query.videoID as VideoID;
|
||||
if (!videoID) {
|
||||
return res.status(400).send("videoID not specified");
|
||||
}
|
||||
|
||||
return segments;
|
||||
const segments = await getSegmentsByVideoID(req, videoID, ["sponsor"] as Category[], [ActionType.Skip], [], Service.YouTube);
|
||||
|
||||
if (segments === null || segments === undefined) {
|
||||
return res.sendStatus(500);
|
||||
} else if (segments.length === 0) {
|
||||
return res.sendStatus(404);
|
||||
}
|
||||
|
||||
// Convert to old outputs
|
||||
const sponsorTimes = [];
|
||||
const UUIDs = [];
|
||||
|
||||
for (const segment of segments) {
|
||||
sponsorTimes.push(segment.segment);
|
||||
UUIDs.push(segment.UUID);
|
||||
}
|
||||
|
||||
return res.send({
|
||||
sponsorTimes,
|
||||
UUIDs,
|
||||
});
|
||||
}
|
||||
|
||||
const filterRequiredSegments = (UUID: SegmentUUID, requiredSegments: SegmentUUID[]): boolean => {
|
||||
@@ -437,25 +483,9 @@ const filterRequiredSegments = (UUID: SegmentUUID, requiredSegments: SegmentUUID
|
||||
return false;
|
||||
};
|
||||
|
||||
async function endpoint(req: Request, res: Response): Promise<Response> {
|
||||
try {
|
||||
const segments = await handleGetSegments(req, res);
|
||||
|
||||
// If false, res.send has already been called
|
||||
if (segments) {
|
||||
//send result
|
||||
return res.send(segments);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof SyntaxError) {
|
||||
return res.status(400).send("Categories parameter does not match format requirements.");
|
||||
} else return res.sendStatus(500);
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
getSegmentsByVideoID,
|
||||
getSegmentsByHash,
|
||||
endpoint,
|
||||
handleGetSegments
|
||||
getSkipSegments,
|
||||
oldGetVideoSponsorTimes
|
||||
};
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { hashPrefixTester } from "../utils/hashPrefixTester";
|
||||
import { getSegmentsByHash } from "./getSkipSegments";
|
||||
import { Request, Response } from "express";
|
||||
import { ActionType, Category, SegmentUUID, VideoIDHash, Service } from "../types/segments.model";
|
||||
import { getService } from "../utils/getService";
|
||||
import { VideoIDHash } from "../types/segments.model";
|
||||
import { Logger } from "../utils/logger";
|
||||
import { parseSkipSegments } from "../utils/parseSkipSegments";
|
||||
import { getEtag } from "../middleware/etag";
|
||||
|
||||
export async function getSkipSegmentsByHash(req: Request, res: Response): Promise<Response> {
|
||||
let hashPrefix = req.params.prefix as VideoIDHash;
|
||||
@@ -11,68 +13,28 @@ export async function getSkipSegmentsByHash(req: Request, res: Response): Promis
|
||||
}
|
||||
hashPrefix = hashPrefix.toLowerCase() as VideoIDHash;
|
||||
|
||||
let categories: Category[] = [];
|
||||
try {
|
||||
categories = req.query.categories
|
||||
? JSON.parse(req.query.categories as string)
|
||||
: req.query.category
|
||||
? Array.isArray(req.query.category)
|
||||
? req.query.category
|
||||
: [req.query.category]
|
||||
: ["sponsor"];
|
||||
if (!Array.isArray(categories)) {
|
||||
return res.status(400).send("Categories parameter does not match format requirements.");
|
||||
}
|
||||
} catch(error) {
|
||||
return res.status(400).send("Bad parameter: categories (invalid JSON)");
|
||||
const parseResult = parseSkipSegments(req);
|
||||
if (parseResult.errors.length > 0) {
|
||||
return res.status(400).send(parseResult.errors);
|
||||
}
|
||||
|
||||
let actionTypes: ActionType[] = [];
|
||||
try {
|
||||
actionTypes = req.query.actionTypes
|
||||
? JSON.parse(req.query.actionTypes as string)
|
||||
: req.query.actionType
|
||||
? Array.isArray(req.query.actionType)
|
||||
? req.query.actionType
|
||||
: [req.query.actionType]
|
||||
: [ActionType.Skip];
|
||||
if (!Array.isArray(actionTypes)) {
|
||||
return res.status(400).send("actionTypes parameter does not match format requirements.");
|
||||
}
|
||||
} catch(error) {
|
||||
return res.status(400).send("Bad parameter: actionTypes (invalid JSON)");
|
||||
}
|
||||
|
||||
let requiredSegments: SegmentUUID[] = [];
|
||||
try {
|
||||
requiredSegments = req.query.requiredSegments
|
||||
? JSON.parse(req.query.requiredSegments as string)
|
||||
: req.query.requiredSegment
|
||||
? Array.isArray(req.query.requiredSegment)
|
||||
? req.query.requiredSegment
|
||||
: [req.query.requiredSegment]
|
||||
: [];
|
||||
if (!Array.isArray(requiredSegments)) {
|
||||
return res.status(400).send("requiredSegments parameter does not match format requirements.");
|
||||
}
|
||||
} catch(error) {
|
||||
return res.status(400).send("Bad parameter: requiredSegments (invalid JSON)");
|
||||
}
|
||||
|
||||
const service: Service = getService(req.query.service, req.body.service);
|
||||
|
||||
// filter out none string elements, only flat array with strings is valid
|
||||
categories = categories.filter((item: any) => typeof item === "string");
|
||||
const { categories, actionTypes, trimUUIDs, requiredSegments, service } = parseResult;
|
||||
|
||||
// Get all video id's that match hash prefix
|
||||
const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, requiredSegments, service);
|
||||
const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, trimUUIDs, requiredSegments, service);
|
||||
|
||||
if (!segments) return res.status(404).json([]);
|
||||
try {
|
||||
const hashKey = hashPrefix.length === 4 ? "skipSegmentsHash" : "skipSegmentsLargerHash";
|
||||
await getEtag(hashKey, hashPrefix, service)
|
||||
.then(etag => res.set("ETag", etag))
|
||||
.catch(/* istanbul ignore next */ () => null);
|
||||
const output = Object.entries(segments).map(([videoID, data]) => ({
|
||||
videoID,
|
||||
segments: data.segments,
|
||||
}));
|
||||
return res.status(output.length === 0 ? 404 : 200).json(output);
|
||||
} catch (e) /* istanbul ignore next */ {
|
||||
Logger.error(`skip segments by hash error: ${e}`);
|
||||
|
||||
const output = Object.entries(segments).map(([videoID, data]) => ({
|
||||
videoID,
|
||||
hash: data.hash,
|
||||
segments: data.segments,
|
||||
}));
|
||||
return res.status(output.length === 0 ? 404 : 200).json(output);
|
||||
return res.status(500).send("Internal server error");
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user