800 Commits

Author SHA1 Message Date
eee7c899ab Merge pull request 'smoothies' (#37) from master into 98
Reviewed-on: #37
2026-07-28 20:30:21 +00:00
c30b3535ae smoothies 2026-07-28 22:30:04 +02:00
6e8ae2f7cb some 98 css additions 2026-07-28 22:26:56 +02:00
90ef78bbf3 Merge pull request 'truncate .' (#36) from master into 98
Reviewed-on: #36
2026-07-28 20:06:46 +00:00
eed8b993e1 truncate . 2026-07-28 22:06:31 +02:00
2eae7f93e5 Merge pull request 'master' (#35) from master into 98
Reviewed-on: #35
2026-07-28 20:02:13 +00:00
9c239769e6 quote truncation 2026-07-28 22:00:58 +02:00
6e07194b27 possible fix for weird ass username display bug 2026-07-28 16:42:18 +02:00
2758f2a72e Merge pull request 'master' (#34) from master into 98
Reviewed-on: #34
2026-07-28 14:26:51 +00:00
866a8003fe fix comment quoting 2026-07-28 16:26:26 +02:00
5ab1a9614a d 2026-07-28 07:47:49 +02:00
e45df6a769 d 2026-07-28 07:46:06 +02:00
99eb9735a1 show pill 2026-07-28 06:38:20 +02:00
b651621cee foobarbaz 2026-07-28 06:30:50 +02:00
d3ce2e38f0 update readme 2026-07-28 03:34:57 +02:00
096786516e 503 2026-07-28 03:11:16 +02:00
ec895a285b onion rules 2026-07-28 03:08:46 +02:00
20aaf183d8 less is more 2026-07-28 03:01:30 +02:00
c0c32ddfe4 Merge pull request 'adding tor switch and update readme' (#33) from master into 98
Reviewed-on: #33
2026-07-27 10:37:04 +00:00
25ab4ba949 adding tor switch and update readme 2026-07-27 12:32:08 +02:00
a6e2689909 Merge pull request 'master' (#32) from master into 98
Reviewed-on: #32
2026-07-27 10:28:47 +00:00
6a52445987 custom location for CF Gate and removing box-shadow 2026-07-27 12:28:06 +02:00
63c39ebe90 deactivate captcha for onion 2026-07-27 10:26:05 +02:00
d1dd088bc6 Merge pull request 'positioning is kinda weird for notic-count' (#31) from master into 98
Reviewed-on: #31
2026-07-26 22:44:49 +00:00
0a21b6c8f8 positioning is kinda weird for notic-count 2026-07-27 00:44:00 +02:00
1bb3dcff21 Merge pull request 'master' (#30) from master into 98
Reviewed-on: #30
2026-07-26 22:23:32 +00:00
a7aabac956 update example gate 2026-07-27 00:22:13 +02:00
9f5510bc04 add custom gate template for private society 2026-07-27 00:12:51 +02:00
fc6749cd11 Merge pull request 'respect config settings' (#29) from master into 98
Reviewed-on: #29
2026-07-26 21:25:01 +00:00
54e2e8871b respect config settings 2026-07-26 23:24:28 +02:00
4d685dff06 Merge pull request 'fix invalid csrf token' (#28) from master into 98
Reviewed-on: #28
2026-07-26 21:20:50 +00:00
c99f3e11d8 fix invalid csrf token 2026-07-26 23:20:20 +02:00
b0053a8de8 Merge pull request 'correctly display url in gate' (#27) from master into 98
Reviewed-on: #27
2026-07-26 21:11:14 +00:00
d14feaf3eb correctly display url in gate 2026-07-26 23:10:41 +02:00
280020c19f Merge pull request 'Revert "adding hardcoded meta for onion"' (#26) from master into 98
Reviewed-on: #26
2026-07-26 21:07:57 +00:00
5e35fd48d4 Revert "adding hardcoded meta for onion"
This reverts commit a07c21f22b.
2026-07-26 23:07:27 +02:00
0d3819c113 Merge pull request 'adding hardcoded meta for onion' (#25) from master into 98
Reviewed-on: #25
2026-07-26 21:05:20 +00:00
a07c21f22b adding hardcoded meta for onion 2026-07-26 23:04:45 +02:00
34d2b62909 Merge pull request 'f' (#24) from master into 98
Reviewed-on: #24
2026-07-26 20:47:21 +00:00
65fb96f675 f 2026-07-26 22:38:10 +02:00
18c898c910 Merge pull request 'break long text in info modal' (#23) from master into 98
Reviewed-on: #23
2026-07-26 20:28:36 +00:00
20a6ffcb04 break long text in info modal 2026-07-26 22:27:57 +02:00
cbfbcb04bf Merge pull request 'master' (#22) from master into 98
Reviewed-on: #22
2026-07-26 20:23:11 +00:00
8518e87c8d fix pagination 2026-07-26 22:09:44 +02:00
a3148848f2 option to advertise onion url 2026-07-26 21:43:39 +02:00
abedf7a789 trying HS 2026-07-26 21:37:07 +02:00
d2ce6f412d Merge pull request 'fix scroller tagging invalid csrf token' (#21) from master into 98
Reviewed-on: #21
2026-07-26 19:22:10 +00:00
e61e24dfe8 fix scroller tagging invalid csrf token 2026-07-26 21:20:00 +02:00
ec4db7a22b Merge pull request 'mobile default tab selection' (#20) from master into 98
Reviewed-on: #20
2026-07-26 18:45:46 +00:00
44af6ae061 mobile default tab selection 2026-07-26 20:45:16 +02:00
c0d70baf83 Merge pull request 'master' (#19) from master into 98
Reviewed-on: #19
2026-07-25 20:50:24 +00:00
0739d72334 remove the fucking animations for new comments 2026-07-25 22:49:27 +02:00
848055446a enabling ipv6 for f0ckm-nginx 2026-07-25 22:38:34 +02:00
122f57eacc update build script 2026-07-25 22:16:15 +02:00
07de9d4488 add f0ck98 theme 2026-07-25 22:14:54 +02:00
88e6b6efb9 persist hide item ratings 2026-07-25 21:52:47 +02:00
eea70ed62e fix quoting 2026-07-25 21:49:11 +02:00
b6c906636c bggg 2026-07-23 21:40:13 +02:00
55b5a0ba9f fuyo 2026-07-23 21:37:22 +02:00
5d60d80fc9 g 2026-07-23 21:35:36 +02:00
4dfb80b149 modern shit 2026-07-23 21:25:38 +02:00
b319f21cd4 favvv 2026-07-23 21:16:25 +02:00
28ed8d985c f0ck95d love 2026-07-23 21:14:32 +02:00
0f5e795793 fuck no 2026-07-23 20:51:06 +02:00
78d14a1b56 daisuki 2026-07-23 20:46:40 +02:00
3f149531da genki 2026-07-23 20:42:49 +02:00
7a4432277d fix tags page 2026-07-19 23:19:47 +02:00
84eee7e13d plastic surgery 2026-07-19 23:05:08 +02:00
2206b3eb86 fix modern layout 2026-07-19 23:01:28 +02:00
5529724982 sunshine daisy 2026-07-19 22:49:13 +02:00
9c6070afff xd 2026-07-19 19:53:37 +02:00
5bfa336773 staleness sucks 2026-07-19 19:44:54 +02:00
517444f9ce ignore svelte for prod 2026-07-19 19:43:21 +02:00
edb92ffa2a vert align top context link 2026-07-19 19:42:32 +02:00
3344064030 tags 2026-07-19 07:37:13 +02:00
e998ba8fc7 chickendöner 2026-07-19 03:30:52 +02:00
6b087efab3 xd 2026-07-19 02:12:58 +02:00
6c9f019646 350 2026-07-19 02:11:05 +02:00
d35437373f possible fix for 502 2026-07-19 00:15:36 +02:00
6efb67f2f5 fuck this auto tagging 2026-07-18 23:44:03 +02:00
fecb0f0b0c tag depths 2026-07-18 23:33:25 +02:00
d89c610dcb gfd 2026-07-18 23:09:28 +02:00
93c042251a set default font via config 2026-07-18 22:16:56 +02:00
990de4b710 vertalign 2026-07-18 22:03:33 +02:00
2f9ad4d349 gfd 2026-07-18 17:21:04 +02:00
701bee7a9a fdsa 2026-07-18 17:15:35 +02:00
4b7fba11ad smaller font = better 2026-07-18 17:11:40 +02:00
6f8eb6f83f g 2026-07-18 17:07:55 +02:00
d78b31633a bbb 2026-07-18 16:52:01 +02:00
294cf2455a hide sidebar yes no 2026-07-18 16:48:55 +02:00
663ba13d18 starto 2026-07-18 16:30:22 +02:00
84c3f1ccda gfsd 2026-07-18 16:18:22 +02:00
4dc7f10ae2 kibort 2026-07-18 16:15:47 +02:00
3ff1edf8bf I do love my keyboard 2026-07-18 16:11:06 +02:00
9ad6eaefec gfsd 2026-07-18 16:01:44 +02:00
d4eb0e52d8 confusion 2026-07-18 15:58:59 +02:00
ce54ed460d fugg :D 2026-07-18 15:40:12 +02:00
cddc763c44 consistency refe 2026-07-18 15:36:49 +02:00
61036558a0 Revert "awesome!!"
This reverts commit 8f0e0d9b3a.
2026-07-18 15:03:02 +02:00
3354baf09f Revert "ff"
This reverts commit c3c485af79.
2026-07-18 15:01:01 +02:00
c3c485af79 ff 2026-07-18 14:59:46 +02:00
8f0e0d9b3a awesome!! 2026-07-18 14:45:46 +02:00
fefd3b6ca6 gdf 2026-07-18 14:37:40 +02:00
5818a0ff39 dragging!! 2026-07-18 14:34:18 +02:00
036a9d372d im pathetic at this point 2026-07-18 14:27:04 +02:00
bef96160db the most pathetic fix to exist yet 2026-07-18 14:24:21 +02:00
a99c17c16b actually useful fix 2026-07-18 14:08:50 +02:00
469f699dd7 button fligger 2026-07-18 13:59:43 +02:00
d3f8c87317 stripping source identifier for IG 2026-07-18 13:54:04 +02:00
568555eab8 62% 2026-07-18 11:18:10 +02:00
b53ff15f91 xd 2026-07-18 01:33:17 +02:00
3eb44c0949 ffff 2026-07-18 01:31:16 +02:00
84d4068e19 youtkakapipibe 2026-07-18 00:47:04 +02:00
9a4aa4585c pipi kaka 2026-07-18 00:33:05 +02:00
98c8b8d097 fg 2026-07-18 00:22:16 +02:00
b7ba21c93a parser :) 2026-07-18 00:22:01 +02:00
5ef0d5c62e I am your father 2026-07-17 23:48:33 +02:00
d13693de01 luke... 2026-07-17 23:42:50 +02:00
a68c8c1618 eridi 2026-07-17 23:39:36 +02:00
3440f98bcd fdsa 2026-07-17 23:25:14 +02:00
298f12305e dynamic köpfe 2026-07-17 19:36:12 +02:00
ba36316fcb 700px! 2026-07-17 18:53:27 +02:00
4ea3db078f jfg 2026-07-17 18:49:14 +02:00
7f171d04d5 j 2026-07-17 18:46:22 +02:00
6da7951b7c user tags 2026-07-17 18:07:25 +02:00
a06beef458 fix profile comment page image attachments 2026-07-17 17:57:46 +02:00
5388813da9 fds 2026-07-17 17:50:58 +02:00
a1f1dd4523 hide ratings 2026-07-17 17:48:02 +02:00
ca74655a0e gfsd 2026-07-17 17:39:11 +02:00
caebbbe101 all i ever wanted 2026-07-17 17:16:25 +02:00
e66c4bf43b fdsa 2026-07-17 17:07:39 +02:00
e4c525cb7d margin 2026-07-17 17:06:04 +02:00
48b86e8003 fdas 2026-07-17 17:03:46 +02:00
cba0f77732 bvdx 2026-07-17 17:01:49 +02:00
2ff53b6513 profile update 2026-07-17 16:56:40 +02:00
0c0f0fd2a9 gf 2026-07-17 16:28:55 +02:00
5256a9eb07 gfd 2026-07-17 13:00:46 +02:00
41d18bbc54 gfsd 2026-07-17 12:55:11 +02:00
7fe2192142 center top 2026-07-17 12:49:08 +02:00
843acab8b3 sss 2026-07-17 12:34:29 +02:00
a6193c13fb video comments on profile comment page 2026-07-17 11:45:46 +02:00
e219bc5573 gfsd 2026-07-17 11:45:01 +02:00
32a7b1afac gfsd 2026-07-17 11:33:51 +02:00
994b607ce7 gfsd 2026-07-17 11:28:58 +02:00
a10db31534 gfdsgsd 2026-07-17 11:24:23 +02:00
5d775fd00c fdsafsda 2026-07-17 11:15:05 +02:00
8043830b88 fdsa 2026-07-17 10:53:51 +02:00
cfd9620be7 gfsd 2026-07-17 10:19:49 +02:00
09ffe600d6 gfds 2026-07-17 10:16:04 +02:00
3601346895 fugg xd 2026-07-17 10:11:20 +02:00
2719ec5e57 fuck box shadow 2026-07-17 10:07:51 +02:00
7ae0392d09 gfsd 2026-07-17 10:06:30 +02:00
dd73ae0eb6 nnn 2026-07-17 10:00:04 +02:00
5f9453c6e5 add impact to gitignore 2026-07-17 09:58:33 +02:00
09a2406b5a c 2026-07-17 09:58:00 +02:00
190d789618 f 2026-07-17 09:55:22 +02:00
1577e63e9e prevent mobile panning and zooming 2026-07-17 09:32:54 +02:00
c45870bf24 mona 2026-07-17 09:26:32 +02:00
78aee03025 gfds 2026-07-17 09:23:18 +02:00
db3da87c38 better profiles 2026-07-17 09:20:32 +02:00
9f92841ea3 gf 2026-07-17 08:52:39 +02:00
ede9e63e8a xd 2026-07-17 08:48:17 +02:00
2e9bd701b1 yeah yeah power un dat 2026-07-17 08:45:20 +02:00
6bc882e75a xd 2026-07-17 08:41:18 +02:00
36996d20d5 gfd 2026-07-17 08:31:37 +02:00
1e8fb4b2b6 tag is too long lmao 2026-07-17 07:58:25 +02:00
04fa79b6bf ghostriders in the sky 2026-07-17 07:55:14 +02:00
2ce3e4535e patheticgorjgof 2026-07-17 00:18:49 +02:00
d9783abffa her 2026-07-17 00:12:21 +02:00
b27d85aa27 pathetische scheiße 2026-07-17 00:09:44 +02:00
266068b4b4 gfsdgsd 2026-07-17 00:04:56 +02:00
bee5f00e76 patheticbkfojbgo 2026-07-17 00:02:37 +02:00
d005aa5d9c pathetic over 9000000000 2026-07-16 23:58:54 +02:00
5d490cf134 pathetic 2026-07-16 23:45:21 +02:00
f6e9e13f4e pathetic sein father 2026-07-16 22:56:07 +02:00
8d9fa3fafd another pathetic try to fix the sidebar shit 2026-07-16 22:51:16 +02:00
353fc382de banner stuff 2026-07-16 22:46:25 +02:00
9608398a8e banner fix for change? 2026-07-16 22:34:32 +02:00
ce5dfa72c6 perstistency... 2026-07-16 22:16:00 +02:00
29d144920a persistency mismatch 2026-07-16 22:13:11 +02:00
91125372c8 another sad try to make the sidebar better 2026-07-16 21:55:09 +02:00
75161e4957 hgdfhf 2026-07-16 21:44:49 +02:00
813a0a066e live update banner udpates 2026-07-16 21:37:28 +02:00
e416575419 gfd 2026-07-16 21:30:29 +02:00
286b6beaf8 fix memes 2026-07-16 21:26:13 +02:00
b370510ecd comment preview foobar 2026-07-16 21:16:32 +02:00
7e2ef4fc0f Revert "hghd"
This reverts commit 74d5ff2e03.
2026-07-16 20:15:52 +02:00
1a942066ec hgfhfd 2026-07-16 19:55:14 +02:00
74d5ff2e03 hghd 2026-07-16 19:48:24 +02:00
7e5f7366d1 jhfg 2026-07-16 19:45:50 +02:00
9c9530e8c9 h 2026-07-16 19:41:30 +02:00
b19cf9ebca gfdgsdf 2026-07-16 19:37:00 +02:00
e6562ecd90 hgfdhhhfg 2026-07-16 19:33:04 +02:00
ad06ca5956 hgfh 2026-07-16 19:23:39 +02:00
43742ecdb1 gfsd 2026-07-16 19:22:37 +02:00
2350a97199 fdsafas 2026-07-16 19:17:43 +02:00
b51b8aa11c right click for default tab favorites 2026-07-16 19:16:03 +02:00
bec1d1c6d1 fds 2026-07-16 19:09:18 +02:00
6aa58c0b74 halo 2026-07-16 19:01:39 +02:00
21706d4a93 gfsd 2026-07-16 18:40:12 +02:00
589046fed5 goldener reiter 2026-07-16 18:35:15 +02:00
05ed241db0 fdsa 2026-07-16 18:32:13 +02:00
d44bc4d2bd gfsd 2026-07-16 18:28:07 +02:00
feb515b740 f 2026-07-16 18:25:36 +02:00
7c8cb2df78 fdsfasd 2026-07-16 18:19:21 +02:00
63837fe86f fdsafdsa 2026-07-16 18:16:54 +02:00
fc237ab71a gsdf 2026-07-16 18:14:32 +02:00
360dc1db06 fdasfasd 2026-07-16 18:10:19 +02:00
77741a55a8 gfsd 2026-07-16 18:06:53 +02:00
ef5fa4a6bc danmaku 2026-07-16 18:01:36 +02:00
bf66a6d276 tt 2026-07-16 17:56:37 +02:00
ce852544d1 hgfd 2026-07-16 17:52:02 +02:00
6a117eeeb3 foo 2026-07-16 17:40:07 +02:00
a8584491b7 metaextract 2026-07-16 17:23:00 +02:00
92c7fc4d6e fix yt metadata extraction once and for all (hopefully) 2026-07-16 17:20:05 +02:00
6015befffc adding tor to docker-compose for easier and better integrated proxy support 2026-07-16 17:06:40 +02:00
4be150ce44 ghost riders 2026-07-16 16:49:43 +02:00
ae9bc17b4a hfghf 2026-07-16 16:46:43 +02:00
8dc0854de2 fdas 2026-07-16 16:39:37 +02:00
de7102ed03 fd 2026-07-16 16:18:57 +02:00
11d4b5acf9 f 2026-07-16 10:13:28 +02:00
2513bf2db9 ficket euch 2026-07-16 09:05:56 +02:00
336a759d45 ^_^ 2026-07-16 09:00:58 +02:00
0af53bf08a scrololololololol 2026-07-16 08:47:24 +02:00
4d19837645 vert 2026-07-16 08:42:36 +02:00
f740fdd404 fdsa 2026-07-16 08:30:00 +02:00
e2a8c86989 fix layout legacy 2026-07-16 08:28:07 +02:00
27ca317eb3 to the good old days 2026-07-16 08:05:39 +02:00
797b5acf86 pauer un dattt 2026-07-16 08:03:28 +02:00
cd868eaea6 beat it 2026-07-16 07:57:26 +02:00
076da81f02 banner v2 2026-07-16 07:51:16 +02:00
1a99e58d84 add user banners :) 2026-07-16 07:22:03 +02:00
41ac99cd5c fdsfdsa 2026-07-16 06:24:55 +02:00
efe3be141e fdsfasd 2026-07-16 06:19:40 +02:00
4eba51c887 yeah power un dat 2026-07-16 06:17:05 +02:00
4daa7c2dfc fuck this shit 2026-07-16 06:15:01 +02:00
d04641cb3e fdsa 2026-07-16 06:04:53 +02:00
6014c62ad8 hgdf 2026-07-16 06:02:54 +02:00
31ed3b5db9 fav fix! 2026-07-16 06:01:38 +02:00
a9b715165e finally xD 2026-07-16 05:54:14 +02:00
d29695bb7e hfg 2026-07-16 05:37:05 +02:00
8374c464cd fdsa 2026-07-16 05:35:29 +02:00
514d6597cf vfd 2026-07-16 05:31:12 +02:00
6f8a809637 22222 2026-07-16 05:27:49 +02:00
9fb0a24488 autism 2026-07-16 05:23:29 +02:00
e9f2929bf6 fdsa 2026-07-16 05:14:49 +02:00
b2f33cf384 400px lol 2026-07-16 05:10:13 +02:00
4123c0b377 ff 2026-07-16 05:08:26 +02:00
3aa1acde0a akzeptabler zwischenstand 2026-07-16 05:03:13 +02:00
7b5ae3533f tg patch 2026-07-16 04:17:12 +02:00
d53794f9bf dms fav picker 2026-07-16 04:09:51 +02:00
6a3b9675b8 f 2026-07-16 04:06:02 +02:00
9806052d5c smooth 2026-07-16 04:04:39 +02:00
f48808237e fds 2026-07-16 04:01:31 +02:00
6c07bdcb33 hi 2026-07-16 03:59:31 +02:00
4ffe83fa9d fd 2026-07-16 03:51:03 +02:00
e2c277086f fettfinger xd 2026-07-16 03:47:34 +02:00
bc44039fa9 fdas 2026-07-16 03:45:33 +02:00
2c169903f3 fdas 2026-07-16 03:42:58 +02:00
13fe1145d5 mobile baddne 2026-07-16 03:41:14 +02:00
8e62d81d7b favven unso 2026-07-16 03:37:53 +02:00
7d8a7587a7 fdsafasd 2026-07-16 02:43:43 +02:00
468107867d update schema 2026-07-16 02:43:15 +02:00
87a95c7f93 pollz 2026-07-16 02:39:08 +02:00
56220e5b7e hgfhgd 2026-07-16 02:34:32 +02:00
bdbd60070c gfsd 2026-07-16 02:27:36 +02:00
a2875bf39b db 2026-07-16 02:24:16 +02:00
698f693700 hdf 2026-07-16 02:16:17 +02:00
93e8a39a40 dd 2026-07-16 02:12:58 +02:00
0b22a1b590 f 2026-07-16 02:03:17 +02:00
5facee3ccd faaaaa 2026-07-16 02:00:57 +02:00
e82471924a favorites tab for emojis 2026-07-16 01:51:05 +02:00
aa6e76dad8 fav tab 2026-07-16 01:38:57 +02:00
08d65532b1 fuck hover 2026-07-16 01:07:57 +02:00
c5fd833790 better sticker renaming 2026-07-16 01:05:10 +02:00
48a2302053 video sticker preview img 2026-07-16 01:02:20 +02:00
e94c4a439e ff 2026-07-16 00:57:31 +02:00
64ca845ec5 renaming 2026-07-16 00:54:16 +02:00
d3550f9648 unshittifying preview 2026-07-16 00:33:05 +02:00
789a18aef7 tg stickers fill available space 2026-07-16 00:29:17 +02:00
302f7c62ad width :D 2026-07-16 00:20:17 +02:00
494a990ad4 auto height 2026-07-16 00:18:22 +02:00
00a2f48fbf tg sticker v5.6 2026-07-16 00:12:07 +02:00
a1f80d7407 tg sticker v5.5 2026-07-16 00:09:58 +02:00
d94831db0f tg stickers v5.4 2026-07-15 23:51:10 +02:00
082f8669fb tg stickers v5.3 2026-07-15 23:45:55 +02:00
f9943bd47a tg stickers v5.2 2026-07-15 23:34:00 +02:00
805c97b8e4 tg stickers v5.1 2026-07-15 23:28:56 +02:00
a2b5a3f349 tg stickers v5 2026-07-15 23:20:43 +02:00
83c92262d8 tg stickers v4 2026-07-15 23:13:48 +02:00
ab9f2daaf9 tg stickers v3 2026-07-15 23:10:35 +02:00
46d4b49157 tg stickers v2 2026-07-15 23:04:43 +02:00
a7c811025e telegram stickers v1 2026-07-15 22:56:26 +02:00
afc776d948 mode reminder for lazy peeps 2026-07-15 22:04:20 +02:00
8778dbf3da tg 2026-07-15 19:45:21 +02:00
c4ef2bfbca tarkock 2026-07-15 19:38:00 +02:00
bdb6be1702 telegram 2026-07-15 19:33:49 +02:00
2338858254 yt metadata 2026-07-15 19:12:28 +02:00
ca0f6f19cc maji manji 2026-07-15 19:07:19 +02:00
c2cb897190 d 2026-07-15 19:03:40 +02:00
5a10649c57 1 2026-07-15 19:03:06 +02:00
563d90dbbc 1.2 2026-07-15 18:59:34 +02:00
d61b05195b emoji dms 2026-07-15 18:55:36 +02:00
3b5f646422 sidebar bigger font size 2026-07-15 18:52:48 +02:00
98c2aa3b7f metayt 2026-07-15 18:49:05 +02:00
5ef981d35b power un dat 2026-07-15 18:32:14 +02:00
d9b5b95f54 uga buga kaka 2026-07-15 18:27:45 +02:00
3bbee6029f repost check for upload 2026-07-15 18:03:06 +02:00
f057ea29d6 QoL enhacement 2026-07-15 17:52:20 +02:00
d53a635495 thubmnail fix for vid preview in shitpost mode upload 2026-07-15 17:45:39 +02:00
9e9fd4adf3 fix chrome shitpost mode video preview in upload 2026-07-15 17:41:58 +02:00
a613d01873 xd 2026-07-15 17:17:00 +02:00
c7edcfdfc2 xd wrapper 2026-07-15 17:15:26 +02:00
aae79eb56a emoji sizes 2026-07-15 17:13:25 +02:00
782c50ff1a chromium is shit 2026-07-15 17:03:12 +02:00
6a8a8a6bda fuck chrome 2026-07-15 16:49:00 +02:00
2fa7e01b3a fuck chromium! its a shit browser 2026-07-15 16:42:23 +02:00
8b003c4d57 Revert "apparently chrome is a shit browser"
This reverts commit f6f47fcbbe.
2026-07-15 16:32:01 +02:00
f6f47fcbbe apparently chrome is a shit browser 2026-07-15 16:30:07 +02:00
ac7bb2e699 g 2026-07-15 16:25:55 +02:00
01475c42f5 pipi kaka 2026-07-15 16:21:55 +02:00
71b06bc64a f 2026-07-15 15:40:25 +02:00
b6e92cd6f2 optimize video load 2026-07-15 14:20:48 +02:00
581d35c983 testing html cache 2026-07-15 14:08:23 +02:00
9fc8741f9c no user select for rating label 2026-07-15 13:56:36 +02:00
24f0ec44ec restore sf ratings on items 2026-07-15 13:30:21 +02:00
7368339bae gfds 2026-07-15 08:34:25 +02:00
0ea1995de5 h 2026-07-15 08:33:08 +02:00
6d73cfcea9 tweaking meme gen 2026-07-15 07:55:23 +02:00
dd5f3dc8b9 smaller char count 2026-07-15 00:39:50 +02:00
d80aa3b96b limit sidebar comments to 20 2026-07-14 23:59:54 +02:00
1c7bf20d6d f 2026-07-14 23:55:15 +02:00
92e6b7c450 css fix 2026-07-14 23:53:23 +02:00
1e11426043 makign url upload better 2026-07-14 21:37:26 +02:00
b5d688ec0d url upload better 2026-07-14 21:05:02 +02:00
0c6132a2b9 testing lazyload shit 2026-07-14 20:58:09 +02:00
9092bc8a98 testing lazyload stuff 2026-07-14 20:56:17 +02:00
8b18c4c27f test 2026-07-14 20:53:32 +02:00
e05b60cee8 change grid rendering 2026-07-14 20:45:33 +02:00
d92004ba3a :) 2026-07-14 20:34:43 +02:00
0129face77 removing border for alternative infobox 2026-07-14 20:27:10 +02:00
cdd7fa97d5 adding some QoL Css fixes 2026-07-14 20:24:28 +02:00
965573a80f add new v0ck feature 2026-07-14 19:12:15 +02:00
4a491f404c fix for item page 2026-07-14 19:06:40 +02:00
c5796744e7 arrow keys for changing volume of video 2026-07-14 18:20:36 +02:00
78879bd028 f is for fullscreen 2026-07-14 18:16:01 +02:00
4f4e3bada3 do not try to preview gifs in thumbs 2026-07-14 18:05:40 +02:00
ca39b3cfca gfdgsd 2026-07-14 18:00:55 +02:00
0488b187fc gfsd 2026-07-14 18:00:33 +02:00
56e17a8e27 fuck chrome 2026-07-14 18:00:19 +02:00
ef531bf6a2 Revert "fixing quicknav jumps in settings"
This reverts commit f7a6104896.
2026-07-14 18:00:19 +02:00
0a979ddc78 j 2026-07-13 05:51:32 +02:00
6a8986b160 lets see 2026-07-13 05:46:08 +02:00
bc85891027 fuck skeletons 2026-07-13 05:42:41 +02:00
aeb9868507 f 2026-07-13 05:40:08 +02:00
55036fcc0d jhtztjr 2026-07-13 05:35:05 +02:00
90994017b0 pb! 2026-07-13 05:16:50 +02:00
d9c2f7cdcc less ajax sometimes can be more 2026-07-13 05:14:37 +02:00
f486123cb7 jfg 2026-07-12 22:07:27 +02:00
9c6db72d5b jhfg 2026-07-12 21:41:42 +02:00
763ef32275 Revert "chromium"
This reverts commit 2492ca8c25.
2026-07-12 21:15:27 +02:00
0afd5bf7f6 Revert "uga aga pipi kaka"
This reverts commit ecdf54a894.
2026-07-12 21:15:26 +02:00
b7b799b17d Revert "pipi kaka uga aga"
This reverts commit 587ba77f71.
2026-07-12 21:15:25 +02:00
d3d7f2209f Revert "ef"
This reverts commit 1762687fc8.
2026-07-12 21:15:25 +02:00
e7f76af63d Revert "jgfd"
This reverts commit 11bf73acc2.
2026-07-12 21:15:24 +02:00
0731f607b1 Revert "tzrf"
This reverts commit ca702c9e5d.
2026-07-12 21:15:23 +02:00
3672ee8afb Revert "I hate chrome"
This reverts commit 4b0abfb551.
2026-07-12 21:15:23 +02:00
68fd1050c2 Revert "chrome is the shittiest browser ever made, fuck this!"
This reverts commit 6c926a2374.
2026-07-12 21:15:22 +02:00
36d9dca211 Revert "jhfg"
This reverts commit 38f5c9d6fe.
2026-07-12 21:15:22 +02:00
d75e5fb218 Reapply "jhfg"
This reverts commit 9898a0704b.
2026-07-12 21:15:21 +02:00
1c88a28520 Reapply "chrome is the shittiest browser ever made, fuck this!"
This reverts commit e0e6ebec29.
2026-07-12 21:15:20 +02:00
e4bac101e8 Reapply "I hate chrome"
This reverts commit b06a8faabd.
2026-07-12 21:15:20 +02:00
ecb49d65e7 Reapply "tzrf"
This reverts commit a9ca344955.
2026-07-12 21:15:19 +02:00
2c93fedaed Reapply "jgfd"
This reverts commit 8294d9626f.
2026-07-12 21:15:19 +02:00
7855db7b09 Reapply "ef"
This reverts commit 9e579d2cdd.
2026-07-12 21:15:18 +02:00
d7af8a98d8 Reapply "pipi kaka uga aga"
This reverts commit d4273ed515.
2026-07-12 21:15:17 +02:00
db44e04dba Reapply "uga aga pipi kaka"
This reverts commit 3856f752bd.
2026-07-12 21:15:17 +02:00
656f3ea4b1 Reapply "chromium"
This reverts commit 5b85f5de2e.
2026-07-12 21:15:16 +02:00
8c0a3bdaaa Revert "fuck chrome"
This reverts commit 9473293ed2.
2026-07-12 21:15:16 +02:00
41a95c8e0d Revert "hgdf"
This reverts commit 1a314ce752.
2026-07-12 21:15:15 +02:00
fbacc9ae56 Revert "fgfsd"
This reverts commit db08e5d3c9.
2026-07-12 21:15:14 +02:00
f2e75389e6 Revert "jfg"
This reverts commit d3aa1d0b69.
2026-07-12 21:15:13 +02:00
93338f877b Revert "hgfhhdf"
This reverts commit eb14192ee8.
2026-07-12 21:15:13 +02:00
a2dcc1d622 Revert "kgh"
This reverts commit a978ddcba6.
2026-07-12 21:15:11 +02:00
a978ddcba6 kgh 2026-07-12 20:59:42 +02:00
eb14192ee8 hgfhhdf 2026-07-12 20:54:18 +02:00
d3aa1d0b69 jfg 2026-07-12 20:51:16 +02:00
db08e5d3c9 fgfsd 2026-07-12 20:47:10 +02:00
1a314ce752 hgdf 2026-07-12 20:34:17 +02:00
9473293ed2 fuck chrome 2026-07-12 20:29:16 +02:00
5b85f5de2e Revert "chromium"
This reverts commit 2492ca8c25.
2026-07-12 20:22:20 +02:00
3856f752bd Revert "uga aga pipi kaka"
This reverts commit ecdf54a894.
2026-07-12 20:22:19 +02:00
d4273ed515 Revert "pipi kaka uga aga"
This reverts commit 587ba77f71.
2026-07-12 20:22:18 +02:00
9e579d2cdd Revert "ef"
This reverts commit 1762687fc8.
2026-07-12 20:22:17 +02:00
8294d9626f Revert "jgfd"
This reverts commit 11bf73acc2.
2026-07-12 20:22:17 +02:00
a9ca344955 Revert "tzrf"
This reverts commit ca702c9e5d.
2026-07-12 20:22:16 +02:00
b06a8faabd Revert "I hate chrome"
This reverts commit 4b0abfb551.
2026-07-12 20:22:15 +02:00
e0e6ebec29 Revert "chrome is the shittiest browser ever made, fuck this!"
This reverts commit 6c926a2374.
2026-07-12 20:22:11 +02:00
9898a0704b Revert "jhfg"
This reverts commit 38f5c9d6fe.
2026-07-12 20:21:55 +02:00
38f5c9d6fe jhfg 2026-07-12 20:15:39 +02:00
6c926a2374 chrome is the shittiest browser ever made, fuck this! 2026-07-12 20:13:01 +02:00
4b0abfb551 I hate chrome 2026-07-12 20:06:49 +02:00
ca702c9e5d tzrf 2026-07-12 20:02:11 +02:00
11bf73acc2 jgfd 2026-07-12 19:59:22 +02:00
1762687fc8 ef 2026-07-12 19:56:39 +02:00
587ba77f71 pipi kaka uga aga 2026-07-12 19:52:43 +02:00
ecdf54a894 uga aga pipi kaka 2026-07-12 19:50:25 +02:00
2492ca8c25 chromium 2026-07-12 19:46:17 +02:00
f7a6104896 fixing quicknav jumps in settings 2026-07-12 19:21:30 +02:00
b96f22be8a add option to create users from admin dashboard and give or take permissions via dashboard 2026-07-12 19:15:37 +02:00
59120ed96e altering the url uploads 2026-07-12 19:00:58 +02:00
6adfb55581 update url uploads 2026-07-12 18:46:09 +02:00
06ced46db1 fix sharex 2 2026-07-12 18:05:37 +02:00
c48a644bb9 fix sharex 2026-07-12 17:37:57 +02:00
88b25ab251 fix unbanning for inactivity ban resets last seen 2026-07-12 17:23:08 +02:00
8bb9a14773 adding parallel file computing for better api performance and upload speed and responses 2026-07-12 17:15:59 +02:00
d424b24221 add support for uploading archives 2026-07-12 17:03:19 +02:00
ab1ea7b368 soy2 2026-06-29 23:50:03 +02:00
6f2afc992f soy 2026-06-29 22:27:29 +02:00
81c0afc534 fix user api keys in schema 2026-06-29 19:09:12 +02:00
977cab8ad2 adding working metadata extract butto for yt embeds 2026-06-21 20:26:44 +02:00
f190ff073a add automatic inactivity bans 2026-06-21 15:47:36 +02:00
e30ead0174 nsfp manager #1 2026-06-19 14:52:02 +02:00
17ee7a3b2d add counter how many items are hidden from public 2026-06-19 14:47:08 +02:00
8a24564cd9 add nsfp tag manager 2026-06-19 14:44:56 +02:00
06564af203 QoL v0ck and tagging 2026-06-19 14:20:15 +02:00
c051df18c2 fix rehost button mutation 2026-06-19 14:13:52 +02:00
78d08aa751 comment input form validation required 2026-06-19 14:07:40 +02:00
a748cca833 v0ck QoL 2026-06-19 14:02:20 +02:00
1b8860d8ff add phash repost detection 2026-06-13 19:09:36 +02:00
4c742aaf66 bump nginx upload size 2026-06-13 16:51:36 +02:00
6b6ed9d42b add direct url to upload response via api 2026-06-13 16:11:10 +02:00
9df81105e2 update private_society to allow direct urls 2026-06-13 16:05:54 +02:00
fb2489812e api upload min tags 2026-06-13 15:16:12 +02:00
d29edd735e umlaut fix 2026-06-12 10:30:41 +02:00
f06a7ffe55 less aggressive html sanitize 2026-06-12 03:02:00 +02:00
8b29ee6722 hfgd 2026-06-12 02:58:53 +02:00
34ed0e4621 fixing about/terms/rules pages 2026-06-12 02:56:02 +02:00
83f3980300 add flash fullscreen button 2026-06-12 01:58:28 +02:00
7b599e3afa update attachment logic 2026-06-12 01:48:04 +02:00
7dcd7005e4 sidebar hidden modern layout same size 2026-06-12 01:30:22 +02:00
c093e9703d ruffle scrolling 2026-06-12 01:12:23 +02:00
9ca60629a0 stabilizing layout 2026-06-12 01:04:41 +02:00
075adcc8c6 center content in modern layout 2026-06-12 00:54:01 +02:00
5f2fe0c732 scroll to file in shitpost mode 2026-06-12 00:38:17 +02:00
28f35861c3 cccc 2026-06-10 10:27:14 +02:00
4e45e0fd66 turn splash screen back on and fix regen script 2026-06-08 20:05:04 +02:00
69e90f8d2d overhaul rethumbing flashs 2026-06-08 16:37:15 +02:00
c615676465 mobile qol 2026-06-08 15:09:38 +02:00
bdc78fc5a5 ++++++ 2026-06-08 14:09:50 +02:00
7fb049e1ed video shortcuts 2026-06-08 13:53:55 +02:00
7f71285c80 texttop 2026-06-08 13:50:41 +02:00
a6997bc4b4 add clickable video timestamps 2026-06-08 13:43:28 +02:00
219cab1b03 j 2026-06-08 13:34:20 +02:00
8c3556fd68 QoL for images 2026-06-08 13:29:33 +02:00
c9892ec62f qol 2026-06-08 13:16:47 +02:00
018428d236 more blur bg! 2026-06-08 13:05:31 +02:00
f4dcfe0e50 arab bunny party 2026-06-08 09:28:47 +02:00
25a878cb7a bunny party 2026-06-08 09:26:51 +02:00
2f048c0105 pipi kaka :D 2026-06-05 12:58:57 +02:00
e3822254a3 0000 2026-06-05 12:47:44 +02:00
5b193bc001 ererere 2026-06-04 21:01:34 +02:00
f36c10b428 gfdhfgd 2026-06-04 20:55:41 +02:00
4943a87e13 hgf 2026-06-04 20:42:22 +02:00
a868e9f94b fix notis 2026-06-04 20:29:30 +02:00
e281484b8a notification thumbnails according to rating blurred or unblurred 2026-06-04 15:44:57 +02:00
39dfcad52f f 2026-06-04 13:47:32 +02:00
fe3af86c87 yt fix #2 2026-06-03 13:43:26 +02:00
f5101da85c fix broken yt dests... 2026-06-03 13:37:41 +02:00
d5de02511b add option to have public nsfw/nsfl 2026-06-03 13:07:24 +02:00
adc8431522 update emoji manager 2026-06-03 12:50:21 +02:00
d30642ca4a QoL fixes 2026-06-03 12:25:57 +02:00
5bb86f7028 Testing: fixing user comments page and profile respects now sidebar width 2026-06-03 11:08:37 +02:00
33411fc5ed adding missing stuff for fresh deployments 2026-06-03 10:58:32 +02:00
e72f9a6ef3 QoL fixes 2026-06-03 08:54:56 +02:00
066fa97c43 rrrrrrrrr 2026-06-02 16:55:59 +02:00
dceadf7113 jgh 2026-06-02 16:45:21 +02:00
a0ef658684 new filenames + backfill 2026-06-02 16:35:34 +02:00
2c88953d97 jhgf 2026-06-02 10:26:53 +02:00
9d54e03ae0 bhgds 2026-06-02 07:54:45 +02:00
c20e54c11b gfds 2026-06-01 22:27:23 +02:00
bbbb4397f0 padding 2026-06-01 18:26:01 +02:00
0bbbf5ce13 ölkj 2026-06-01 18:21:46 +02:00
7ebb74a295 g 2026-06-01 13:48:52 +02:00
0dd1f30777 nginx 2026-06-01 13:40:11 +02:00
2bc0f9c5fd jghf 2026-06-01 13:28:44 +02:00
a8ef68fee6 update nginx compose 2026-06-01 13:24:26 +02:00
39e6d58e18 add approval message 2026-06-01 13:14:31 +02:00
1557d59300 nginx test 2026-06-01 11:32:15 +02:00
1df8caa940 adding nginx reverse proxy in docker 2026-06-01 11:09:45 +02:00
0f69365b02 ffmpeg fallback for specific vp9 videos 2026-06-01 10:33:04 +02:00
8d8416e650 add tooltips for sidebar 2026-06-01 10:26:26 +02:00
412995ece6 removing alt=av 2026-06-01 10:20:30 +02:00
df3405ac9b f 2026-06-01 08:43:46 +02:00
9146e37039 update readme 2026-06-01 08:43:02 +02:00
bb6322e187 hgfd 2026-06-01 08:30:50 +02:00
064bd51c64 gdf 2026-06-01 08:10:37 +02:00
f6de7f72cf hngfdhfgd 2026-05-31 22:08:02 +02:00
d594ac2edd hgfdhgfd 2026-05-31 22:02:38 +02:00
09fcf8d8ec ghfd 2026-05-31 21:52:46 +02:00
1efd3b18ad errrr 2026-05-31 20:51:24 +02:00
b2128ef0f8 jjj 2026-05-31 20:38:45 +02:00
8e4e40d92f update example config 2026-05-31 20:26:13 +02:00
e0c29f203b gfdsgfds 2026-05-31 19:54:34 +02:00
994039370c scroll to top button for mobile 2026-05-31 18:48:45 +02:00
08cdada5bc silent scroll :) 2026-05-31 18:37:45 +02:00
8a3a77d273 gfds 2026-05-31 18:24:22 +02:00
235f1b6d14 better timestamps 2026-05-31 18:10:35 +02:00
52a18acf40 gfdsgfds 2026-05-31 17:30:44 +02:00
c8f0982f22 hgfd 2026-05-31 17:22:07 +02:00
1f97701779 jfgh 2026-05-31 17:19:10 +02:00
f863580f20 jhgf 2026-05-31 17:10:30 +02:00
d299117eb0 jhgf 2026-05-31 17:07:46 +02:00
62588a3a4b hhhhhhhhh 2026-05-31 17:00:57 +02:00
d50a8b5965 gfds 2026-05-31 16:56:39 +02:00
ec95f548ff obermainbrücke 2026-05-31 16:55:30 +02:00
379298acc7 hfgd 2026-05-31 16:42:44 +02:00
7b80a3434c gfds 2026-05-31 16:03:48 +02:00
23427f009f gfds 2026-05-31 15:57:55 +02:00
c4a571a714 gfds 2026-05-31 12:25:35 +02:00
db6344d055 gfds 2026-05-31 12:23:14 +02:00
f97de44a0c gfds 2026-05-31 12:21:19 +02:00
448efc69f8 hgfd 2026-05-31 12:18:59 +02:00
c2cb67c51c hgfdhfd 2026-05-31 12:18:50 +02:00
89548e1105 magnet und hydrodynamik 2026-05-31 12:17:12 +02:00
7c23c646fe gfdsgdfs 2026-05-31 12:15:36 +02:00
7671e8c0cf gfds 2026-05-31 12:14:43 +02:00
7a57f4897f fdfdd 2026-05-31 06:59:05 +02:00
0b89e446e7 hausdavid 2026-05-31 06:56:45 +02:00
83bf04e965 hackinga to tha gato 2026-05-31 06:21:42 +02:00
69bf968a4b hgfdhgfdhd 2026-05-30 18:59:07 +02:00
85cf4e0fc6 long covid 2026-05-30 18:44:27 +02:00
86a08bb76e gfdsgdfsgdfs 2026-05-30 17:33:53 +02:00
73e328c0b6 gfds 2026-05-30 17:21:30 +02:00
57c12057d9 gfds 2026-05-30 17:05:16 +02:00
0ae82ce433 huo 2026-05-30 13:19:12 +02:00
067f202c08 hgfd 2026-05-30 13:07:38 +02:00
9177b993fc jhgf 2026-05-30 12:55:22 +02:00
1a0a5d7679 fdas 2026-05-30 12:50:15 +02:00
ae2a9b76cb hgfd 2026-05-30 12:38:47 +02:00
47f1b5bb41 pipi kaka uga aga 2026-05-30 11:24:18 +02:00
6fdfed5cae gfds 2026-05-30 09:01:52 +02:00
c949453c9e im already tracer 2026-05-30 08:51:15 +02:00
0e8e26237e ff 2026-05-30 08:46:31 +02:00
4a0784746d ghf 2026-05-30 08:41:28 +02:00
c98e797d4f add alternative controls 2026-05-30 08:35:20 +02:00
3ff61f4e36 eierfon gay fix? 2026-05-30 07:29:13 +02:00
26b4081984 fjnf 2026-05-30 06:57:58 +02:00
80457014c1 ina ina 2026-05-30 06:55:43 +02:00
8dd1ed22a2 dönerkebab 2026-05-30 06:48:12 +02:00
db0b28fe0c hgfd 2026-05-29 21:23:35 +02:00
44bf46f02c gfds 2026-05-29 21:20:44 +02:00
d9b49b1e21 hgdf 2026-05-29 21:17:07 +02:00
a7e4d5b0dd hgf 2026-05-29 20:53:38 +02:00
67643f17a9 hgfd 2026-05-29 20:49:30 +02:00
e0e0456768 gfhgfd 2026-05-29 20:49:26 +02:00
7e7da4030d jghf 2026-05-29 20:18:44 +02:00
754fc95d56 add polls 2026-05-29 20:15:00 +02:00
9365cb21c8 big oppai 2026-05-29 19:41:34 +02:00
264b6c3e6d gfds 2026-05-29 19:38:18 +02:00
78fe42ef3a jghf 2026-05-29 19:33:45 +02:00
45df561e9d kkkkkkkkk 2026-05-29 19:20:33 +02:00
f38d77a4d8 gdfs 2026-05-29 19:17:11 +02:00
beb5460797 hgfd 2026-05-29 19:08:01 +02:00
37460ba224 regression for filter setting possible fix 2026-05-29 19:05:44 +02:00
f79e4d6f32 prevent comment attachment to be abused 2026-05-29 18:38:26 +02:00
86085c435a gfds 2026-05-29 12:24:29 +02:00
697d62f89b beautifying the tags 2026-05-29 09:12:21 +02:00
18add9f21a gfd 2026-05-29 09:00:46 +02:00
5e298383a3 f 2026-05-29 08:59:01 +02:00
d5f118f2fc test 2026-05-29 08:56:21 +02:00
63bb86defc gfds 2026-05-29 05:38:56 +02:00
066ca99dd3 sidebar 2026-05-28 21:50:34 +02:00
d1b0e3542c gfdsgfds 2026-05-28 21:46:47 +02:00
a8978e232f sexy grabbing finally!!! 2026-05-28 21:25:37 +02:00
ddd87b6336 hdf 2026-05-28 21:22:11 +02:00
6be580dc92 fdsagfds 2026-05-28 21:15:47 +02:00
420f58c85a fds 2026-05-28 20:48:45 +02:00
62a6a345cb fdsa 2026-05-28 20:43:10 +02:00
700e705bee gfdsgfds 2026-05-28 20:40:16 +02:00
80240ccb66 gfds 2026-05-28 20:34:26 +02:00
eabf1585b9 border 2026-05-28 20:28:45 +02:00
4125db98ba spicy queen 2026-05-28 20:14:31 +02:00
98075423f0 bhi 2026-05-28 19:28:22 +02:00
b8024acf12 uga aga 2026-05-28 18:41:35 +02:00
4ed87cd331 fix hall creation 2026-05-28 18:33:23 +02:00
dcdea5e9ea kjhg 2026-05-28 16:42:05 +02:00
1cfb001148 jhgf 2026-05-28 16:34:02 +02:00
9a003be98f kjhg 2026-05-28 16:22:53 +02:00
2a73a00e98 add dimensions 2026-05-28 16:02:16 +02:00
9804376d30 gfds 2026-05-28 13:21:18 +02:00
006ee727ec jhgf 2026-05-28 13:15:45 +02:00
1fe506da65 h 2026-05-28 12:47:43 +02:00
df997db8eb slightly bigger pagination 2026-05-28 12:33:45 +02:00
4d1d5d4332 gurkenwasser 2026-05-28 11:52:18 +02:00
03f751954d hfgd 2026-05-28 08:21:31 +02:00
33abde6f79 j 2026-05-28 08:17:39 +02:00
3e427b7b58 pagination now correctly centers in available space 2026-05-28 08:10:30 +02:00
ac1d710811 chud 2026-05-28 08:06:32 +02:00
93bb36883f eeeeeeeeeee 2026-05-28 08:04:14 +02:00
a6bf8fe6df tinkering with the dms 2026-05-28 07:57:09 +02:00
090c0b8016 easier fullscreen for mobile 2026-05-28 07:26:40 +02:00
7593033ab9 kjhg 2026-05-28 06:43:12 +02:00
991a31ff35 f 2026-05-28 06:38:59 +02:00
aff3153a84 lkjh 2026-05-28 06:34:29 +02:00
a4cd858114 fds 2026-05-27 20:32:36 +02:00
ebaea76b90 hgdf 2026-05-27 20:29:27 +02:00
b705cd3a9c hbg 2026-05-27 20:21:42 +02:00
57a59dcda0 n 2026-05-27 20:02:54 +02:00
8ec4f1c1b3 fdsa 2026-05-27 20:02:14 +02:00
181c30e9ee fd 2026-05-27 19:40:35 +02:00
ab8d751330 f 2026-05-27 19:38:29 +02:00
603b3f37b9 add total amount of users to stats 2026-05-27 19:33:38 +02:00
9f6215706d idk fuck this 2026-05-27 19:28:00 +02:00
3e1657ec34 hgfd 2026-05-27 19:25:58 +02:00
8909e02ddc fdsa 2026-05-27 19:21:28 +02:00
61754e058f attachment fix 2026-05-27 19:12:35 +02:00
514dae7906 uga aga pipi kaka 2026-05-27 18:48:54 +02:00
ffb328ab96 drachenfotze 2026-05-27 16:27:53 +02:00
8ddcff61e4 133 2026-05-27 16:14:45 +02:00
c4c311c541 testing: adding smooth animation for comment hding 2026-05-27 15:51:05 +02:00
b575a07921 filter update 2026-05-27 15:25:42 +02:00
236e540204 fav gap and ugly horizontal scrollbar 1050px width... 2026-05-27 07:01:53 +02:00
ef08f85d25 fges 2026-05-27 06:44:20 +02:00
635afe9f9f scroller filename as metadata 2026-05-27 06:33:28 +02:00
25dfa6c8a2 fa 2026-05-26 21:49:16 +02:00
cfd446597d fuck this shit 2026-05-26 21:44:24 +02:00
9c42e8ea2b gfdsgfds 2026-05-26 21:39:57 +02:00
4f9fc25ef2 gfbds 2026-05-26 21:28:16 +02:00
8693e16802 fix dynamic thumb for mme+rating filter 2026-05-26 21:19:14 +02:00
9732b30aa5 change mode display 2026-05-26 19:56:22 +02:00
7c2619e492 Testing: allow selecting multiple ratings for better filtering 2026-05-26 19:10:24 +02:00
0f7eced14d cockvore 2026-05-26 15:13:24 +02:00
924dcc0641 xdddd 2026-05-26 15:10:21 +02:00
54bdbad25e fuck italic 2026-05-26 14:52:45 +02:00
1174cd6947 feat: add support for encrypted DM attachments, per-user upload API keys, and configurable feed layouts via new database migrations and API documentation. 2026-05-26 14:30:02 +02:00
6f0b62cf8d feat: implement API documentation, add database migrations for site features, and include comment file attachments in API responses 2026-05-26 14:24:52 +02:00
ef3a9bd3b0 feat: add database migration scripts and supplementary tooling for data imports and site management 2026-05-26 14:17:05 +02:00
dd4e56c8fb feat: implement database migrations for wordfilter, DMs, user invites, and site settings while adding video title import utilities. 2026-05-26 14:14:05 +02:00
0ed609c8ce legacy layout scrollbutton fix 2026-05-26 14:12:30 +02:00
3f92e62820 feat: implement database migrations for word filter, DM attachments, message editing, and user invite tracking, plus add API documentation and dev scripts. 2026-05-26 14:02:28 +02:00
cb3bd4358c same height for attachments in sidebar than comments 2026-05-26 13:50:17 +02:00
be499ddb36 gfds 2026-05-25 20:25:18 +02:00
df8797b92a empty title still reserves the same space as set title for layout consistency 2026-05-25 15:24:47 +02:00
6622ea93aa gtfds 2026-05-25 13:10:00 +02:00
cce4eb3d57 ehehehe 2026-05-25 13:06:37 +02:00
49a1365cf9 xdddd 2026-05-25 12:24:48 +02:00
0dad6924b5 bvgfd 2026-05-25 12:12:46 +02:00
7ca88f6416 search testing xd 2026-05-25 12:09:35 +02:00
f2cebddd4d update search to include video titles 2026-05-25 10:08:32 +02:00
fda2ed36bd option to enable/disable item titles 2026-05-25 09:55:53 +02:00
1adc0f4ee2 remove title 2026-05-25 09:50:42 +02:00
9b64feb8ed adding back tooltip for timeago on comments 2026-05-25 09:48:59 +02:00
c6dd2a7ff8 geilify admin pages 2026-05-25 09:46:21 +02:00
8977c072f2 rating switch more visual 2026-05-25 09:32:44 +02:00
d4a68f59fd add apu bingo 2026-05-25 09:20:40 +02:00
92cc474ca3 eeee 2026-05-25 09:03:58 +02:00
3a436304bd meme generator update 2026-05-25 08:57:13 +02:00
96b13db79c center thumb 2026-05-25 08:48:53 +02:00
b0d53d34ac eee 2026-05-25 08:45:03 +02:00
107a184c04 test 2026-05-25 08:41:30 +02:00
29d33fe277 meme test 2026-05-25 08:38:14 +02:00
8257c8d021 update env example 2026-05-24 23:24:09 +02:00
fa8ed5e354 fix yt links 2026-05-24 23:16:01 +02:00
95e37c1dd1 fix xss... 2026-05-24 23:11:31 +02:00
613f099a8b add item titles 2026-05-24 23:02:49 +02:00
187f35227b no margin 2026-05-24 22:10:45 +02:00
8a679c2fe6 fix tooltip breakout calculation position 2026-05-24 22:08:26 +02:00
b2584763ee cd score layout modern fixes 2026-05-24 22:04:07 +02:00
f9e45327bf hgfd 2026-05-24 21:27:33 +02:00
096720c266 fdf 2026-05-24 21:24:48 +02:00
83fdada12d updating compose with latest mounts and adding missing gitkeeps 2026-05-24 21:19:24 +02:00
0714b0a68c use correct class for quicknav 2026-05-24 21:16:25 +02:00
78c28b4734 remove iconset.svg 2026-05-24 21:10:26 +02:00
34fa51a6e9 bghd 2026-05-24 21:09:50 +02:00
060d73122b fd 2026-05-24 21:07:05 +02:00
026bf4a421 hgfd 2026-05-24 20:58:13 +02:00
6c85a86959 prevent image modal for emojis and make the emojis bigger 2026-05-24 20:53:33 +02:00
5ce2371b41 fix image expansion 2026-05-24 20:41:24 +02:00
503c131f0b t 2026-05-24 19:00:05 +02:00
5bbcb5be41 hgfd 2026-05-24 18:49:47 +02:00
126bf41d9a eeee 2026-05-24 18:39:12 +02:00
5ae397bb0c g 2026-05-24 18:37:12 +02:00
d8a8626dae update usermanager 2026-05-24 18:31:35 +02:00
3abefe64de quick nav style update 2026-05-24 18:15:07 +02:00
d77936e58f add missing i18n for sidebar 2026-05-24 18:03:30 +02:00
88fc872df6 display reposts in info modal 2026-05-24 17:51:16 +02:00
18e07e43b6 only load captcha resources if not logged in. 2026-05-24 17:37:22 +02:00
f735a144af fix layout modern image expansion 2026-05-24 17:17:08 +02:00
fa350e8f1c gf 2026-05-24 17:00:07 +02:00
ad72c053d9 hgfd 2026-05-24 16:58:01 +02:00
7e458e4450 f 2026-05-24 16:56:24 +02:00
4a155bc5f4 add recaptcha option 2026-05-24 16:44:20 +02:00
393db5fe2a add possibility to create account without email and token 2026-05-24 16:35:07 +02:00
a5e79cca0c custom navbar 2026-05-24 16:09:02 +02:00
cdd415a52f fd 2026-05-24 15:55:48 +02:00
0b9b049f82 correct nsfw badge color for shitpost uploading 2026-05-24 10:22:05 +02:00
ca4a722029 comment safe guards 2026-05-24 10:11:41 +02:00
bb4125601f option for users to delete their own comments 2026-05-24 10:05:40 +02:00
375e1a85d4 xd score fix 2026-05-24 09:51:10 +02:00
18cac93bf1 space to enlarge 2026-05-24 09:40:44 +02:00
2ab4ae06af make quick cycling great again 2026-05-24 09:25:05 +02:00
2bce856153 speed up shitpost mode upload 2026-05-24 08:56:09 +02:00
8e6011785a higher quality tag and hall images 2026-05-24 08:49:18 +02:00
a87123cb43 unify sidebar emoji height 2026-05-24 08:27:33 +02:00
28d5b9364f notis on blur aswell 2026-05-24 00:11:05 +02:00
6688db6145 require item revealing when user wants it 2026-05-23 23:23:31 +02:00
a3bec09864 update wordfilter func 2026-05-23 23:09:24 +02:00
229cfacd5c remove dashboard link 2026-05-23 23:06:29 +02:00
0c246aab30 wordfilter update 2026-05-23 23:01:28 +02:00
a0ac4607cc add wordfilter 2026-05-23 22:55:53 +02:00
9a9b787fd7 add shitpost mode config options 2026-05-23 22:38:28 +02:00
e61654c567 update xd score scoring system 2026-05-23 22:23:51 +02:00
6137545cab do not show chat manager in admin dashboard if disabled 2026-05-23 22:13:39 +02:00
e3ba7d3b10 gfds 2026-05-23 22:07:29 +02:00
0945f780a3 gfdgdf 2026-05-23 22:06:32 +02:00
ac98e292e9 fix shitpost mode ugly padding 2026-05-23 22:02:43 +02:00
4e10aec872 utf8 2026-05-23 21:51:00 +02:00
1aaa0493a9 rules,about,tos markdown 2026-05-23 21:48:47 +02:00
7155b3a7da updating meme manager to update memes 2026-05-23 21:25:46 +02:00
2f044a8d02 generate blur thumbnail for all items! 2026-05-23 21:05:40 +02:00
8c9e89c771 fix quick nav highlight 2026-05-23 20:55:41 +02:00
d7377c108a better 2026-05-23 20:47:57 +02:00
cbccac6e22 hide thumb higher 2026-05-23 20:46:40 +02:00
046ecf8321 gjgjg 2026-05-23 20:41:47 +02:00
a2dd32989e add get sharex config button to api key 2026-05-23 20:37:47 +02:00
b608208cf9 fix for api upload when private_society is enabled 2026-05-23 20:34:18 +02:00
e0c435009b better filters 2026-05-23 20:21:47 +02:00
0f3b80f0c1 making settings more readable and navigatable 2026-05-23 20:10:57 +02:00
c6ff4fa703 fix inviting 2026-05-23 19:32:50 +02:00
bf92d53620 implement user invites 2026-05-23 19:14:13 +02:00
dd6cda2b44 fd 2026-05-23 18:32:53 +02:00
dbe0859750 sidebar blurring 2026-05-23 18:22:46 +02:00
c480b82db6 content preferences 2026-05-23 15:41:40 +02:00
3e6298f81c previews and make sure blurry thumb gets always generated when rating is changed later on 2026-05-23 15:35:42 +02:00
97cc69b337 better blur 2026-05-23 15:29:50 +02:00
4b50e56eb8 add option to blur any thumb 2026-05-23 15:26:35 +02:00
c488b93290 fix fullscreen control and cursor hide again... 2026-05-23 13:05:34 +02:00
aebb20b37f speed up review process 2026-05-23 13:01:14 +02:00
fcfe73178b fix player flickering when entering with mouse 2026-05-23 12:57:49 +02:00
224af7e8cb 2.5s are better 2026-05-23 12:34:43 +02:00
29f73c9271 hide mouse cursor in fullscreen after 5 seconds aswell 2026-05-23 12:30:33 +02:00
0e04e9f49f add file info button 2026-05-23 12:19:51 +02:00
ca9ccab697 double speed also when paused 2026-05-23 11:54:42 +02:00
74f1c31df2 fdfdfdfdfd 2026-05-23 09:54:56 +02:00
fdf54e4513 x2 speed for v0ck 2026-05-23 09:49:57 +02:00
867304bcb1 agayn 2026-05-23 09:44:38 +02:00
3b5144f475 hide controls after 5 seconds and remove unnecesarry min-height 2026-05-23 09:40:58 +02:00
422f80cabd gs 2026-05-23 09:34:50 +02:00
f3b2887df3 uga aga 2026-05-23 09:31:09 +02:00
1be9216624 hgfd 2026-05-23 08:45:59 +02:00
0d85ff0535 auto 2026-05-23 08:43:03 +02:00
1410200cf2 ye 2026-05-23 08:39:58 +02:00
0745637229 hehe 2026-05-22 21:28:01 +02:00
832581ad68 fuck border radius 2026-05-22 21:24:04 +02:00
748da77678 eeeeeee 2026-05-22 21:23:06 +02:00
fe1a29c2a6 add config option for api keys 2026-05-22 21:20:52 +02:00
013bdce1db settings padding... 2026-05-22 21:05:20 +02:00
615aacae9a fuck formatting!!! 2026-05-22 20:59:11 +02:00
a1ef06e573 Revert "ff"
This reverts commit 0450d9e2ed.
2026-05-22 20:53:08 +02:00
6ca29806b0 Revert "gfds"
This reverts commit 9694a560f7.
2026-05-22 20:52:48 +02:00
9694a560f7 gfds 2026-05-22 20:46:18 +02:00
0450d9e2ed ff 2026-05-22 20:44:02 +02:00
71f292f243 add api key for uploading via 3rd party tools 2026-05-22 20:42:48 +02:00
d44fb1ac05 dynamic comment length 2026-05-22 20:21:15 +02:00
b836ce37f3 gf 2026-05-22 18:59:35 +02:00
29551f9d27 lets see if this works out 2026-05-22 18:49:10 +02:00
de2302b589 gfd 2026-05-22 18:27:29 +02:00
126923f2b7 fd 2026-05-22 18:19:21 +02:00
bc89c1d7a8 zomg indicator 2026-05-22 18:15:31 +02:00
e07fb589c5 better filter visualization 2026-05-22 18:12:37 +02:00
3ec97f4451 fooooo 2026-05-22 15:43:12 +02:00
c569cde8cf keep keyboard open when opening emoji selector 2026-05-22 15:37:29 +02:00
df312009b8 attempting to fix legacy user accounts with less than 20 characters. 2026-05-22 15:34:23 +02:00
6c6764202e must select template before using text 2026-05-22 08:35:46 +02:00
b093f7618a goo goo ga ga 2026-05-22 08:22:25 +02:00
7e00c090e2 adding custom meme template instead of fixed library 2026-05-22 08:18:30 +02:00
9c46396a39 attempting to fix mobile replies/quotes 2026-05-22 08:09:41 +02:00
9ef3207cd4 fixing random api endpoint 2026-05-21 19:51:57 +02:00
72b8140f77 fix meme manager text overflowing 2026-05-21 15:53:53 +02:00
948e6461fd convenience for shitpost mode link uploader 2026-05-21 15:41:42 +02:00
eb209f6d27 add option to have unencrypted direct messages 2026-05-21 15:31:57 +02:00
d0a014705b updating phash/dhash generation 2026-05-20 19:10:50 +02:00
07edfcb71d fixing legacy password login 2026-05-20 18:53:57 +02:00
0074355df8 lflf 2026-05-18 18:32:19 +02:00
3ac1489d1f lazyloading 2026-05-18 18:26:46 +02:00
f87642341b scrollbottom for chat 2026-05-18 18:17:32 +02:00
e445169456 37 2026-05-18 18:15:03 +02:00
8f8bda1d0d adding online presence for dms 2026-05-18 18:02:11 +02:00
bcb17dc48b gonna hate race conditions 2026-05-18 17:56:14 +02:00
ab566fc126 lets see 2026-05-18 17:52:45 +02:00
aabc33a6cd fix bug lol 2026-05-18 17:39:50 +02:00
9c129b7a37 add decent replying to direct messages 2026-05-18 17:36:07 +02:00
0393878c9f add option to edit/delete direct mssages and dynamic expiry date for attachments via config 2026-05-18 17:22:44 +02:00
313cbeddc4 fix attachment button and logic 2026-05-18 16:49:31 +02:00
e97698877d possible fix for boot crash and image expansion 2026-05-18 16:44:29 +02:00
ec8c423304 add encrypted dm attachments 2026-05-18 16:26:53 +02:00
ad325c085a yippi ya ohhhh 2026-05-17 14:24:30 +02:00
385b731ee8 abyss metadata preview #2 2026-05-17 14:19:21 +02:00
82574466ee abyss internal link shortening, removal of # for ids and external preview 2026-05-17 14:16:13 +02:00
152 changed files with 25300 additions and 3303 deletions

View File

@@ -1,3 +1,10 @@
POSTGRES_USER=
POSTGRES_DB=
POSTGRES_PASSWORD=
POSTGRES_USER=f0ckm
POSTGRES_DB=f0ckm
POSTGRES_PASSWORD=f0ckm
# --- Nginx & Tor Profiles (Optional) ---
# Set to 'f0ckm-nginx' for Nginx, 'tor' for Tor hidden service, or 'f0ckm-nginx,tor' for both
# COMPOSE_PROFILES=tor
#
# VIRTUAL_HOST=yourdomain.com
# LETSENCRYPT_HOST=yourdomain.com
# LETSENCRYPT_EMAIL=your-email@example.com

4
.gitignore vendored
View File

@@ -16,4 +16,6 @@ public/a
public/tag_cache
.env
config.json
bundle.css
bundle.css
public/s/fonts/impact.woff
f0ck-svelte/*

View File

@@ -1,18 +1,30 @@
# f0ckm
Happy to finally bring you f0ckm! The long awaited imageboard solution that you can host yourself. It is designed to be a real alternative to big tech platforms that you can modify to suit your communities needs.
It features extensive tagging, searching, filtering and a variety of options.
The software is mostly generic, it can be modified easily via config.json to suit your communities needs. Most things can be enabled/disabled very easily and modified to needs.
The software comes without any warranties or entitlements of any kind! The developer is not responsible for anything you do with the use of this software.
## Software Requirements
- Docker (https://docs.docker.com/engine/install/debian/)
## prod
first things
`cp .env.example .env`
fill with for example: f0ckm
fill with for example: f0ckm (prefilled)
`cp config_example.json config.json`
Edit to needs, for sql you can do this:
host can either be localhost or the docker containers hostname, when running via docker this must be the dockers hostname
host can either be localhost or the docker containers hostname, when running via docker this must be the dockers hostname, if you choose localhost you wont need to add the ENV `DB_HOST=localhost` and if you also change the port to be `DB_PORT=5454` you wont need this ENV either, but then Docker wont find the DB.
```
"sql": {
@@ -42,6 +54,8 @@ now vist http://localhost:1337 in your browser
## dev
NOTE: when developing locally it might be necessary to run commands with `DB_HOST=localhost DB_PORT=5454`
`docker compose up -d f0ckm-db`
on dev machine:
@@ -49,8 +63,38 @@ on dev machine:
`npm i`
`npm run dev`
Fill Database
`docker exec -i f0ckm-db psql -U f0ckm -d f0ckm < migrations/f0ckm_schema.sql`
`DB_HOST=localhost DB_PORT=5454 node scripts/seed.mjs`
Create admin user in dev env
`DB_HOST=localhost DB_PORT=5454 node scripts/create-admin.mjs admin 'YOUR_PASSWORD_HERE'`
now visit http://localhost:1337 in your browser, you can develop without needing to rebuild the docker image for every change
## NGINX
uncomment in .env # COMPOSE_PROFILES=f0ckm-nginx to enable nginx proxy with automatic lets encrypt.
## Tor Hidden Service (.onion)
Tor is bundled in `docker-compose.yml` and preconfigured as long as COMPOSE_PROFILES=f0ckm-tor is set with a hidden service pointing to the application (`f0ckm:1337`).
When running `docker compose up -d`, Tor automatically generates a `.onion` address for your node. You can find your onion address by running:
```bash
cat ./f0ckm-data/tor/f0ckm_hs/hostname
```
### Automatic Onion-Location Header
To advertise your `.onion` address to Tor Browser users visiting your clearnet site, add your `.onion` address to `config.json`:
```json
"main": {
"onion": "http://yourgeneratedaddress.onion"
}
```

View File

@@ -16,7 +16,7 @@ fi
# Parse arguments
TARGET="master"
CACHE_FLAG=""
BRANCH_TARGET=""
CUSTOM_BRANCH=""
for arg in "$@"; do
case $arg in
@@ -27,8 +27,8 @@ for arg in "$@"; do
CACHE_FLAG="--no-cache"
;;
*)
if [ -z "$BRANCH_TARGET" ]; then
BRANCH_TARGET=$arg
if [ -z "$CUSTOM_BRANCH" ]; then
CUSTOM_BRANCH=$arg
fi
;;
esac
@@ -43,7 +43,10 @@ fi
# Set Image name and branch defaults
IMAGE_NAME="f0ckm"
if [ "$TARGET" == "master" ]; then
if [ -n "$CUSTOM_BRANCH" ]; then
BRANCH_TARGET="$CUSTOM_BRANCH"
echo "--- CUSTOM BRANCH DEPLOYMENT (${BRANCH_TARGET}) ---"
elif [ "$TARGET" == "master" ]; then
echo "--- PRODUCTION DEPLOYMENT (master) ---"
BRANCH_TARGET="master"
elif [ "$TARGET" == "stg" ]; then

3
config/nginx/f0ck.conf Normal file
View File

@@ -0,0 +1,3 @@
client_max_body_size 10000M;
client_body_timeout 120s;
client_header_timeout 120s;

9
config/tor/torrc Normal file
View File

@@ -0,0 +1,9 @@
# Tor configuration for f0ckm
# Enable SOCKS proxy for internal container & external connections
SocksPort 0.0.0.0:9050
# Tor Hidden Service (v3 Onion Service) configuration
# Tor will automatically generate private keys and hostnames in /var/lib/tor/f0ckm_hs/
HiddenServiceDir /var/lib/tor/f0ckm_hs/
HiddenServicePort 80 f0ckm:1337

View File

@@ -5,6 +5,7 @@
"domain": "example.com",
"regex": "example\\.com"
},
"onion": "http://your-onion-address.onion",
"socks": "socks5://127.0.0.1:9050",
"mail": "admin@example.com",
"maxfilesize": 104857600,
@@ -53,14 +54,21 @@
"amoled"
],
"theme": "amoled",
"default_font": "",
"default_layout": "legacy",
"custom_favicon": "/s/img/favicon.gif",
"custom_brand_image": [],
"custom_navbar_brand_text": "",
"show_koepfe": false,
"hide_sidebar_default": true,
"koepfe": [],
"enable_tor_hs": true,
"enable_global_chat": true,
"enable_danmaku": true,
"private_messages": true,
"dm_attachments": true,
"dm_unencrypted": false,
"dm_attachment_expiry_days": 90,
"halls_enabled": true,
"userhalls_enabled": true,
"enable_userhall_image_upload": true,
@@ -68,12 +76,24 @@
"meme_creator": true,
"enable_cleanup": false,
"enable_data_export": true,
"inactivity_ban_days": 60,
"enable_user_api_keys": true,
"enable_user_invites": true,
"user_invite_slots": 2,
"invite_criteria": {
"uploads": 10,
"age_days": 10,
"comments": 10,
"tags": 10
},
"cleanup_timeframe_days": 30,
"web_url_upload": true,
"enable_youtube_upload": true,
"web_meta_extraction": true,
"bypass_duplicate_check": true,
"shitpost_mode": false,
"shitpost_require_rating": false,
"shitpost_min_tags": 0,
"protect_files": false,
"enable_dynamic_thumbs": false,
"allowed_comment_images": [
@@ -83,6 +103,14 @@
],
"show_mime_picker": true,
"embed_youtube_in_comments": true,
"allow_fileupload_comments": true,
"allow_comment_deletion": false,
"enable_comment_polls": false,
"fileupload_comments_multifile": true,
"fileupload_comments_size": 104857600,
"fileupload_comments_max": 5,
"fileupload_comments_mode": "attachment",
"fileupload_comments_mimes": ["image", "video", "audio"],
"show_content_warning": true,
"default_comment_display_mode": 1,
"phrases": [
@@ -94,12 +122,21 @@
"enable_swiping": true,
"enable_profile_description": true,
"user_alternative_infobox": false,
"user_banner_enabled": true,
"user_alternative_steuerung": false,
"enable_swf": false,
"swf_thumb": "/s/img/swf.png",
"enable_archive": true,
"archive_thumb": "/s/img/archive.webp",
"enable_item_title": true,
"open_registration": true,
"open_registration_web_toggle": false,
"open_registration_require_mail_andor_token": false,
"private_society": false,
"private_society_gate": "cloudflare",
"private_society_gate_location": "Frankfurt",
"private_society_gate_template": "_gate_template",
"public_nsfw": false,
"paths": {
"images": "/b",
"thumbnails": "/t",
@@ -177,7 +214,16 @@
"video/x-matroska": "mkv",
"application/x-shockwave-flash": "swf",
"application/vnd.adobe.flash.movie": "swf",
"application/pdf": "pdf"
"application/pdf": "pdf",
"application/zip": "zip",
"application/x-zip-compressed": "zip",
"application/x-rar-compressed": "rar",
"application/vnd.rar": "rar",
"application/x-7z-compressed": "7z",
"application/x-tar": "tar",
"application/gzip": "gz",
"application/x-bzip2": "bz2",
"application/x-xz": "xz"
},
"apis": {},
"smtp": {
@@ -189,5 +235,10 @@
"password": "smtp_password",
"from": "admin@example.com",
"mail_reset_password": false
},
"recaptcha": {
"enabled": false,
"site_key": "YOUR_RECAPTCHA_V2_SITE_KEY",
"secret_key": "YOUR_RECAPTCHA_V2_SECRET_KEY"
}
}

View File

@@ -11,12 +11,14 @@ services:
networks:
- f0ckm-net
volumes:
- ./config.json:/opt/f0ckm/config.json:Z
- ./config.json:/opt/f0ckm/config.json:ro,Z
- ./src/:/opt/f0ckm/src/:Z
- ./views/:/opt/f0ckm/views/:Z
- ./scripts/:/opt/f0ckm/scripts/:Z
- ./f0ckm-data/a/:/opt/f0ckm/public/a/:Z
- ./f0ckm-data/b/:/opt/f0ckm/public/b/:Z
- ./f0ckm-data/c/:/opt/f0ckm/public/c/:Z
- ./f0ckm-data/e/:/opt/f0ckm/public/e/:Z
- ./f0ckm-data/t/:/opt/f0ckm/public/t/:Z
- ./f0ckm-data/deleted/:/opt/f0ckm/deleted/:Z
- ./f0ckm-data/pending/:/opt/f0ckm/pending/:Z
@@ -33,6 +35,10 @@ services:
environment:
- GIT_HASH=${f0ckm_TAG:-unknown}
- VIRTUAL_HOST=${VIRTUAL_HOST:-localhost}
- VIRTUAL_PORT=1337
- LETSENCRYPT_HOST=${LETSENCRYPT_HOST:-}
- LETSENCRYPT_EMAIL=${LETSENCRYPT_EMAIL:-}
ports:
- "1337:1337"
restart: unless-stopped
@@ -40,6 +46,21 @@ services:
f0ckm-db:
condition: service_healthy
tor:
image: dockurr/tor
container_name: tor
profiles:
- tor
ports:
- "9050:9050"
- "8118:8118"
volumes:
- ./config/tor:/etc/tor:ro
- ./f0ckm-data/tor:/var/lib/tor:Z
networks:
- f0ckm-net
restart: always
f0ckm-db:
container_name: f0ckm-db
image: postgres:17
@@ -78,6 +99,51 @@ services:
# - f0ckm-net
# restart: unless-stopped
f0ckm-nginx:
image: nginxproxy/nginx-proxy:latest
container_name: f0ckm-nginx
profiles:
- f0ckm-nginx
environment:
- ENABLE_IPV6=true
ports:
- "80:80"
- "443:443"
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- certs:/etc/nginx/certs:rw
- vhost:/etc/nginx/vhost.d:rw
- html:/usr/share/nginx/html:rw
- ./config/nginx/f0ck.conf:/etc/nginx/conf.d/f0ckm.conf:ro
networks:
- f0ckm-net
restart: unless-stopped
acme-companion:
image: nginxproxy/acme-companion:latest
container_name: f0ckm-acme-companion
profiles:
- f0ckm-nginx
environment:
- NGINX_PROXY_CONTAINER=f0ckm-nginx
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- certs:/etc/nginx/certs:rw
- vhost:/etc/nginx/vhost.d:rw
- html:/usr/share/nginx/html:rw
- acme:/etc/acme.sh:rw
depends_on:
- f0ckm-nginx
networks:
- f0ckm-net
restart: unless-stopped
networks:
f0ckm-net:
driver: bridge
volumes:
certs:
vhost:
html:
acme:

0
f0ckm-data/c/.gitkeep Normal file
View File

0
f0ckm-data/e/.gitkeep Normal file
View File

View File

@@ -0,0 +1,10 @@
-- User emoji favorites — persisted per-user, cross-device
CREATE TABLE IF NOT EXISTS user_emoji_favorites (
user_id integer NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
emoji_name text NOT NULL,
emoji_url text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, emoji_name)
);
CREATE INDEX IF NOT EXISTS idx_user_emoji_favorites_user_id ON user_emoji_favorites (user_id);

View File

@@ -0,0 +1,53 @@
-- Migration: Add sticker_packs table and link custom_emojis to packs
-- Run this against the f0ckm database (idempotent — safe to run multiple times)
-- Create sticker_packs table
CREATE TABLE IF NOT EXISTS public.sticker_packs (
id serial PRIMARY KEY,
name text NOT NULL,
tg_name text UNIQUE,
tg_title text,
thumb_url text,
sticker_count integer DEFAULT 0,
created_at timestamp with time zone DEFAULT now()
);
ALTER TABLE public.sticker_packs OWNER TO f0ckm;
-- Add pack_id column to custom_emojis (nullable: NULL = standalone emoji, no pack)
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'custom_emojis'
AND column_name = 'pack_id'
) THEN
ALTER TABLE public.custom_emojis
ADD COLUMN pack_id integer REFERENCES public.sticker_packs(id) ON DELETE SET NULL;
RAISE NOTICE 'pack_id column added to custom_emojis';
ELSE
RAISE NOTICE 'pack_id column already exists on custom_emojis — skipping';
END IF;
END
$$;
-- Add thumb_url column to sticker_packs if missing
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'sticker_packs'
AND column_name = 'thumb_url'
) THEN
ALTER TABLE public.sticker_packs ADD COLUMN thumb_url text;
RAISE NOTICE 'thumb_url column added to sticker_packs';
ELSE
RAISE NOTICE 'thumb_url already exists on sticker_packs — skipping';
END IF;
END
$$;
-- Index for fast pack lookups
CREATE INDEX IF NOT EXISTS custom_emojis_pack_id_idx ON public.custom_emojis (pack_id);

View File

@@ -0,0 +1,15 @@
-- Add banner_file column to user_options for custom profile banners
-- Banners are displayed in the alternative infobox (user-infobox-block)
ALTER TABLE user_options
ADD COLUMN IF NOT EXISTS banner_file character varying(255) DEFAULT NULL;
ALTER TABLE user_options
ADD COLUMN IF NOT EXISTS banner_position character varying(50) DEFAULT 'center';
ALTER TABLE user_options
ADD COLUMN IF NOT EXISTS banner_size character varying(50) DEFAULT 'cover';
COMMENT ON COLUMN public.user_options.banner_file IS 'Custom uploaded banner image filename, stored in public/a/ (same dir as avatars)';
COMMENT ON COLUMN public.user_options.banner_position IS 'CSS background-position for the banner';
COMMENT ON COLUMN public.user_options.banner_size IS 'CSS background-size for the banner (e.g. cover, contain, or a percentage)';

View File

@@ -20,6 +20,9 @@ SET client_min_messages = warning;
SET row_security = off;
DROP PUBLICATION IF EXISTS alltables;
ALTER TABLE IF EXISTS ONLY public.user_api_keys DROP CONSTRAINT IF EXISTS user_api_keys_user_id_fkey;
ALTER TABLE IF EXISTS ONLY public.user_api_keys DROP CONSTRAINT IF EXISTS user_api_keys_api_key_key;
ALTER TABLE IF EXISTS ONLY public.user_api_keys DROP CONSTRAINT IF EXISTS user_api_keys_pkey;
ALTER TABLE IF EXISTS ONLY public.user_warnings DROP CONSTRAINT IF EXISTS user_warnings_user_id_fkey;
ALTER TABLE IF EXISTS ONLY public.user_warnings DROP CONSTRAINT IF EXISTS user_warnings_admin_id_fkey;
ALTER TABLE IF EXISTS ONLY public.user_video_views DROP CONSTRAINT IF EXISTS user_video_views_video_id_fkey;
@@ -76,7 +79,7 @@ CREATE OR REPLACE VIEW public.items_li AS
SELECT
NULL::integer AS id,
NULL::character varying(255) AS src,
NULL::character varying(40) AS dest,
NULL::character varying(60) AS dest,
NULL::character varying(100) AS mime,
NULL::integer AS size,
NULL::character varying(255) AS checksum,
@@ -91,6 +94,7 @@ DROP INDEX IF EXISTS public.idx_user_last_seen;
DROP INDEX IF EXISTS public.idx_user_halls_user_id;
DROP INDEX IF EXISTS public.idx_user_halls_assign_item;
DROP INDEX IF EXISTS public.idx_user_halls_assign_hall;
DROP INDEX IF EXISTS public.idx_user_api_keys_api_key;
DROP INDEX IF EXISTS public.idx_user_alias_userid;
DROP INDEX IF EXISTS public.idx_user_alias_type;
DROP INDEX IF EXISTS public.idx_user_alias_alias;
@@ -191,6 +195,7 @@ DROP TABLE IF EXISTS public.user_halls_assign;
DROP TABLE IF EXISTS public.user_halls;
DROP TABLE IF EXISTS public.user_dm_keyvault;
DROP TABLE IF EXISTS public.user_conversation_states;
DROP TABLE IF EXISTS public.user_api_keys;
DROP TABLE IF EXISTS public.user_alias;
DROP TABLE IF EXISTS public."user";
DROP SEQUENCE IF EXISTS public.user_id_seq;
@@ -588,7 +593,7 @@ CREATE TABLE public.comment_files (
id integer NOT NULL,
comment_id integer,
user_id integer NOT NULL,
dest character varying(40) NOT NULL,
dest character varying(60) NOT NULL,
mime character varying(100) NOT NULL,
size integer NOT NULL,
checksum character varying(255) NOT NULL,
@@ -600,6 +605,8 @@ CREATE TABLE public.comment_files (
ALTER TABLE public.comment_files OWNER TO f0ckm;
ALTER TABLE ONLY public.comment_files REPLICA IDENTITY DEFAULT;
--
-- Name: comment_files_id_seq; Type: SEQUENCE; Schema: public; Owner: f0ckm
--
@@ -820,12 +827,25 @@ CREATE TABLE public.invite_tokens (
used_by integer,
is_used boolean DEFAULT false,
created_by_discord character varying(255) DEFAULT NULL::character varying,
created_by_matrix character varying(255) DEFAULT NULL::character varying
created_by_matrix character varying(255) DEFAULT NULL::character varying,
used_at timestamp with time zone DEFAULT NULL
);
ALTER TABLE public.invite_tokens OWNER TO f0ckm;
--
-- Name: idx_invite_tokens_created_by; Type: INDEX; Schema: public; Owner: f0ckm
--
CREATE INDEX IF NOT EXISTS idx_invite_tokens_created_by ON public.invite_tokens (created_by);
--
-- Name: idx_invite_tokens_used_at; Type: INDEX; Schema: public; Owner: f0ckm
--
CREATE INDEX IF NOT EXISTS idx_invite_tokens_used_at ON public.invite_tokens (used_at) WHERE is_used = true;
--
-- Name: invite_tokens_id_seq; Type: SEQUENCE; Schema: public; Owner: f0ckm
--
@@ -869,7 +889,7 @@ ALTER SEQUENCE public.items_id_seq OWNER TO f0ckm;
CREATE TABLE public.items (
id integer DEFAULT nextval('public.items_id_seq'::regclass) NOT NULL,
src character varying(255) NOT NULL,
dest character varying(40) NOT NULL,
dest character varying(60) NOT NULL,
mime character varying(100) NOT NULL,
size integer NOT NULL,
checksum character varying(255) NOT NULL,
@@ -887,7 +907,10 @@ CREATE TABLE public.items (
is_pinned boolean DEFAULT false,
is_oc boolean DEFAULT false,
xd_score integer DEFAULT 0 NOT NULL,
original_filename text
original_filename text,
title text,
width integer,
height integer
);
@@ -1326,6 +1349,21 @@ CREATE TABLE public."user" (
ALTER TABLE public."user" OWNER TO f0ckm;
--
-- Name: user_api_keys; Type: TABLE; Schema: public; Owner: f0ckm
--
CREATE TABLE public.user_api_keys (
user_id integer NOT NULL,
api_key text NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT user_api_keys_pkey PRIMARY KEY (user_id),
CONSTRAINT user_api_keys_api_key_key UNIQUE (api_key)
);
ALTER TABLE public.user_api_keys OWNER TO f0ckm;
--
-- Name: user_alias; Type: TABLE; Schema: public; Owner: f0ckm
--
@@ -1455,6 +1493,7 @@ CREATE TABLE public.user_options (
hide_koepfe boolean DEFAULT false NOT NULL,
language text,
use_alternative_infobox boolean DEFAULT false,
use_alternative_steuerung boolean DEFAULT NULL,
receive_system_notifications boolean DEFAULT true,
receive_user_notifications boolean DEFAULT true,
do_not_disturb boolean DEFAULT false,
@@ -1586,6 +1625,13 @@ ALTER TABLE ONLY public.audit_log ALTER COLUMN id SET DEFAULT nextval('public.au
ALTER TABLE ONLY public.comments ALTER COLUMN id SET DEFAULT nextval('public.comments_id_seq'::regclass);
--
-- Name: comment_files id; Type: DEFAULT; Schema: public; Owner: f0ckm
--
ALTER TABLE ONLY public.comment_files ALTER COLUMN id SET DEFAULT nextval('public.comment_files_id_seq'::regclass);
--
-- Name: custom_emojis id; Type: DEFAULT; Schema: public; Owner: f0ckm
--
@@ -1693,6 +1739,14 @@ ALTER TABLE ONLY public.comment_subscriptions
ADD CONSTRAINT comment_subscriptions_pkey PRIMARY KEY (user_id, item_id);
--
-- Name: comment_files comment_files_pkey; Type: CONSTRAINT; Schema: public; Owner: f0ckm
--
ALTER TABLE ONLY public.comment_files
ADD CONSTRAINT comment_files_pkey PRIMARY KEY (id);
--
-- Name: comments comments_pkey; Type: CONSTRAINT; Schema: public; Owner: f0ckm
--
@@ -2241,6 +2295,13 @@ CREATE INDEX idx_user_alias_type ON public.user_alias USING btree (type);
CREATE INDEX idx_user_alias_userid ON public.user_alias USING btree (userid);
--
-- Name: idx_user_api_keys_api_key; Type: INDEX; Schema: public; Owner: f0ckm
--
CREATE INDEX idx_user_api_keys_api_key ON public.user_api_keys USING btree (api_key);
--
-- Name: idx_user_halls_assign_hall; Type: INDEX; Schema: public; Owner: f0ckm
--
@@ -2385,6 +2446,22 @@ ALTER TABLE ONLY public.comment_subscriptions
ADD CONSTRAINT comment_subscriptions_user_id_fkey FOREIGN KEY (user_id) REFERENCES public."user"(id) ON DELETE CASCADE;
--
-- Name: comment_files comment_files_comment_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: f0ckm
--
ALTER TABLE ONLY public.comment_files
ADD CONSTRAINT comment_files_comment_id_fkey FOREIGN KEY (comment_id) REFERENCES public.comments(id) ON DELETE CASCADE;
--
-- Name: comment_files comment_files_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: f0ckm
--
ALTER TABLE ONLY public.comment_files
ADD CONSTRAINT comment_files_user_id_fkey FOREIGN KEY (user_id) REFERENCES public."user"(id) ON DELETE CASCADE;
--
-- Name: comments comments_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: f0ckm
--
@@ -2721,6 +2798,14 @@ ALTER TABLE ONLY public.user_warnings
ADD CONSTRAINT user_warnings_user_id_fkey FOREIGN KEY (user_id) REFERENCES public."user"(id) ON DELETE CASCADE;
--
-- Name: user_api_keys user_api_keys_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: f0ckm
--
ALTER TABLE ONLY public.user_api_keys
ADD CONSTRAINT user_api_keys_user_id_fkey FOREIGN KEY (user_id) REFERENCES public."user"(id) ON DELETE CASCADE;
--
-- Name: alltables; Type: PUBLICATION; Schema: -; Owner: f0ckm
--
@@ -2759,4 +2844,104 @@ CREATE INDEX IF NOT EXISTS idx_user_ips_user_id ON user_ips(user_id);
-- Add IP tracking to user_sessions for "current" IP view
ALTER TABLE user_sessions ADD COLUMN IF NOT EXISTS ip TEXT;
-- DM encrypted attachments (Migration 005)
CREATE TABLE IF NOT EXISTS public.dm_attachments (
id bigserial PRIMARY KEY,
sender_id integer NOT NULL REFERENCES public."user"(id) ON DELETE CASCADE,
recipient_id integer NOT NULL REFERENCES public."user"(id) ON DELETE CASCADE,
iv text NOT NULL,
file_path text NOT NULL,
original_name text NOT NULL DEFAULT '',
mime_hint text NOT NULL DEFAULT '',
size_bytes integer NOT NULL DEFAULT 0,
created_at timestamp with time zone DEFAULT now(),
expires_at timestamp with time zone DEFAULT (now() + interval '90 days')
);
CREATE INDEX IF NOT EXISTS idx_dm_att_sender ON public.dm_attachments(sender_id);
CREATE INDEX IF NOT EXISTS idx_dm_att_recipient ON public.dm_attachments(recipient_id);
CREATE INDEX IF NOT EXISTS idx_dm_att_expires ON public.dm_attachments(expires_at);
-- DM message edit/delete support (Migration 006)
ALTER TABLE private_messages
ADD COLUMN IF NOT EXISTS edited_at timestamp with time zone DEFAULT NULL;
-- Wordfilter Table (Migration 009)
CREATE TABLE IF NOT EXISTS public.wordfilter (
id SERIAL PRIMARY KEY,
word VARCHAR(255) UNIQUE NOT NULL,
replacement VARCHAR(255) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Comment Polls
CREATE TABLE IF NOT EXISTS public.comment_polls (
id SERIAL PRIMARY KEY,
comment_id INTEGER NOT NULL REFERENCES public.comments(id) ON DELETE CASCADE,
question TEXT NOT NULL,
is_anonymous BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
expires_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
UNIQUE(comment_id)
);
CREATE TABLE IF NOT EXISTS public.comment_poll_options (
id SERIAL PRIMARY KEY,
poll_id INTEGER NOT NULL REFERENCES public.comment_polls(id) ON DELETE CASCADE,
text TEXT NOT NULL,
sort_order SMALLINT NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS public.comment_poll_votes (
id SERIAL PRIMARY KEY,
poll_id INTEGER NOT NULL REFERENCES public.comment_polls(id) ON DELETE CASCADE,
option_id INTEGER NOT NULL REFERENCES public.comment_poll_options(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES public."user"(id) ON DELETE CASCADE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(poll_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_comment_polls_comment_id ON public.comment_polls(comment_id);
CREATE INDEX IF NOT EXISTS idx_comment_poll_options_poll ON public.comment_poll_options(poll_id);
CREATE INDEX IF NOT EXISTS idx_comment_poll_votes_poll ON public.comment_poll_votes(poll_id);
CREATE INDEX IF NOT EXISTS idx_comment_poll_votes_user ON public.comment_poll_votes(user_id);
-- Sticker Packs (Migration 010)
-- sticker_packs table: holds imported Telegram (or custom) sticker pack metadata
CREATE TABLE IF NOT EXISTS public.sticker_packs (
id serial PRIMARY KEY,
name text NOT NULL,
tg_name text UNIQUE,
tg_title text,
thumb_url text,
sticker_count integer DEFAULT 0,
created_at timestamp with time zone DEFAULT now()
);
ALTER TABLE public.sticker_packs OWNER TO f0ckm;
-- Link custom_emojis to a sticker pack (NULL = standalone emoji)
ALTER TABLE public.custom_emojis
ADD COLUMN IF NOT EXISTS pack_id integer REFERENCES public.sticker_packs(id) ON DELETE SET NULL;
-- Ensure thumb_url exists even on databases created before this column was added
ALTER TABLE public.sticker_packs
ADD COLUMN IF NOT EXISTS thumb_url text;
CREATE INDEX IF NOT EXISTS custom_emojis_pack_id_idx ON public.custom_emojis (pack_id);
-- User Emoji Favorites (Migration 011)
-- Persists per-user sticker/emoji favorites for cross-device sync
CREATE TABLE IF NOT EXISTS public.user_emoji_favorites (
user_id integer NOT NULL REFERENCES public."user"(id) ON DELETE CASCADE,
emoji_name text NOT NULL,
emoji_url text NOT NULL,
created_at timestamp with time zone NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, emoji_name)
);
ALTER TABLE public.user_emoji_favorites OWNER TO f0ckm;
CREATE INDEX IF NOT EXISTS idx_user_emoji_favorites_user_id ON public.user_emoji_favorites (user_id);
\unrestrict RMNKNzVQLV2ZcwmM3bmhglTot5nRoju9FmRyi3eUMfNy6iJUBfHRIgXnbrpJikG

357
public/s/css/98.css Normal file
View File

@@ -0,0 +1,357 @@
git pu/* 98.css framework - Scoped exclusively for f0ck98 theme */
@font-face {
font-family: "Pixelated MS Sans Serif";
font-style: normal;
font-weight: 400;
src: url("/s/fonts/ms_sans_serif.woff2") format("woff2");
}
@font-face {
font-family: "Pixelated MS Sans Serif";
font-style: normal;
font-weight: 700;
src: url("/s/fonts/ms_sans_serif_bold.woff2") format("woff2");
}
html[theme="f0ck98"] {
--w98-silver: #c0c0c0;
--w98-teal: #008080;
--w98-navy: #000080;
--w98-navy-gradient: linear-gradient(90deg, navy, #1084d0);
--w98-dark-shadow: #0a0a0a;
--w98-light-highlight: #ffffff;
--w98-mid-gray: grey;
--w98-light-gray: #dfdfdf;
color: #000;
font-family: "Pixelated MS Sans Serif", Arial, sans-serif;
font-size: 11px;
background-color: var(--w98-silver) !important;
background: var(--w98-silver) !important;
}
html[theme="f0ck98"] body {
color: #000;
font-family: "Pixelated MS Sans Serif", Arial, sans-serif;
font-size: 11px;
}
html[theme="f0ck98"] .title-bar,
html[theme="f0ck98"] .window,
html[theme="f0ck98"] button,
html[theme="f0ck98"] input,
html[theme="f0ck98"] label,
html[theme="f0ck98"] legend,
html[theme="f0ck98"] li[role=tab],
html[theme="f0ck98"] option,
html[theme="f0ck98"] select,
html[theme="f0ck98"] table,
html[theme="f0ck98"] textarea,
html[theme="f0ck98"] ul.tree-view {
-webkit-font-smoothing: none;
font-family: "Pixelated MS Sans Serif", Arial, sans-serif;
font-size: 11px;
}
html[theme="f0ck98"] u {
border-bottom: 0.5px solid #222;
text-decoration: none;
}
/* Windows 98 Buttons */
html[theme="f0ck98"] button,
html[theme="f0ck98"] input[type=reset],
html[theme="f0ck98"] input[type=submit],
html[theme="f0ck98"] .btn {
background: silver;
border: none;
border-radius: 0;
box-shadow: inset -1px -1px #0a0a0a, inset 1px 1px #fff, inset -2px -2px grey, inset 2px 2px #dfdfdf;
box-sizing: border-box;
color: #000;
min-height: 23px;
}
html[theme="f0ck98"] button.default,
html[theme="f0ck98"] input[type=reset].default,
html[theme="f0ck98"] input[type=submit].default,
html[theme="f0ck98"] .btn.default {
box-shadow: inset -2px -2px #0a0a0a, inset 1px 1px #0a0a0a, inset 2px 2px #fff, inset -3px -3px grey, inset 3px 3px #dfdfdf;
}
html[theme="f0ck98"] .vertical-bar {
background: silver;
box-shadow: inset -1px -1px #0a0a0a, inset 1px 1px #fff, inset -2px -2px grey, inset 2px 2px #dfdfdf;
height: 20px;
width: 4px;
}
html[theme="f0ck98"] button:not(:disabled):active,
html[theme="f0ck98"] input[type=reset]:not(:disabled):active,
html[theme="f0ck98"] input[type=submit]:not(:disabled):active,
html[theme="f0ck98"] .btn:not(:disabled):active {
box-shadow: inset -1px -1px #fff, inset 1px 1px #0a0a0a, inset -2px -2px #dfdfdf, inset 2px 2px grey;
}
html[theme="f0ck98"] button.default:not(:disabled):active,
html[theme="f0ck98"] input[type=reset].default:not(:disabled):active,
html[theme="f0ck98"] input[type=submit].default:not(:disabled):active {
box-shadow: inset 2px 2px #0a0a0a, inset -1px -1px #0a0a0a, inset -2px -2px #fff, inset 3px 3px grey, inset -3px -3px #dfdfdf;
}
html[theme="f0ck98"] button:focus,
html[theme="f0ck98"] input[type=reset]:focus,
html[theme="f0ck98"] input[type=submit]:focus,
html[theme="f0ck98"] .btn:focus {
outline: 1px dotted #000;
outline-offset: -4px;
}
html[theme="f0ck98"] :disabled,
html[theme="f0ck98"] :disabled+label,
html[theme="f0ck98"] input[readonly],
html[theme="f0ck98"] input[readonly]+label {
color: grey;
}
html[theme="f0ck98"] :disabled+label,
html[theme="f0ck98"] button:disabled,
html[theme="f0ck98"] input[type=reset]:disabled,
html[theme="f0ck98"] input[type=submit]:disabled,
html[theme="f0ck98"] .btn:disabled {
text-shadow: 1px 1px 0 #fff;
}
/* Window Shell & Title Bars */
html[theme="f0ck98"] .window {
background: silver;
box-shadow: inset -1px -1px #0a0a0a, inset 1px 1px #dfdfdf, inset -2px -2px grey, inset 2px 2px #fff;
padding: 3px;
}
html[theme="f0ck98"] .title-bar {
align-items: center;
background: linear-gradient(90deg, navy, #1084d0);
display: flex;
justify-content: space-between;
padding: 3px 2px 3px 3px;
}
html[theme="f0ck98"] .title-bar.inactive {
background: linear-gradient(90deg, grey, #b5b5b5);
}
html[theme="f0ck98"] .title-bar-text {
color: #fff;
font-weight: 700;
letter-spacing: 0;
margin-right: 24px;
}
html[theme="f0ck98"] .title-bar-controls {
display: flex;
}
html[theme="f0ck98"] .title-bar-controls button {
display: block;
min-height: 14px;
min-width: 16px;
padding: 0;
}
html[theme="f0ck98"] .title-bar-controls button:active {
padding: 0;
}
html[theme="f0ck98"] .title-bar-controls button:focus {
outline: none;
}
html[theme="f0ck98"] .title-bar-controls button[aria-label=Minimize],
html[theme="f0ck98"] .title-bar-controls button[aria-label].minimize {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='6' height='2' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%23000' d='M0 0h6v2H0z'/%3E%3C/svg%3E");
background-position: bottom 3px left 4px;
background-repeat: no-repeat;
}
html[theme="f0ck98"] .title-bar-controls button[aria-label=Maximize],
html[theme="f0ck98"] .title-bar-controls button[aria-label].maximize {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='9' height='9' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M9 0H0v9h9V0zM8 2H1v6h7V2z' fill='%23000'/%3E%3C/svg%3E");
background-position: top 2px left 3px;
background-repeat: no-repeat;
}
html[theme="f0ck98"] .title-bar-controls button[aria-label=Close],
html[theme="f0ck98"] .title-bar-controls button[aria-label].close {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='8' height='7' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0 0h2v1h1v1h2V1h1V0h2v1H7v1H6v1H5v1h1v1h1v1h1v1H6V6H5V5H3v1H2v1H0V6h1V5h1V4h1V3H2V2H1V1H0V0z' fill='%23000'/%3E%3C/svg%3E");
background-position: top 3px left 4px;
background-repeat: no-repeat;
margin-left: 2px;
}
/* Status Bar */
html[theme="f0ck98"] .status-bar {
gap: 1px;
display: flex;
margin: 0 1px;
}
html[theme="f0ck98"] .status-bar-field {
box-shadow: inset -1px -1px #dfdfdf, inset 1px 1px grey;
flex-grow: 1;
margin: 0;
padding: 2px 3px;
}
html[theme="f0ck98"] .window-body {
margin: 8px;
}
html[theme="f0ck98"] fieldset {
border-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='5' height='5' fill='gray' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0 0h5v5H0V2h2v1h1V2H0' fill='%23fff'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M0 0h4v4H0V1h1v2h2V1H0'/%3E%3C/svg%3E") 2;
margin: 0;
padding: 10px;
padding-block-start: 8px;
}
html[theme="f0ck98"] legend {
background: silver;
}
html[theme="f0ck98"] .field-row {
align-items: center;
display: flex;
}
html[theme="f0ck98"] [class^=field-row]+[class^=field-row] {
margin-top: 6px;
}
html[theme="f0ck98"] .field-row>*+* {
margin-left: 6px;
}
html[theme="f0ck98"] label {
align-items: center;
display: inline-flex;
user-select: none;
}
/* Form Inputs & Textarea */
html[theme="f0ck98"] input[type=email],
html[theme="f0ck98"] input[type=number],
html[theme="f0ck98"] input[type=password],
html[theme="f0ck98"] input[type=search],
html[theme="f0ck98"] input[type=tel],
html[theme="f0ck98"] input[type=text],
html[theme="f0ck98"] input[type=url],
html[theme="f0ck98"] select,
html[theme="f0ck98"] textarea {
background-color: #fff;
box-shadow: inset -1px -1px #fff, inset 1px 1px grey, inset -2px -2px #dfdfdf, inset 2px 2px #0a0a0a;
box-sizing: border-box;
padding: 3px 4px;
border: none;
border-radius: 0;
color: #000;
}
html[theme="f0ck98"] input[type=email]:disabled,
html[theme="f0ck98"] input[type=number]:disabled,
html[theme="f0ck98"] input[type=password]:disabled,
html[theme="f0ck98"] input[type=search]:disabled,
html[theme="f0ck98"] input[type=tel]:disabled,
html[theme="f0ck98"] input[type=text]:disabled,
html[theme="f0ck98"] input[type=url]:disabled,
html[theme="f0ck98"] textarea:disabled {
background-color: silver;
}
html[theme="f0ck98"] select {
appearance: none;
-webkit-appearance: none;
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='16' height='17' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M15 0H0v16h1V1h14V0z' fill='%23DFDFDF'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M2 1H1v14h1V2h12V1H2z' fill='%23fff'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M16 17H0v-1h15V0h1v17z' fill='%23000'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M15 1h-1v14H1v1h14V1z' fill='gray'/%3E%3Cpath fill='silver' d='M2 2h12v13H2z'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M11 6H4v1h1v1h1v1h1v1h1V9h1V8h1V7h1V6z' fill='%23000'/%3E%3C/svg%3E");
background-position: top 2px right 2px;
background-repeat: no-repeat;
border-radius: 0;
padding-right: 32px;
}
html[theme="f0ck98"] input[type=email]:focus,
html[theme="f0ck98"] input[type=number]:focus,
html[theme="f0ck98"] input[type=password]:focus,
html[theme="f0ck98"] input[type=search]:focus,
html[theme="f0ck98"] input[type=tel]:focus,
html[theme="f0ck98"] input[type=text]:focus,
html[theme="f0ck98"] input[type=url]:focus,
html[theme="f0ck98"] select:focus,
html[theme="f0ck98"] textarea:focus {
outline: none;
}
html[theme="f0ck98"] a {
color: #000080;
}
html[theme="f0ck98"] a:focus {
outline: 1px dotted #000080;
}
html[theme="f0ck98"] .sunken-panel {
background-color: #fff;
box-shadow: inset -1px -1px #fff, inset 1px 1px grey, inset -2px -2px #dfdfdf, inset 2px 2px #0a0a0a;
box-sizing: border-box;
overflow: auto;
}
/* Scoped Scrollbars for f0ck98 */
html[theme="f0ck98"] ::-webkit-scrollbar {
width: 16px;
height: 17px;
}
html[theme="f0ck98"] ::-webkit-scrollbar-corner {
background: #dfdfdf;
}
html[theme="f0ck98"] ::-webkit-scrollbar-track {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='2' height='2' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M1 0H0v1h1v1h1V1H1V0z' fill='silver'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M2 0H1v1H0v1h1V1h1V0z' fill='%23fff'/%3E%3C/svg%3E");
}
html[theme="f0ck98"] ::-webkit-scrollbar-thumb {
background-color: #dfdfdf;
box-shadow: inset -1px -1px #0a0a0a, inset 1px 1px #fff, inset -2px -2px grey, inset 2px 2px #dfdfdf;
}
html[theme="f0ck98"] ::-webkit-scrollbar-button:vertical:start {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='16' height='17' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M15 0H0v16h1V1h14V0z' fill='%23DFDFDF'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M2 1H1v14h1V2h12V1H2z' fill='%23fff'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M16 17H0v-1h15V0h1v17z' fill='%23000'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M15 1h-1v14H1v1h14V1z' fill='gray'/%3E%3Cpath fill='silver' d='M2 2h12v13H2z'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8 6H7v1H6v1H5v1H4v1h7V9h-1V8H9V7H8V6z' fill='%23000'/%3E%3C/svg%3E");
height: 17px;
display: block;
}
html[theme="f0ck98"] ::-webkit-scrollbar-button:vertical:end {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='16' height='17' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M15 0H0v16h1V1h14V0z' fill='%23DFDFDF'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M2 1H1v14h1V2h12V1H2z' fill='%23fff'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M16 17H0v-1h15V0h1v17z' fill='%23000'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M15 1h-1v14H1v1h14V1z' fill='gray'/%3E%3Cpath fill='silver' d='M2 2h12v13H2z'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M11 6H4v1h1v1h1v1h1v1h1V9h1V8h1V7h1V6z' fill='%23000'/%3E%3C/svg%3E");
height: 17px;
display: block;
}
html[theme="f0ck98"] .sidebar-activity .comment-content.has-overflow:not(.expanded) .comment-content-inner::after {
background: linear-gradient(to bottom, transparent, rgb(192, 192, 192));
}
html[theme="f0ck98"] .item-sidebar-right, .index-sidebar-right, .global-sidebar-right {
box-shadow: none!important;
}
html[theme="f0ck98"] .sidebar-activity .read-more-btn, .sidebar-activity .see-less-btn {
padding: 5px;
}
html[theme="f0ck98"] .modal-content p {
color: var(--black);
}
html[theme="f0ck98"] .drop-zone {
border: 2px dashed rgba(0, 0, 0, 0.2);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +1,21 @@
@font-face {
font-family: 'Impact';
src: url('/s/fonts/impact.woff') format('woff');
font-weight: normal;
}
@font-face {
font-family: 'Impact';
src: url('/s/fonts/impact.woff') format('woff');
font-weight: bold;
}
/* Meme Creator Styles */
.meme-creator-container {
box-sizing: border-box !important;
padding: 20px;
max-width: 1200px;
max-width: 1100px;
width: 100%;
margin: 0 auto;
position: relative;
@@ -104,6 +112,7 @@
.canvas-wrapper {
flex: 1;
max-width: 650px;
min-width: 0; /* Allow shrinking */
background: #000;
border: 2px solid var(--nav-bg, #2b2b2b);
@@ -185,6 +194,8 @@ canvas#memeCanvas {
.meme-layout-wrapper input[type="range"] {
width: 100%;
accent-color: var(--accent, #9f0);
touch-action: pan-x;
cursor: pointer;
}
.meme-layout-wrapper .layer-input-group {
@@ -229,22 +240,49 @@ canvas#memeCanvas {
color: var(--white, #fff);
}
/* Mobile Stacking - Simple 2-Row Layout */
/* Mobile Stacking - Clean Flexbox Column Layout */
@media (max-width: 950px) {
.meme-editor-layout {
display: grid !important;
grid-template-columns: 1fr !important;
grid-template-rows: 0.6fr 1fr !important;
display: flex !important;
flex-direction: column !important;
align-items: center !important;
gap: 20px;
}
.meme-controls {
box-sizing: border-box !important;
width: 100% !important;
grid-row: 2;
max-width: 500px !important;
overflow: visible !important;
}
.canvas-wrapper {
box-sizing: border-box !important;
width: 100% !important;
grid-row: 1;
max-width: 650px !important;
margin-bottom: 10px;
overflow: visible !important;
height: auto !important;
}
}
/* Stack early when sidebar is open (sidebar is 300px, so 950 + 300 = 1250px)
This prevents the canvas from shrinking too much when the sidebar takes space. */
@media (max-width: 1250px) {
body:not(.sidebar-right-hidden) .meme-editor-layout {
display: flex !important;
flex-direction: column !important;
align-items: center !important;
gap: 20px;
}
body:not(.sidebar-right-hidden) .meme-controls {
box-sizing: border-box !important;
width: 100% !important;
max-width: 500px !important;
overflow: visible !important;
}
body:not(.sidebar-right-hidden) .canvas-wrapper {
box-sizing: border-box !important;
width: 100% !important;
max-width: 650px !important;
margin-bottom: 10px;
overflow: visible !important;
height: auto !important;
@@ -260,3 +298,44 @@ canvas#memeCanvas {
gap: 10px;
}
}
/* Custom Template Card & Drag Hover Styles */
.custom-template-card .template-image-wrapper {
transition: background-color 0.2s ease;
}
.custom-template-card:hover .template-image-wrapper {
background-color: rgba(255, 255, 255, 0.08) !important;
}
.custom-template-card i {
transition: transform 0.2s ease, color 0.2s ease;
}
.custom-template-card:hover i {
transform: scale(1.1);
}
.canvas-wrapper.drag-hover {
border-color: var(--accent, #9f0) !important;
box-shadow: 0 0 25px rgba(159, 255, 0, 0.4) !important;
}
/* Sidebar space reservation for meme pages */
.meme-layout-wrapper {
box-sizing: border-box !important;
width: 100%;
}
@media (min-width: 1000px) {
/* Reserve space for the fixed sidebar so content doesn't flow behind it */
body:not(.sidebar-right-hidden) .meme-layout-wrapper {
padding-right: 300px;
}
}
/* Collapse reserved space when sidebar is hidden */
body.sidebar-right-hidden .meme-layout-wrapper {
padding-right: 0 !important;
}

View File

@@ -118,7 +118,7 @@
flex-direction: column;
/* Stacked */
align-items: center;
gap: 1rem;
gap: 0.3rem;
width: 100%;
}
@@ -219,19 +219,13 @@
.upload-form:not(.shitpost-mode-active) .preview-media-small {
width: 100%;
max-width: 400px;
min-height: auto;
height: auto;
aspect-ratio: 16 / 9;
object-fit: contain;
}
.upload-form.shitpost-mode-active .preview-media-small {
width: 120px;
height: 80px;
object-fit: contain;
min-height: auto;
}
.preview-media-small {
flex-shrink: 0;
@@ -247,7 +241,7 @@
align-items: center;
}
.upload-form.shitpost-mode-active .file-meta-row-small {
.upload-form.shitpost-mode-active .file-name-small {
padding-right: 30px; /* Space for X button */
}
@@ -255,8 +249,9 @@
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
overflow: visible;
min-width: 0;
width: 100%;
}
.file-info-small {
@@ -403,56 +398,71 @@
color: rgba(255, 255, 255, 0.4);
transition: all 0.2s;
text-transform: uppercase;
user-select: none;
}
.item-rating-option input:checked + .item-rating-label.sfw {
background: #40c057;
background: var(--badge-sfw);
color: #fff;
border-color: #40c057;
border-color: var(--badge-sfw);
}
.item-rating-option input:checked + .item-rating-label.nsfw {
background: #fd7e14;
background: var(--badge-nsfw);
color: #fff;
border-color: #fd7e14;
border-color: var(--badge-nsfw);
}
.item-rating-option input:checked + .item-rating-label.nsfl {
background: #fa5252;
background: var(--badge-nsfl);
color: #fff;
border-color: #fa5252;
border-color: var(--badge-nsfl);
}
.item-rating-label:hover {
background: rgba(255, 255, 255, 0.1);
}
/* Bigger Previews in Shitpost Mode */
.file-preview-item {
.upload-form.shitpost-mode-active .file-preview-item {
display: flex;
flex-direction: row;
align-items: flex-start;
padding: 15px;
gap: 0;
gap: 16px;
width: 100%;
border-bottom: 1px solid rgba(255,255,255,0.05);
}
.preview-media-small {
.upload-form.shitpost-mode-active .preview-media-small {
flex: 0 0 50%;
width: 50% !important;
height: auto !important;
min-height: 120px;
max-height: 350px;
max-width: 50% !important;
height: 240px !important;
max-height: 240px !important;
object-fit: contain;
border-radius: 8px;
background: rgba(0,0,0,0.3);
overflow: hidden; /* Clip the video — Chrome cannot expand past this */
}
/* Inner video inside the wrapper fills the container and cannot resize it */
.upload-form.shitpost-mode-active .preview-video-wrapper > video {
width: 100% !important;
height: 100% !important;
max-width: 100% !important;
max-height: 100% !important;
display: block;
object-fit: contain;
}
/* Per-item Tags */
.item-tags-container {
margin-top: 10px;
width: 100%;
position: relative;
}
.item-tags-list {
@@ -549,6 +559,34 @@
border-color: var(--accent);
}
.item-title-container {
margin-top: 6px;
width: 100%;
}
.item-title-input {
width: 100%;
background: rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 4px;
padding: 5px 10px;
color: #fff;
font-size: 0.8rem;
font-family: inherit;
outline: none;
transition: border-color 0.2s;
box-sizing: border-box;
}
.item-title-input::placeholder {
color: rgba(255,255,255,0.3);
font-style: italic;
}
.item-title-input:focus {
border-color: var(--accent);
}
.rating-options {
display: flex;
gap: 1rem;
@@ -676,6 +714,29 @@
outline: none;
}
/* Global title input (normal mode) — matches tag-input-container style */
.upload-title-input {
width: 100%;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 0;
padding: 0.5rem;
color: inherit;
font-family: inherit;
font-size: 0.9rem;
outline: none;
transition: border-color 0.2s;
box-sizing: border-box;
}
.upload-title-input:focus {
border-color: var(--accent, #7c5cbf);
}
.upload-title-input::placeholder {
color: rgba(255, 255, 255, 0.3);
}
.tag-count {
font-weight: normal;
font-size: 0.85rem;
@@ -735,9 +796,9 @@
.upload-form .tag-suggestions {
position: absolute !important;
min-width: 220px !important;
max-width: 320px !important;
max-height: 260px !important;
min-width: 220px;
max-width: 320px;
max-height: 260px;
overflow-y: auto !important;
background: var(--dropdown-bg, #1a1a1a) !important;
border: 1px solid var(--black, #000) !important;
@@ -750,9 +811,7 @@
scrollbar-width: thin !important;
}
.upload-form.shitpost-mode-active .tag-suggestions {
position: relative !important;
}
@keyframes tagDropIn {
from {
@@ -1243,7 +1302,7 @@
flex-shrink: 0;
}
@media (max-width: 600px) {
@media (max-width: 768px) {
.upload-form.shitpost-mode-active .file-preview-item {
flex-direction: column;
align-items: stretch;
@@ -1253,6 +1312,7 @@
.upload-form.shitpost-mode-active .preview-media-small,
.upload-form.shitpost-mode-active .item-media-col {
width: 100% !important;
max-width: 100% !important;
flex: 0 0 auto;
min-height: auto;
}
@@ -1260,4 +1320,341 @@
.upload-form.shitpost-mode-active .item-media-col iframe {
height: 200px;
}
/* Keep suggestions visible and position them above the tag input */
.upload-form.shitpost-mode-active .file-meta-row-small {
overflow: visible !important;
}
.upload-form.shitpost-mode-active .tag-suggestions {
position: absolute !important;
bottom: 100% !important;
top: auto !important;
left: 0 !important;
right: 0 !important;
width: 100% !important;
max-width: none !important;
margin-top: 0 !important;
margin-bottom: 8px !important;
z-index: 200000 !important;
}
}
/* Video thumbnail loading animation */
.video-thumbnail-loading {
animation: thumbPulse 1.5s ease-in-out infinite;
background: rgba(255, 255, 255, 0.05);
}
@keyframes thumbPulse {
0% { opacity: 0.4; }
50% { opacity: 0.8; }
100% { opacity: 0.4; }
}
/* ── Ruffle (Flash) Upload Preview ─────────────────────────────────────────── */
/* The container: CSS Grid with 3 rows — player | snapshot preview | button.
All rows are auto so the container grows naturally; no overflow clipping. */
.swf-upload-preview {
position: relative;
display: grid;
grid-template-rows: auto auto auto;
max-height: none !important;
background: #000;
border-radius: 8px;
}
/* Normal (non-shitpost) mode: full-width, player drives container height via aspect-ratio */
.upload-form:not(.shitpost-mode-active) .swf-upload-preview.preview-media-small {
width: 100% !important;
height: auto !important;
max-height: none !important;
min-height: auto !important;
}
.upload-form:not(.shitpost-mode-active) .swf-upload-preview ruffle-player,
.upload-form:not(.shitpost-mode-active) .swf-upload-preview ruffle-object {
aspect-ratio: 16 / 9;
width: 100% !important;
height: auto !important;
}
/* Shitpost mode: player row is a fixed height so the snapshot row doesn't steal its space */
.upload-form.shitpost-mode-active .swf-upload-preview.preview-media-small {
width: 45% !important;
flex: 0 0 45% !important;
height: auto !important;
max-height: none !important;
min-height: auto !important;
aspect-ratio: unset;
}
.upload-form.shitpost-mode-active .swf-upload-preview ruffle-player,
.upload-form.shitpost-mode-active .swf-upload-preview ruffle-object {
width: 100% !important;
height: 220px !important;
min-height: 220px;
}
/* Placeholder shown while Ruffle is loading */
.swf-upload-placeholder {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
min-height: 200px;
background: rgba(0, 0, 0, 0.6);
animation: thumbPulse 1.8s ease-in-out infinite;
}
.swf-upload-placeholder-icon {
font-size: 2.5rem;
line-height: 1;
filter: drop-shadow(0 0 8px rgba(255, 200, 0, 0.7));
}
.swf-upload-placeholder-text {
font-size: 0.8rem;
color: rgba(255, 255, 255, 0.5);
letter-spacing: 0.5px;
}
/* ── Ruffle Snapshot Button ─────────────────────────────────────────────────── */
/* The snapshot button lives inside .swf-upload-preview, pinned to the bottom */
.swf-upload-preview {
position: relative;
display: flex;
flex-direction: column;
}
.btn-ruffle-snapshot {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
margin-top: 0;
padding: 8px 16px;
background: rgba(255, 200, 0, 0.08);
border: none;
border-top: 1px solid rgba(255, 200, 0, 0.2);
border-radius: 0 0 6px 6px;
color: rgba(255, 200, 0, 0.9);
font-size: 0.85rem;
font-weight: 600;
font-family: inherit;
cursor: pointer;
transition: all 0.2s ease;
letter-spacing: 0.3px;
flex-shrink: 0;
}
.btn-ruffle-snapshot:hover:not(:disabled) {
background: rgba(255, 200, 0, 0.15);
border-top-color: rgba(255, 200, 0, 0.4);
color: #ffd700;
}
.btn-ruffle-snapshot:active:not(:disabled) {
background: rgba(255, 200, 0, 0.22);
}
.btn-ruffle-snapshot:disabled {
opacity: 0.6;
cursor: not-allowed;
}
/* Snapshot preview: sits in its own grid row, below the player */
.swf-upload-preview .ruffle-snapshot-preview {
display: block;
width: 100%;
height: auto;
object-fit: contain;
object-position: center;
background: rgba(0, 0, 0, 0.6);
border-top: 1px solid rgba(81, 207, 102, 0.3);
animation: snapPreviewIn 0.35s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}
@keyframes snapPreviewIn {
from { opacity: 0; transform: scale(0.96) translateY(4px); }
to { opacity: 1; transform: scale(1) translateY(0); }
}
/* =============================================
URL Upload Tracker — single persistent panel
============================================= */
#url-upload-tracker {
position: fixed;
bottom: 20px;
left: 20px;
z-index: 9998;
width: 320px;
background: var(--nav-bg, #1c1c1c);
border: 1px solid rgba(var(--accent-rgb, 120,120,120), 0.15);
overflow: hidden;
font-size: 0.8rem;
opacity: 0;
transform: translateY(10px);
transition: opacity 1.5s ease, transform 1.5s ease;
pointer-events: none;
}
#url-upload-tracker.uut-visible {
opacity: 1;
transform: translateY(0);
pointer-events: all;
}
/* ── Header ──────────────────────────────────────── */
.uut-header {
display: flex;
align-items: center;
gap: 7px;
padding: 8px 10px 8px 12px;
background: rgba(var(--accent-rgb, 120,120,120), 0.07);
border-bottom: 1px solid rgba(var(--accent-rgb, 120,120,120), 0.1);
user-select: none;
}
.uut-header > .fa-solid {
color: var(--accent);
font-size: 11px;
opacity: 0.75;
flex-shrink: 0;
}
.uut-title {
flex: 1;
font-size: 0.74rem;
font-weight: 600;
color: var(--white, #fff);
letter-spacing: 0.01em;
}
.uut-badge {
background: var(--accent);
color: #fff;
font-size: 0.62rem;
font-weight: 700;
min-width: 16px;
height: 16px;
border-radius: 8px;
padding: 0 4px;
display: inline-flex;
align-items: center;
justify-content: center;
}
.uut-actions { display: flex; gap: 2px; }
.uut-btn {
background: none;
border: none;
cursor: pointer;
color: var(--white, #fff);
opacity: 0.3;
padding: 3px 6px;
border-radius: 4px;
font-size: 12px;
line-height: 1;
transition: opacity 0.15s, background 0.15s;
}
.uut-btn:hover { opacity: 0.8; background: rgba(var(--accent-rgb,120,120,120),0.12); }
/* ── Body (scrollable) ───────────────────────────── */
.uut-body {
max-height: 340px;
overflow-y: auto;
overflow-x: hidden;
scrollbar-width: thin;
scrollbar-color: rgba(var(--accent-rgb,120,120,120), 0.25) transparent;
}
/* ── Active job rows ─────────────────────────────── */
.uut-job {
padding: 8px 12px 6px;
border-bottom: 1px solid rgba(var(--accent-rgb,120,120,120), 0.06);
transition: opacity 0.3s;
}
.uut-job--fading { opacity: 0; }
.uut-job-row {
display: flex;
align-items: flex-start;
gap: 8px;
}
.uut-spinner {
width: 11px;
height: 11px;
flex-shrink: 0;
margin-top: 3px;
border: 1.5px solid rgba(var(--accent-rgb,120,120,120), 0.18);
border-top-color: var(--accent);
border-radius: 50%;
animation: uutSpin 0.75s linear infinite;
}
@keyframes uutSpin { to { transform: rotate(360deg); } }
.uut-job-info { flex: 1; min-width: 0; }
.uut-url {
display: block;
font-size: 0.72rem;
color: var(--white, #fff);
opacity: 0.65;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.uut-meta {
display: flex;
align-items: center;
gap: 6px;
margin-top: 2px;
}
.uut-stage {
font-size: 0.71rem;
color: var(--accent);
white-space: nowrap;
}
.uut-speed {
font-size: 0.67rem;
color: var(--white, #fff);
opacity: 0.38;
margin-left: auto;
white-space: nowrap;
}
/* Progress bar */
.uut-bar {
height: 2px;
background: rgba(var(--accent-rgb,120,120,120), 0.1);
border-radius: 2px;
overflow: hidden;
margin-top: 6px;
}
.uut-bar-fill {
height: 100%;
background: var(--accent);
border-radius: 2px;
transition: width 0.65s ease;
background-image: linear-gradient(90deg, var(--accent) 0%, rgba(255,255,255,0.4) 50%, var(--accent) 100%);
background-size: 200% 100%;
animation: uutShimmer 1.6s linear infinite;
}
@keyframes uutShimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }

View File

@@ -138,13 +138,11 @@
transform: translateY(100%) translateY(-3px);
}
.v0ck:hover .v0ck_player_controls,
.v0ck.v0ck_hover .v0ck_player_controls,
.v0ck.v0ck_swf_active .v0ck_player_controls {
transform: translateY(0);
}
.v0ck:hover .v0ck_progress,
.v0ck.v0ck_hover .v0ck_progress,
.v0ck.v0ck_swf_active .v0ck_progress {
height: 8px;
@@ -434,8 +432,9 @@
padding: 0 3px;
text-shadow: none;
}
/* Hide images (emojis, inline imgs) inside unrevealed spoiler */
.danmaku-pill .dpill-spoiler img {
/* Hide images/videos (emojis, inline imgs, webm stickers) inside unrevealed spoiler */
.danmaku-pill .dpill-spoiler img,
.danmaku-pill .dpill-spoiler video {
opacity: 0;
transition: opacity 0.15s ease;
}
@@ -448,7 +447,9 @@
-1px 1px 0 #000, 1px 1px 0 #000;
}
.danmaku-pill .dpill-spoiler:hover img,
.danmaku-pill .dpill-spoiler.revealed img {
.danmaku-pill .dpill-spoiler.revealed img,
.danmaku-pill .dpill-spoiler:hover video,
.danmaku-pill .dpill-spoiler.revealed video {
opacity: 1;
}
@@ -511,4 +512,39 @@
@keyframes danmaku-fly {
from { transform: translateX(calc(100vw + 100%)); }
to { transform: translateX(calc(-100% - 200px)); }
}
/* Speedup 2x HUD Pill */
.v0ck_speed_indicator {
position: absolute;
top: 20px;
left: 50%;
transform: translate(-50%, -10px);
background: rgba(0, 0, 0, 0.75);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
color: #fff;
padding: 8px 16px;
border-radius: 20px;
font-size: 14px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s, transform 0.2s;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
}
.v0ck_speed_indicator:not(.v0ck_hidden) {
opacity: 1;
transform: translate(-50%, 0);
}
/* Hide mouse cursor on inactivity in fullscreen */
.v0ck.v0ck_fullscreen:not(.v0ck_hover),
.v0ck.v0ck_fullscreen:not(.v0ck_hover) * {
cursor: none !important;
}

Binary file not shown.

Binary file not shown.

BIN
public/s/img/archive.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg">
<!-- Font Awesome Free 5.15.3 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) -->
<defs>
<symbol id="heart_regular" viewBox="0 0 512 512"><path d="M458.4 64.3C400.6 15.7 311.3 23 256 79.3 200.7 23 111.4 15.6 53.6 64.3-21.6 127.6-10.6 230.8 43 285.5l175.4 178.7c10 10.2 23.4 15.9 37.6 15.9 14.3 0 27.6-5.6 37.6-15.8L469 285.6c53.5-54.7 64.7-157.9-10.6-221.3zm-23.6 187.5L259.4 430.5c-2.4 2.4-4.4 2.4-6.8 0L77.2 251.8c-36.5-37.2-43.9-107.6 7.3-150.7 38.9-32.7 98.9-27.8 136.5 10.5l35 35.7 35-35.7c37.8-38.5 97.8-43.2 136.5-10.6 51.1 43.1 43.5 113.9 7.3 150.8z"/></symbol>
<symbol id="heart_solid" viewBox="0 0 512 512"><path d="M462.3 62.6C407.5 15.9 326 24.3 275.7 76.2L256 96.5l-19.7-20.3C186.1 24.3 104.5 15.9 49.7 62.6c-62.8 53.6-66.1 149.8-9.9 207.9l193.5 199.8c12.5 12.9 32.8 12.9 45.3 0l193.5-199.8c56.3-58.1 53-154.3-9.8-207.9z"/></symbol>
<symbol id="cross" viewBox="0 0 512 512"><path d="M53.6,62.3 L458.4,458.4 M458.4,62.3 L53.6,458.4" style="stroke-linecap: round;stroke-width: 60;"/></symbol>
<symbol id="window-maximize" viewBox="0 0 512 512"><path d="M464 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h416c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm0 394c0 3.3-2.7 6-6 6H54c-3.3 0-6-2.7-6-6V192h416v234z" style="fill: var(--maximize_button);"/></symbol>
<symbol id="window-minimize" viewBox="0 0 512 512"><path d="M464 0H144c-26.5 0-48 21.5-48 48v48H48c-26.5 0-48 21.5-48 48v320c0 26.5 21.5 48 48 48h320c26.5 0 48-21.5 48-48v-48h48c26.5 0 48-21.5 48-48V48c0-26.5-21.5-48-48-48zm-96 464H48V256h320v208zm96-96h-48V144c0-26.5-21.5-48-48-48H144V48h320v320z" style="fill: var(--maximize_button);"/></symbol>
<symbol id="plus" viewBox="0 0 512 512"><path d="M256 80c0-8.84-7.16-16-16-16s-16 7.16-16 16v160H64c-8.84 0-16 7.16-16 16s7.16 16 16 16h160v160c0 8.84 7.16 16 16 16s16-7.16 16-16V272h160c8.84 0 16-7.16 16-16s-7.16-16-16-16H272V80z"/></symbol>
<symbol id="tag" viewBox="0 0 512 512"><path d="M0 252.118V48C0 21.49 21.49 0 48 0h204.118a48 48 0 0 1 33.941 14.059l211.882 211.882c18.745 18.745 18.745 49.137 0 67.882L293.823 497.941c-18.745 18.745-49.137 18.745-67.882 0L14.059 286.059A48 48 0 0 1 0 252.118zM112 64a48 48 0 1 0 48 48 48.055 48.055 0 0 0-48-48z"/></symbol>
<symbol id="shield" viewBox="0 0 512 512"><path d="M466.5 83.71c-19.2-4.44-45.2-14.91-45.2-14.91a27.29 27.29 0 0 0-21.6 0s-26 10.47-45.2 14.91a27.3 27.3 0 0 1-31.4-18.41V28c0-15.46-12.54-28-28-28h-74.8c-15.46 0-28 12.54-28 28v37.39a27.3 27.3 0 0 1-31.4 18.41c-19.2-4.44-45.2-14.91-45.2-14.91a27.29 27.29 0 0 0-21.6 0s-26 10.47-45.2 14.91A27.3 27.3 0 0 1 12 102.12V256c0 141.38 102.34 230.13 234.33 254.12a27.5 27.5 0 0 0 9.34 0C387.66 486.13 490 397.38 490 256V102.12a27.3 27.3 0 0 1-23.5-18.41z"/></symbol>
<symbol id="bell_solid" viewBox="0 0 448 512"><path d="M224 512c35.32 0 63.97-28.65 63.97-64H160.03c0 35.35 28.65 64 63.97 64zm215.39-149.71c-19.32-20.76-55.47-51.99-55.47-154.29 0-77.7-54.48-139.9-127.94-155.16V32c0-17.67-14.32-32-31.98-32s-31.98 14.33-31.98 32v20.84C118.56 68.1 64.08 130.3 64.08 208c0 102.3-36.15 133.53-55.47 154.29-6 6.45-8.66 14.16-8.61 21.71.11 16.4 12.98 32 32.1 32h383.8c19.12 0 32-15.6 32.1-32 .05-7.55-2.61-15.27-8.61-21.71z"/></symbol>
<symbol id="bell_regular" viewBox="0 0 448 512"><path d="M224 512c35.32 0 63.97-28.65 63.97-64H160.03c0 35.35 28.65 64 63.97 64zm215.39-149.71c-19.32-20.76-55.47-51.99-55.47-154.29 0-77.7-54.48-139.9-127.94-155.16V32c0-17.67-14.32-32-31.98-32s-31.98 14.33-31.98 32v20.84C118.56 68.1 64.08 130.3 64.08 208c0 102.3-36.15 133.53-55.47 154.29-6 6.45-8.66 14.16-8.61 21.71.11 16.4 12.98 32 32.1 32h383.8c19.12 0 32-15.6 32.1-32 .05-7.55-2.61-15.27-8.61-21.71zM44.75 330.4C63.2 312 96 281.3 96 208c0-61.94 43.15-112 112-112s112 50.06 112 112c0 73.3 32.8 104 51.25 122.4 2.8 2.8 3.5 6.9 1.75 10.4s-5.4 5.6-9.15 5.6H52.1c-3.75 0-7.35-2.1-9.1-5.6s-1.05-7.6 1.75-10.4z"/></symbol>
<symbol id="pin_solid" viewBox="0 0 24 24"><path d="M12 17h-7v-1.76a2 2 0 0 1 1.11-1.79l1.78-.9a2 0 0 0 1.11-1.76v-4.79a3 3 0 0 1 3-3 3 3 0 0 1 3 3v4.76a2 2 0 0 0 1.11 1.79l1.78.9a2 0 0 1 1.11 1.79v1.76h-7v5z" fill="currentColor" transform="rotate(45 12 12)"/></symbol>
<symbol id="pin_regular" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="17" x2="12" y2="22"></line><path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6a3 3 0 0 0-3-3 3 3 0 0 0-3 3v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V17z"></path></g></symbol>
<symbol id="building" viewBox="0 0 512 512"><path d="M432 64H80c-8.8 0-16 7.2-16 16v352c0 8.8 7.2 16 16 16h352c8.8 0 16-7.2 16-16V80c0-8.8-7.2-16-16-16zm-32 352H112V96h288v320zM192 288h128v32H192zm0-64h128v32H192zm0-64h128v32H192z" fill="currentColor"/></symbol>
<symbol id="arrow-down" viewBox="0 0 448 512"><path d="M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z" fill="currentColor"/></symbol>
<symbol id="arrow-up" viewBox="0 0 448 512"><path d="M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9l-22.2 22.2c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z" fill="currentColor"/></symbol>
<symbol id="star_regular" viewBox="0 0 576 512"><path d="M528.1 171.5L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l126.7 66.7c23.2 12.3 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6zM388.6 312.3l23.7 137.4L288 384.8l-124.3 64.9 23.7-137.4L87.5 214.4l138-20.1L288 69.1l62.5 125.2 138 20.1-99.9 97.9z" fill="currentColor"/></symbol>
<symbol id="star_solid" viewBox="0 0 576 512"><path d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l126.7 66.7c23.2 12.3 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z" fill="currentColor"/></symbol>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 6.4 KiB

View File

@@ -60,7 +60,7 @@
a.textContent = tag.tag;
const span = document.createElement("span");
span.classList.add("badge", "mr-2");
span.classList.add("badge");
if (highlightTag && (tag.tag === highlightTag || tag.normalized === highlightTag)) {
span.classList.add('new-tag-glow');
}
@@ -155,7 +155,13 @@
postid,
existingTags: tags,
anchorEl: anchor,
onSubmit: async (tag) => post("/api/v2/tags/" + postid, { tagname: tag }),
onSubmit: async (tag) => {
const res = await post("/api/v2/tags/" + postid, { tagname: tag });
if (res.success && window.invalidateItemCache) {
window.invalidateItemCache(postid);
}
return res;
},
renderTags
});
};
@@ -199,7 +205,6 @@
a.appendChild(img);
favcontainer.appendChild(a);
favcontainer.appendChild(document.createTextNode('\u00A0'));
});
favcontainer.hidden = false;
} else {
@@ -379,40 +384,91 @@
window.adminSetPassword = async (btn) => {
const id = btn.dataset.id;
const name = btn.dataset.name;
const password = prompt(`Enter new password for ${name} (min 20 chars):`);
if (!password) return;
if (password.length < 20) return alert('Password must be at least 20 characters.');
if (!confirm(`Are you sure you want to set a new password for ${name}? This will invalidate all their existing sessions and force them to change it on next login.`)) return;
if (typeof ModAction === 'undefined') return alert('Error: ModAction module not loaded');
try {
const hint =
'Set a new password for <strong>' + escHTML(name) + '</strong>. Must be at least 20 characters.<br><br>' +
'<input type="password" id="admin-pw-new" class="input" placeholder="New password (min 20 chars)" style="width:100%;margin-bottom:8px;" autocomplete="new-password">' +
'<input type="password" id="admin-pw-confirm" class="input" placeholder="Confirm new password" style="width:100%;" autocomplete="new-password">';
ModAction.confirm('Set Password', hint, async () => {
const password = document.getElementById('admin-pw-new')?.value || '';
const confirm = document.getElementById('admin-pw-confirm')?.value || '';
if (password.length < 20) throw new Error('Password must be at least 20 characters.');
if (password !== confirm) throw new Error('Passwords do not match.');
const data = await post('/api/v2/admin/users/set-password', { user_id: id, password });
if (data.success) {
alert(data.msg);
showFlash(data.msg, 'success');
} else {
alert(data.msg || 'Failed to set password');
throw new Error(data.msg || 'Failed to set password');
}
} catch (err) {
alert('Network error');
}
}, { hideReason: true, confirmText: 'Set Password', unsafeContent: true });
};
window.adminRenameUser = async (btn) => {
const id = btn.dataset.id;
const currentName = btn.dataset.name;
const currentUsername = btn.dataset.username;
if (typeof ModAction === 'undefined') return alert('Error: ModAction module not loaded');
ModAction.confirm(
'Rename User',
'Enter a new login name for <strong>' + escHTML(currentName) + '</strong>.<br>' +
'<small style="color:#888;">Current login: <code>' + escHTML(currentUsername) + '</code> — All uploads will be reassigned. User sessions will be invalidated. And the user has to login with the NEW name from now on.</small>',
async (newUsername) => {
const data = await post('/api/v2/admin/users/rename', { user_id: id, new_username: newUsername });
if (data.success) {
showFlash(data.msg, 'success');
// Update the row in-place: links, text, and all button data attributes
const row = document.getElementById('user-row-' + id);
if (row) {
// Update the name link
const link = row.querySelector('.user-info-cell a');
if (link) {
link.href = '/user/' + data.new_login;
// Only overwrite text if there's no display_name (plain username link)
if (!link.querySelector('span[style*="accent"]')) {
link.textContent = data.new_user;
}
}
// Update all buttons in the row with the new name/username
row.querySelectorAll('[data-username]').forEach(el => { el.dataset.username = data.new_login; });
row.querySelectorAll('[data-name]').forEach(el => { el.dataset.name = data.new_user; });
// Update activity stat links
row.querySelectorAll('a[href^="/user/"]').forEach(a => {
a.href = a.href.replace(/\/user\/[^/]+/, '/user/' + data.new_login);
});
}
} else {
throw new Error(data.msg || 'Rename failed');
}
},
{ hideReason: false, singleLine: true, confirmText: 'Rename', placeholder: 'new username' }
);
};
window.adminDeleteUser = async (btn) => {
const id = btn.dataset.id;
const name = btn.dataset.name;
if (!confirm(`CRITICAL ACTION: Are you sure you want to PERMANENTLY DELETE user ${name}? All their uploads and comments will be reassigned to 'deleted_user'. This cannot be undone.`)) return;
try {
const data = await post('/api/v2/admin/users/delete', { user_id: id });
if (data.success) {
alert(data.msg);
document.getElementById(`user-row-${id}`)?.remove();
} else {
alert(data.msg || 'Failed to delete user');
}
} catch (err) {
alert('Network error');
}
if (typeof ModAction === 'undefined') return alert('Error: ModAction module not loaded');
ModAction.confirm(
'Delete User',
'<strong style="color:#d9534f">CRITICAL ACTION</strong>: Permanently delete user <strong>' + escHTML(name) + '</strong>?<br><br>All their uploads and comments will be reassigned to <code>deleted_user</code>. <strong>This cannot be undone.</strong>',
async () => {
const data = await post('/api/v2/admin/users/delete', { user_id: id });
if (data.success) {
showFlash(data.msg, 'success');
document.getElementById(`user-row-${id}`)?.remove();
} else {
throw new Error(data.msg || 'Failed to delete user');
}
},
{ hideReason: true, confirmText: 'Delete User' }
);
};
window.adminResetLoginAttempts = async (btn) => {
@@ -422,8 +478,13 @@
try {
const data = await post('/api/v2/admin/users/reset-login-attempts', { username });
if (data.success) {
alert(data.msg);
window.location.reload(); // Quickest way to refresh badges
showFlash(data.msg, 'success');
// Remove the failed attempt badges and reset button from the row in-place
const row = btn.closest('tr');
if (row) {
row.querySelectorAll('.status-badge[style*="ffcc00"], .status-badge[style*="ff4d4d"]').forEach(el => el.remove());
}
btn.remove();
} else {
alert(data.msg || 'Failed to reset attempts');
}
@@ -435,18 +496,22 @@
window.adminBulkDeleteHalls = async (btn) => {
const id = btn.dataset.id;
const name = btn.dataset.name;
if (!confirm(`Are you sure you want to PERMANENTLY DELETE ALL HALLS for ${name}? This cannot be undone.`)) return;
try {
const data = await post('/api/v2/admin/users/bulk-delete-halls', { user_id: id });
if (data.success) {
alert(data.msg);
} else {
alert(data.msg || 'Failed to delete halls');
}
} catch (err) {
alert('Network error');
}
if (typeof ModAction === 'undefined') return alert('Error: ModAction module not loaded');
ModAction.confirm(
'Delete All Halls',
'Permanently delete <strong>ALL halls</strong> for <strong>' + escHTML(name) + '</strong>? <strong>This cannot be undone.</strong>',
async () => {
const data = await post('/api/v2/admin/users/bulk-delete-halls', { user_id: id });
if (data.success) {
showFlash(data.msg, 'success');
} else {
throw new Error(data.msg || 'Failed to delete halls');
}
},
{ hideReason: true, confirmText: 'Delete Everything' }
);
};
window.adminReassignUploads = async (btn) => {
@@ -473,7 +538,7 @@
throw new Error(res.msg || 'Reassignment failed');
}
},
{ hideReason: false, confirmText: 'Reassign', placeholder: 'target username' }
{ hideReason: false, singleLine: true, confirmText: 'Reassign', placeholder: 'target username' }
);
};

File diff suppressed because it is too large Load Diff

View File

@@ -533,7 +533,7 @@ class Danmaku {
const raw = msg.dataset.rawText;
if (!raw) return;
// Only re-render if the content is still plain text (no img children)
if (!msg.querySelector('img.dpill-emoji')) {
if (!msg.querySelector('.dpill-emoji')) {
msg.textContent = '';
msg.appendChild(this._renderContent(raw));
}
@@ -600,11 +600,25 @@ class Danmaku {
const code = match[3];
const url = emojiCache[code];
if (url) {
const img = document.createElement('img');
img.src = url;
img.alt = `:${code}:`;
img.className = 'dpill-emoji';
parent.appendChild(img);
if (url.endsWith('.webm')) {
const vid = document.createElement('video');
vid.src = url;
vid.className = 'dpill-emoji';
vid.muted = true;
vid.loop = true;
vid.autoplay = true;
vid.playsInline = true;
vid.play().catch(() => {
vid.addEventListener('canplay', () => vid.play().catch(() => {}), { once: true });
});
parent.appendChild(vid);
} else {
const img = document.createElement('img');
img.src = url;
img.alt = `:${code}:`;
img.className = 'dpill-emoji';
parent.appendChild(img);
}
} else {
parent.appendChild(document.createTextNode(match[0]));
}

View File

@@ -46,11 +46,19 @@
return;
}
// Mark internal drags to prevent them from triggering the dropzone
window.addEventListener('dragstart', (e) => {
if (e.dataTransfer) {
e.dataTransfer.setData('application/x-f0ck-internal', 'true');
}
});
// Global Drag Events
window.addEventListener('dragenter', (e) => {
e.preventDefault();
if (window.location.pathname === '/upload') return;
if (e.dataTransfer.types.includes('Files')) {
if (e.dataTransfer && e.dataTransfer.types.includes('application/x-f0ck-internal')) return;
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
dragCounter++;
dropOverlay.classList.add('active');
}
@@ -59,10 +67,17 @@
window.addEventListener('dragover', (e) => {
e.preventDefault();
if (window.location.pathname === '/upload') return;
if (e.dataTransfer && e.dataTransfer.types.includes('application/x-f0ck-internal')) {
// Change dropEffect to none to indicate this dropzone doesn't accept internal elements
e.dataTransfer.dropEffect = 'none';
}
});
window.addEventListener('dragleave', (e) => {
if (window.location.pathname === '/upload') return;
// dragleave doesn't always have reliable dataTransfer.types, but if it does, check it
if (e.dataTransfer && e.dataTransfer.types.includes('application/x-f0ck-internal')) return;
dragCounter--;
if (dragCounter <= 0) {
dragCounter = 0;
@@ -72,6 +87,8 @@
window.addEventListener('drop', (e) => {
if (window.location.pathname === '/upload') return;
if (e.dataTransfer && e.dataTransfer.types.includes('application/x-f0ck-internal')) return;
e.preventDefault();
dragCounter = 0;
dropOverlay.classList.remove('active');

File diff suppressed because it is too large Load Diff

View File

@@ -634,8 +634,12 @@
// Visual state: strike-through when disabled
const swfButtons = Array.from(document.querySelectorAll('.v0ck_menu_item')).filter(b => b.textContent.trim() === 'SWF');
// Handle floating badge visibility
ui.floatingBadge.style.display = swfButtons.length > 0 ? 'none' : 'block';
// Handle floating badge visibility — only show as fallback when on an item page
// with the primary player present but no in-player SWF button (e.g. v0ck not loaded).
// Never show it just because sidebar .webm stickers exist.
const primaryVideo = document.getElementById('my-video') ||
document.querySelector('video.viewer, video.v0ck_video');
ui.floatingBadge.style.display = (swfButtons.length === 0 && !!primaryVideo) ? 'block' : 'none';
// Style both (if they exist)
[ui.floatingBadge, ...swfButtons].forEach(b => {

View File

@@ -23,6 +23,22 @@
let chatFocused = document.hasFocus();
const ytOembedCache = new Map(); // videoId → {title, author_name}
// Shared IntersectionObserver for lazy-loading embedded images.
// Images are rendered with data-lazy-src; this observer sets the real src
// when the image is within 200px of the visible scroll area.
const lazyImgObserver = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const img = entry.target;
const src = img.dataset.lazySrc;
if (src) { img.src = src; delete img.dataset.lazySrc; }
lazyImgObserver.unobserve(img);
}
}, {
rootMargin: '200px', // start loading 200px before entering viewport
threshold: 0
});
function updateBadge() {
const badge = document.getElementById('gchat-badge');
const bubble = document.getElementById('gchat-reopen-bubble');
@@ -187,7 +203,7 @@
'gi'
);
html = html.replace(imageRegex, url =>
`<span class="gchat-embed-img"><img src="${url}" loading="lazy" alt="" onerror="this.parentNode.style.display='none'"></span>`
`<span class="gchat-embed-img"><img data-lazy-src="${url}" src="" loading="lazy" alt="" onerror="this.parentNode.style.display='none'"></span>`
);
// 6b. Raw video URLs from allowed hosts → <video>
@@ -270,7 +286,7 @@
if (/\.(mp4|webm|ogv|mov)(\?.*)?$/i.test(path))
return `${pre}<span class="gchat-embed-video"><video src="${url}" controls loop muted playsinline preload="metadata"></video></span>`;
if (/\.(jpg|jpeg|png|gif|webp)(\?.*)?$/i.test(path))
return `${pre}<span class="gchat-embed-img"><img src="${url}" loading="lazy" alt="" onerror="this.parentNode.style.display='none'"></span>`;
return `${pre}<span class="gchat-embed-img"><img data-lazy-src="${url}" src="" loading="lazy" alt="" onerror="this.parentNode.style.display='none'"></span>`;
if (/\.(mp3|ogg|wav|flac|aac|opus|m4a)(\?.*)?$/i.test(path))
return `${pre}<span class="gchat-embed-audio"><audio src="${url}" controls preload="metadata"></audio></span>`;
}
@@ -310,11 +326,73 @@
</div>`;
}
function scrollToBottom(force = false) {
function scrollToBottom(force = false, smooth = false) {
const el = document.getElementById('gchat-messages');
if (!el) return;
const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
if (force || nearBottom) el.scrollTop = el.scrollHeight;
const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 120;
if (!force && !nearBottom) return;
if (smooth) {
el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });
} else {
// Double rAF ensures layout is committed before reading scrollHeight
requestAnimationFrame(() => requestAnimationFrame(() => { el.scrollTop = el.scrollHeight; }));
}
}
/**
* Watch the message container and keep snapping to bottom for durationMs.
* Only stops if the user actively scrolls up via wheel / touch / keyboard.
* Same logic as the DM snapToBottomSticky.
*/
function startStickyScroll(durationMs = 8000) {
const el = document.getElementById('gchat-messages');
if (!el) return;
let userScrolledUp = false;
const onWheel = (e) => { if (e.deltaY < 0) userScrolledUp = true; };
const onKey = (e) => { if (['ArrowUp', 'PageUp', 'Home'].includes(e.key)) userScrolledUp = true; };
let touchStartY = 0;
const onTouchStart = (e) => { touchStartY = e.touches[0]?.clientY ?? 0; };
const onTouchMove = (e) => { if ((e.touches[0]?.clientY ?? 0) > touchStartY + 10) userScrolledUp = true; };
el.addEventListener('wheel', onWheel, { passive: true });
el.addEventListener('keydown', onKey, { passive: true });
el.addEventListener('touchstart', onTouchStart, { passive: true });
el.addEventListener('touchmove', onTouchMove, { passive: true });
let ro;
const cleanup = () => {
el.removeEventListener('wheel', onWheel);
el.removeEventListener('keydown', onKey);
el.removeEventListener('touchstart', onTouchStart);
el.removeEventListener('touchmove', onTouchMove);
if (ro) ro.disconnect();
};
if (typeof ResizeObserver !== 'undefined') {
// Debounce: batch rapid layout changes (e.g. progressive image renders)
// into a single smooth scroll instead of many jarring instant jumps.
let debounceTimer = null;
ro = new ResizeObserver(() => {
if (userScrolledUp) { cleanup(); return; }
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
if (!userScrolledUp) el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });
}, 80);
});
ro.observe(el);
} else {
setTimeout(() => scrollToBottom(true), 300);
setTimeout(() => scrollToBottom(true), 800);
setTimeout(() => scrollToBottom(true), 2000);
}
setTimeout(cleanup, durationMs);
// First snap is instant (no animation — the panel just opened)
scrollToBottom(true);
setTimeout(() => { if (!userScrolledUp) scrollToBottom(true); }, 150);
}
async function fetchYtOembed(cardEl) {
@@ -417,9 +495,19 @@
s.addEventListener('click', () => s.classList.toggle('revealed'));
});
// Embedded images: scroll to bottom when loaded + open modal on click
node.querySelectorAll('.gchat-embed-img img').forEach(img => {
img.addEventListener('load', () => scrollToBottom(scrollForce));
// Embedded images: register with lazy observer; scroll on load only for new messages (not history)
node.querySelectorAll('.gchat-embed-img img[data-lazy-src]').forEach(img => {
// Only snap to bottom on image load for NEW incoming messages, not history.
// History already scrolls once at the end of loadHistory; an extra scroll
// here is what causes the double jump.
if (scrollForce) img.addEventListener('load', () => scrollToBottom(true));
img.addEventListener('click', () => openImgModal(img.src));
img.style.cursor = 'zoom-in';
lazyImgObserver.observe(img);
});
// Already-src'd images (avatars etc.) — same rule
node.querySelectorAll('.gchat-embed-img img:not([data-lazy-src])').forEach(img => {
if (scrollForce) img.addEventListener('load', () => scrollToBottom(true));
img.addEventListener('click', () => openImgModal(img.src));
img.style.cursor = 'zoom-in';
});
@@ -444,11 +532,14 @@
const data = await res.json();
if (!data.success) return;
const container = document.getElementById('gchat-messages');
if (container) container.innerHTML = '';
(data.messages || []).forEach(m => appendMsg(m));
scrollToBottom(true);
// Also scroll after images have had time to paint
setTimeout(() => scrollToBottom(true), 600);
if (!container) return;
container.innerHTML = '';
(data.messages || []).forEach(m => appendMsg(m, false));
// Double rAF: wait for the browser to commit the layout (panel just became
// visible from display:none) before reading scrollHeight.
requestAnimationFrame(() => requestAnimationFrame(() => {
container.scrollTop = container.scrollHeight;
}));
} catch (e) {
console.error('[Chat] Failed to load history:', e);
}
@@ -552,7 +643,9 @@
if (icon) icon.className = `fa-solid ${isMinimized ? 'fa-chevron-up' : 'fa-chevron-down'}`;
if (!isMinimized) {
clearUnread();
loadHistory();
// Wait one rAF so the panel transitions from display:none to its full
// height before loadHistory measures scrollHeight.
requestAnimationFrame(() => loadHistory());
if (!window.matchMedia('(pointer: coarse)').matches)
setTimeout(() => document.getElementById('gchat-input')?.focus(), 150);
}

View File

@@ -18,8 +18,69 @@
let draggingLayer = null;
let hoveredLayer = null;
let img = new Image();
let hasLoadedImage = window.memeTemplate.id !== 'custom' && window.memeTemplate.category !== 'Custom';
// Show the local file picker only when no pre-selected template exists
if (!hasLoadedImage) {
const customSelector = document.getElementById('customTemplateSelector');
if (customSelector) customSelector.style.display = '';
}
const memeFont = 'Impact, Charcoal, sans-serif';
const memeLetterSpacing = '0.03em';
function wrapText(ctx, text, maxWidth) {
const paragraphs = text.split('\n');
const lines = [];
paragraphs.forEach(paragraph => {
if (paragraph.trim() === '') {
lines.push('');
return;
}
const words = paragraph.split(' ').filter(w => w !== '');
let currentLine = '';
words.forEach(word => {
const testLine = currentLine ? currentLine + ' ' + word : word;
let metrics = ctx.measureText(testLine);
if (metrics.width <= maxWidth) {
currentLine = testLine;
} else {
if (currentLine !== '') {
lines.push(currentLine);
currentLine = '';
}
metrics = ctx.measureText(word);
if (metrics.width <= maxWidth) {
currentLine = word;
} else {
let charLine = '';
for (let i = 0; i < word.length; i++) {
const char = word[i];
const testCharLine = charLine + char;
if (ctx.measureText(testCharLine).width > maxWidth && charLine !== '') {
lines.push(charLine);
charLine = char;
} else {
charLine = testCharLine;
}
}
currentLine = charLine;
}
}
});
if (currentLine) {
lines.push(currentLine);
}
});
return lines;
}
// Image Setup
img.crossOrigin = "anonymous";
@@ -29,11 +90,23 @@
const defaultSize = 40;
// Initial layers
textLayers = [
{ id: Date.now(), text: '', x: canvas.width / 2, y: 40, fontSize: defaultSize },
{ id: Date.now() + 1, text: '', x: canvas.width / 2, y: canvas.height - 100, fontSize: defaultSize }
];
// Initial layers - only set if we don't have any layers yet and we have loaded an image
if (textLayers.length === 0 && hasLoadedImage) {
textLayers = [
{ id: Date.now(), text: '', x: canvas.width / 2, y: 40, fontSize: defaultSize },
{ id: Date.now() + 1, text: '', x: canvas.width / 2, y: canvas.height - 100, fontSize: defaultSize }
];
} else if (hasLoadedImage) {
// Keep the text layers but adjust their coordinates to be in-bounds if they exceed new boundaries
textLayers.forEach(layer => {
if (layer.x > canvas.width) {
layer.x = canvas.width / 2;
}
if (layer.y > canvas.height) {
layer.y = canvas.height - 100;
}
});
}
renderInputs();
draw();
@@ -42,11 +115,65 @@
// Ensure font is loaded before first draw
if (document.fonts) {
// Force browser to load the Impact font
document.fonts.load('bold 40px Impact');
document.fonts.load('bold 80px Impact');
document.fonts.load('bold 150px Impact');
document.fonts.ready.then(() => {
draw();
});
}
function createSlider(container, min, max, initValue, onChange) {
container.style.cssText = 'position:relative;height:28px;display:flex;align-items:center;flex:1;cursor:pointer;user-select:none;-webkit-user-select:none;touch-action:none;';
const track = document.createElement('div');
track.style.cssText = 'position:absolute;left:8px;right:8px;height:4px;background:#333;border-radius:2px;top:50%;transform:translateY(-50%);';
const fill = document.createElement('div');
fill.style.cssText = 'position:absolute;left:0;height:100%;background:var(--accent,#9f0);border-radius:2px;pointer-events:none;';
const thumb = document.createElement('div');
thumb.style.cssText = 'position:absolute;width:18px;height:18px;background:var(--accent,#9f0);border-radius:50%;top:50%;transform:translate(-50%,-50%);box-shadow:0 0 6px rgba(0,0,0,.6);pointer-events:none;transition:transform .1s;';
const setRatio = (r) => {
fill.style.width = (r * 100) + '%';
thumb.style.left = (r * 100) + '%';
};
setRatio((initValue - min) / (max - min));
track.appendChild(fill);
track.appendChild(thumb);
container.appendChild(track);
const valueFromClientX = (clientX) => {
const rect = track.getBoundingClientRect();
const r = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
setRatio(r);
return Math.round(min + r * (max - min));
};
container.addEventListener('pointerdown', (e) => {
e.preventDefault(); // block keyboard + scroll takeover
container.setPointerCapture(e.pointerId);
thumb.style.transform = 'translate(-50%,-50%) scale(1.25)';
onChange(valueFromClientX(e.clientX));
}, { passive: false });
container.addEventListener('pointermove', (e) => {
if (!container.hasPointerCapture(e.pointerId)) return;
onChange(valueFromClientX(e.clientX));
});
const onEnd = (e) => {
if (!container.hasPointerCapture(e.pointerId)) return;
container.releasePointerCapture(e.pointerId);
thumb.style.transform = 'translate(-50%,-50%) scale(1)';
};
container.addEventListener('pointerup', onEnd);
container.addEventListener('pointercancel', onEnd);
}
function renderInputs() {
layersContainer.innerHTML = '';
textLayers.forEach((layer, index) => {
@@ -64,7 +191,7 @@
<div class="layer-font-size-control" style="display: flex; align-items: center; gap: 10px;">
<span style="font-size: 0.8em; color: #888; white-space: nowrap;">${(window.f0ckI18n?.meme?.size_label) || 'Size'}: <span class="layer-fs-val">${layer.fontSize}</span>px</span>
<input type="range" class="layer-fs-input" min="10" max="200" value="${layer.fontSize}" style="flex: 1;">
<div class="layer-fs-slider" style="flex: 1;"></div>
</div>
`;
@@ -74,11 +201,11 @@
draw();
});
const fsInput = div.querySelector('.layer-fs-input');
const fsVal = div.querySelector('.layer-fs-val');
fsInput.addEventListener('input', (e) => {
layer.fontSize = parseInt(e.target.value);
fsVal.textContent = layer.fontSize;
const fsSlider = div.querySelector('.layer-fs-slider');
const fsVal = div.querySelector('.layer-fs-val');
createSlider(fsSlider, 10, 200, layer.fontSize, (val) => {
layer.fontSize = val;
fsVal.textContent = val;
draw();
});
@@ -94,6 +221,10 @@
}
addTextBtn.addEventListener('click', () => {
if (!hasLoadedImage) {
window.flashMessage((window.f0ckI18n?.meme?.choose_image_first) || 'Please select an image first!', 3000, 'error');
return;
}
textLayers.push({
id: Date.now(),
text: 'NEW TEXT',
@@ -125,10 +256,11 @@
const fontSize = layer.fontSize || 40;
ctx.font = `bold ${fontSize}px ${memeFont}`;
ctx.letterSpacing = memeLetterSpacing;
let displayStr = layer.text.toUpperCase();
const lines = displayStr.split('\n');
const h = lines.length * fontSize * 1.1;
const lines = wrapText(ctx, displayStr, canvas.width * 0.9);
const h = lines.length * fontSize * 1.25;
const w = canvas.width * 0.9;
// Box for the dragged/hovered layer (top-most layer gets preference)
@@ -142,12 +274,13 @@
}
lines.forEach((line, i) => {
const yOffset = i * (fontSize * 1.1);
const yOffset = i * (fontSize * 1.25);
const renderX = Math.round(layer.x);
const renderY = Math.round(layer.y + yOffset);
ctx.save();
ctx.font = `bold ${fontSize}px ${memeFont}`; // Ensure correct font size per line
ctx.letterSpacing = memeLetterSpacing;
ctx.strokeStyle = 'black';
ctx.lineWidth = Math.max(2, fontSize / 8); // Slightly thicker stroke for better legibility
ctx.strokeText(line, renderX, renderY);
@@ -173,9 +306,13 @@
const isInsideText = (pt, layer) => {
if (!layer.text) return false;
const fontSize = layer.fontSize || 40;
const lines = layer.text.split('\n');
ctx.save();
ctx.font = `bold ${fontSize}px ${memeFont}`;
ctx.letterSpacing = memeLetterSpacing;
const lines = wrapText(ctx, layer.text.toUpperCase(), canvas.width * 0.9);
ctx.restore();
const w = canvas.width * 0.95;
const h = lines.length * fontSize * 1.2;
const h = lines.length * fontSize * 1.25;
return pt.x >= layer.x - w / 2 && pt.x <= layer.x + w / 2 &&
pt.y >= layer.y - 20 && pt.y <= layer.y + h + 20;
@@ -232,16 +369,22 @@
canvas.addEventListener('mousedown', onStart);
// Upload
uploadBtn.addEventListener('click', async () => {
if (!hasLoadedImage) {
window.flashMessage((window.f0ckI18n?.meme?.choose_image_first) || 'Please select an image first!', 3000, 'error');
return;
}
const category = (window.memeTemplate && window.memeTemplate.category) ? window.memeTemplate.category.toLowerCase() : '';
const subCategory = (window.memeTemplate && window.memeTemplate.sub_category) ? window.memeTemplate.sub_category.toLowerCase() : '';
const templateId = (window.memeTemplate && window.memeTemplate.id) ? window.memeTemplate.id.toLowerCase() : '';
const isOrakelVon10 = subCategory === 'von10';
const isOrakelUser = subCategory === 'user';
const isOrakelNormal = category === 'orakel' && !isOrakelUser && !isOrakelVon10;
const isOrakelBingoApu = subCategory === 'bingoapu' || templateId === 'bingoapu';
const isOrakelNormal = category === 'orakel' && !isOrakelUser && !isOrakelVon10 && !isOrakelBingoApu;
let uploadCanvas = canvas;
if (isOrakelNormal || isOrakelUser || isOrakelVon10) {
if (isOrakelNormal || isOrakelUser || isOrakelVon10 || isOrakelBingoApu) {
// Create an off-screen canvas to apply the orakel answer silently
uploadCanvas = document.createElement('canvas');
uploadCanvas.width = canvas.width;
@@ -252,6 +395,7 @@
uCtx.drawImage(canvas, 0, 0);
let result = '';
let selectedCorner = null;
if (isOrakelNormal) {
const outcomes = ['JA', 'NEIN', 'VIELLEICHT', 'AUF JEDEN FALL', 'NIEMALS', 'SOWAS VON JA', 'VERGISS ES', 'FRAG SPÄTER', 'KOMMT DRAUF AN'];
result = outcomes[Math.floor(Math.random() * outcomes.length)];
@@ -265,92 +409,124 @@
}
} else if (isOrakelVon10) {
result = Math.floor(Math.random() * 11).toString();
} else if (isOrakelBingoApu) {
const corners = [
{ x: 60, y: 100, label: 'YES' },
{ x: 573, y: 100, label: 'NO' },
{ x: 60, y: 615, label: 'NO' },
{ x: 573, y: 615, label: 'YES' }
];
selectedCorner = corners[Math.floor(Math.random() * corners.length)];
result = selectedCorner.label;
}
// Draw Orakel result on the hidden canvas
uCtx.save();
uCtx.font = (isOrakelVon10) ? 'bold 150px Impact' : 'bold 80px Impact'; // Bigger font for the rating
uCtx.textAlign = 'center';
uCtx.textBaseline = 'middle';
if (isOrakelNormal) {
uCtx.shadowBlur = 20;
uCtx.shadowColor = 'rgba(101, 37, 212, 1)';
} else if (isOrakelVon10) {
uCtx.shadowBlur = 0; // No shadow as requested
} else {
// No shadow for the User Orakel
uCtx.shadowBlur = 0;
}
uCtx.fillStyle = '#fff';
uCtx.strokeStyle = '#000';
uCtx.lineWidth = 10;
uCtx.miterLimit = 2;
// Adjust position for user Orakel (reverting to +10 offset)
let yPos = Math.round(isOrakelUser ? (uploadCanvas.height / 2 + 10) : (uploadCanvas.height / 2 + 50));
if (isOrakelVon10) {
yPos = Math.round(uploadCanvas.height / 2 ); // 1px lower
}
const xPos = Math.round(uploadCanvas.width / 2);
// Auto-fit font size for user orakel — shrink until text fits within image width
let orakelFontSize = isOrakelVon10 ? 150 : 80;
const maxTextWidth = uploadCanvas.width - 80; // 40px padding each side
if (isOrakelUser) {
const parts = result.split('|||');
const namePart = parts[0];
const idPart = parts.length > 1 ? `(${parts[1]})` : '';
const combinedText = idPart ? `${namePart} ${idPart}` : namePart;
// Even tighter threshold for User Orakel (approx 25% total padding)
const userMaxWidth = Math.round(uploadCanvas.width * 0.75);
let currentFontSize = 74;
uCtx.font = `bold ${currentFontSize}px Impact`;
if (isOrakelBingoApu) {
// Draw "KOPS" in normal meme text style on the selected corner
uCtx.font = `bold 28px ${memeFont}`;
uCtx.letterSpacing = memeLetterSpacing;
uCtx.textAlign = 'center';
uCtx.textBaseline = 'middle';
uCtx.fillStyle = '#fff';
uCtx.strokeStyle = '#000';
uCtx.lineWidth = 4;
uCtx.miterLimit = 2;
// First attempt: Shrink entire text on one line down to 58px if needed
while (uCtx.measureText(combinedText).width > userMaxWidth && currentFontSize > 58) {
currentFontSize -= 2;
uCtx.font = `bold ${currentFontSize}px Impact`;
}
const combinedFits = uCtx.measureText(combinedText).width <= userMaxWidth;
if (combinedFits) {
// Single line — potentially shrunk for long names
uCtx.fillText(combinedText, xPos, yPos);
} else {
// Two lines — auto-fit just the name, ID below
let nameFontSize = 74;
uCtx.font = `bold ${nameFontSize}px Impact`;
while (uCtx.measureText(namePart).width > userMaxWidth && nameFontSize > 16) {
nameFontSize -= 2;
uCtx.font = `bold ${nameFontSize}px Impact`;
}
const idFontSize = Math.max(18, Math.round(nameFontSize * 0.45));
const lineGap = Math.round(nameFontSize * 0.65);
const nameY = Math.round(yPos - lineGap / 2);
const idY = Math.round(yPos + lineGap / 2) + 2;
uCtx.font = `bold ${nameFontSize}px Impact`;
uCtx.fillText(namePart, xPos, nameY);
if (idPart) {
uCtx.font = `bold ${idFontSize}px Impact`;
uCtx.fillText(idPart, xPos, idY);
}
}
uCtx.strokeText('KOPS', selectedCorner.x, selectedCorner.y);
uCtx.fillText('KOPS', selectedCorner.x, selectedCorner.y);
} else {
// Normal / von10 — single line as before
uCtx.font = `bold ${orakelFontSize}px Impact`;
uCtx.strokeText(result, xPos, yPos);
uCtx.fillText(result, xPos, yPos);
uCtx.font = (isOrakelVon10) ? 'bold 150px Impact' : 'bold 80px Impact'; // Bigger font for the rating
uCtx.letterSpacing = memeLetterSpacing;
uCtx.textAlign = 'center';
uCtx.textBaseline = 'middle';
if (isOrakelNormal) {
uCtx.shadowBlur = 20;
uCtx.shadowColor = 'rgba(101, 37, 212, 1)';
} else if (isOrakelVon10) {
uCtx.shadowBlur = 0; // No shadow as requested
} else {
// No shadow for the User Orakel
uCtx.shadowBlur = 0;
}
uCtx.fillStyle = '#fff';
uCtx.strokeStyle = '#000';
uCtx.lineWidth = 10;
uCtx.miterLimit = 2;
// Adjust position for user Orakel (reverting to +10 offset)
let yPos = Math.round(isOrakelUser ? (uploadCanvas.height / 2 + 10) : (uploadCanvas.height / 2 + 50));
if (isOrakelVon10) {
yPos = Math.round(uploadCanvas.height / 2 ); // 1px lower
}
const xPos = Math.round(uploadCanvas.width / 2);
// Auto-fit font size for user orakel — shrink until text fits within image width
let orakelFontSize = isOrakelVon10 ? 150 : 80;
const maxTextWidth = uploadCanvas.width - 80; // 40px padding each side
if (isOrakelUser) {
const parts = result.split('|||');
const namePart = parts[0];
const idPart = parts.length > 1 ? `(${parts[1]})` : '';
const combinedText = idPart ? `${namePart} ${idPart}` : namePart;
// Even tighter threshold for User Orakel (approx 25% total padding)
const userMaxWidth = Math.round(uploadCanvas.width * 0.75);
let currentFontSize = 74;
uCtx.font = `bold ${currentFontSize}px Impact`;
uCtx.letterSpacing = memeLetterSpacing;
// First attempt: Shrink entire text on one line down to 58px if needed
while (uCtx.measureText(combinedText).width > userMaxWidth && currentFontSize > 58) {
currentFontSize -= 2;
uCtx.font = `bold ${currentFontSize}px Impact`;
uCtx.letterSpacing = memeLetterSpacing;
}
const combinedFits = uCtx.measureText(combinedText).width <= userMaxWidth;
if (combinedFits) {
// Single line — potentially shrunk for long names
uCtx.fillText(combinedText, xPos, yPos);
} else {
// Two lines — auto-fit just the name, ID below
let nameFontSize = 74;
uCtx.font = `bold ${nameFontSize}px Impact`;
uCtx.letterSpacing = memeLetterSpacing;
while (uCtx.measureText(namePart).width > userMaxWidth && nameFontSize > 16) {
nameFontSize -= 2;
uCtx.font = `bold ${nameFontSize}px Impact`;
uCtx.letterSpacing = memeLetterSpacing;
}
const idFontSize = Math.max(18, Math.round(nameFontSize * 0.45));
const lineGap = Math.round(nameFontSize * 1.25);
const nameY = Math.round(yPos - lineGap / 2);
const idY = Math.round(yPos + lineGap / 2) + 2;
uCtx.font = `bold ${nameFontSize}px Impact`;
uCtx.letterSpacing = memeLetterSpacing;
uCtx.fillText(namePart, xPos, nameY);
if (idPart) {
uCtx.font = `bold ${idFontSize}px Impact`;
uCtx.letterSpacing = memeLetterSpacing;
uCtx.fillText(idPart, xPos, idY);
}
}
} else {
// Normal / von10 — single line as before
uCtx.font = `bold ${orakelFontSize}px Impact`;
uCtx.letterSpacing = memeLetterSpacing;
uCtx.strokeText(result, xPos, yPos);
uCtx.fillText(result, xPos, yPos);
}
}
uCtx.restore();
}
@@ -384,13 +560,22 @@
const result = await res.json();
if (result.success) {
const dest = result.redirect || '/meme';
if (window.loadItemAjax) {
window.loadItemAjax(dest);
} else if (window.loadPageAjax) {
window.loadPageAjax(dest);
if (result.manual_approval) {
window.flashMessage(window.f0ckI18n?.upload_pending_approval_patient || 'Upload awaits approval', 3000, 'warning');
if (window.loadPageAjax) {
window.loadPageAjax('/');
} else {
window.location.href = '/';
}
} else {
window.location.href = dest;
const dest = result.redirect || '/meme';
if (window.loadItemAjax) {
window.loadItemAjax(dest);
} else if (window.loadPageAjax) {
window.loadPageAjax(dest);
} else {
window.location.href = dest;
}
}
}
else {
@@ -404,6 +589,79 @@
}
});
// Custom Local Image Selector logic
const fileInput = document.getElementById('customTemplateFile');
const selectFileBtn = document.getElementById('selectCustomFileBtn');
const canvasWrapper = document.querySelector('.canvas-wrapper');
const loadLocalImage = (file) => {
if (file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (event) => {
hasLoadedImage = true;
img.src = event.target.result;
// Update template metadata
window.memeTemplate.name = file.name.replace(/\.[^/.]+$/, "");
// Update header title dynamically
const headerTitle = document.querySelector('.meme-title');
if (headerTitle) {
const baseTitle = window.f0ckI18n?.meme?.create_meme || 'Create Meme:';
headerTitle.innerHTML = `${baseTitle} ${window.memeTemplate.name}`;
}
// Update tags input value if tags are present
const tagsInput = document.getElementById('tags');
if (tagsInput) {
tagsInput.value = `meme, Custom, ${window.memeTemplate.name}`;
}
};
reader.readAsDataURL(file);
}
};
if (selectFileBtn && fileInput) {
selectFileBtn.addEventListener('click', () => {
fileInput.click();
});
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
loadLocalImage(file);
});
}
// HTML5 Drag & Drop Support
if (canvas && canvasWrapper) {
const preventDefaults = (e) => {
e.preventDefault();
e.stopPropagation();
};
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
canvasWrapper.addEventListener(eventName, preventDefaults, false);
});
['dragenter', 'dragover'].forEach(eventName => {
canvasWrapper.addEventListener(eventName, () => {
canvasWrapper.classList.add('drag-hover');
}, false);
});
['dragleave', 'drop'].forEach(eventName => {
canvasWrapper.addEventListener(eventName, () => {
canvasWrapper.classList.remove('drag-hover');
}, false);
});
canvasWrapper.addEventListener('drop', (e) => {
const dt = e.dataTransfer;
const file = dt.files[0];
loadLocalImage(file);
}, false);
}
// Initial draw
setTimeout(draw, 300);
}

File diff suppressed because it is too large Load Diff

View File

@@ -209,6 +209,12 @@
if (!str) return '';
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function decodeHtmlEntities(str) {
if (!str) return '';
const txt = document.createElement('textarea');
txt.innerHTML = String(str);
return txt.value;
}
function timeAgo(iso) {
const s = Math.floor((Date.now() - new Date(iso)) / 1000);
const i = window.f0ckI18n || {};
@@ -229,28 +235,33 @@
return ago(fmt(y === 1 ? i.ta_year : i.ta_years, y, 'year'));
}
function hashId() {
// Strip the leading '#' and allow numeric IDs or board/postid format
// Check path first /abyss/1234 or /abyss/gif/1234
const pathClean = location.pathname.replace(/\/$/, '');
const pathMatch = pathClean.match(/\/abyss\/([a-zA-Z0-9_\/-]+)$/);
if (pathMatch) return pathMatch[1];
// Fallback to hash
const raw = location.hash.replace(/^#/, '').trim();
if (/^\d+$/.test(raw)) return raw;
if (/^[a-z0-9]+\/\d+$/.test(raw)) return raw;
return '';
}
let lastPushedHash = location.hash;
let lastPushedUrl = location.pathname + location.hash;
function pushHash(id) {
if (!id) return;
const newHash = '#' + id;
if (newHash === lastPushedHash) return;
lastPushedHash = newHash;
history.pushState({ scrollerId: id }, '', '/abyss' + newHash);
const newUrl = '/abyss/' + id;
if (newUrl === lastPushedUrl) return;
lastPushedUrl = newUrl;
history.pushState({ scrollerId: id }, '', newUrl);
updateCacheActiveId(id);
}
// Handle back/forward within abyss — scroll to the target slide
window.addEventListener('popstate', (e) => {
if (!document.body.classList.contains('scroller-active')) return;
const id = e.state?.scrollerId || location.hash.replace('#', '');
const id = e.state?.scrollerId || hashId();
if (!id) return;
lastPushedHash = '#' + id;
lastPushedUrl = '/abyss/' + id;
const slide = feed.querySelector(`.scroll-slide[data-id="${id}"], .scroll-slide[data-local-id="${id}"]`);
if (slide) {
slide.scrollIntoView({ behavior: 'smooth', block: 'start' });
@@ -707,9 +718,12 @@
const id = contextLink.dataset.id;
const target = commentsList.querySelector(`.comment-item[data-comment-id="${id}"]`);
if (target) {
// Clear any previous persistent highlight
commentsList.querySelectorAll('.comment-linked').forEach(el => el.classList.remove('comment-linked'));
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
target.classList.add('highlight-comment');
setTimeout(() => target.classList.remove('highlight-comment'), 2000);
// Flash the animation for attention, then keep the persistent highlight
target.classList.add('highlight-comment', 'comment-linked');
setTimeout(() => target.classList.remove('highlight-comment'), 2500);
}
}
});
@@ -986,9 +1000,10 @@
e.stopPropagation();
const itemId = slide.dataset.id;
try {
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
const resp = await fetch(`/api/v2/tags/${itemId}/${encodeURIComponent(tag)}`, {
method: 'DELETE',
headers: { 'x-csrf-token': window.scrollerCsrf || '' }
headers: { ...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {}) }
});
const data = await resp.json();
if (data.success) pill.remove();
@@ -1143,10 +1158,14 @@
if (nowFaved) flashFav(slide);
}
try {
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
const resp = await fetch('/api/v2/togglefav', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `postid=${id}`
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {})
},
body: `postid=${id}${csrfToken ? `&csrf_token=${encodeURIComponent(csrfToken)}` : ''}`
});
const data = await resp.json();
// Sync count to server truth (handles race conditions)
@@ -1366,18 +1385,15 @@
${window.scrollerLoggedIn ? `
<button class="scroll-btn js-fav-btn${item.is_faved ? ' faved' : ''}" title="${_i.favourite || 'Favourite'} (double-tap)">
<div class="scroll-btn-icon"><i class="${item.is_faved ? 'fa-solid' : 'fa-regular'} fa-heart"></i></div>
<span class="scroll-btn-label"></span>
<span class="scroll-btn-count">${item.fav_count ?? 0}</span>
</button>` : ''}
<button class="scroll-btn js-comments-btn" data-id="${item.id}" title="${_i.comments_label || 'Comments'} (C)">
<div class="scroll-btn-icon"><i class="fa-regular fa-comment"></i></div>
<span class="scroll-btn-label"></span>
<span class="scroll-btn-count">${item.comment_count ?? 0}</span>
</button>
${window.scrollerLoggedIn ? `
<button class="scroll-btn js-tag-btn" data-id="${item.id}" title="${_i.add_tag || 'Add tag'}">
<div class="scroll-btn-icon"><i class="fa-solid fa-tag"></i></div>
<span class="scroll-btn-label"></span>
</button>` : ''}
<button class="scroll-btn js-share-btn" data-id="${item.id}" title="${_i.share_label || 'Share'}">
<div class="scroll-btn-icon"><i class="fa-solid fa-share-nodes"></i></div>
@@ -1385,7 +1401,7 @@
</button>
${item.is_external ? (
item.local_id
? `<a class="scroll-btn success" href="/${item.local_id}" target="_blank" title="${_i.already_added || 'Already added'}">
? `<a class="scroll-btn rehost-btn success" href="/${item.local_id}" target="_blank" title="${_i.already_added || 'Already added'}">
<div class="scroll-btn-icon"><i class="fa-solid fa-check"></i></div>
<span class="scroll-btn-label">${_i.view_label || 'View'}</span>
</a>`
@@ -1546,24 +1562,13 @@
const rBadge = slide.querySelector('.scroll-rating[data-item-id]');
if (rBadge) {
if (window.scrollerIsMod || item.local_id) rBadge.classList.add('can-cycle');
rBadge.addEventListener('click', async e => {
rBadge.addEventListener('click', e => {
if (Date.now() - speedEndedAt < 200) return; // ignore click if we just ended a speed-hold
e.stopPropagation();
const slideEl = rBadge.closest('.scroll-slide');
const id = slideEl?.dataset.localId || rBadge.dataset.itemId;
if (!id || isNaN(id)) { showShareToast('Rehost first to change rating'); return; }
try {
const resp = await fetch(`/api/v2/tags/${id}/cycle-rating`, {
method: 'PUT',
headers: { 'x-csrf-token': window.scrollerCsrf || '' }
});
const data = await resp.json();
if (data.success) {
rBadge.className = `scroll-rating ${data.rating_class}${window.scrollerIsMod ? ' can-cycle' : ''}`;
rBadge.textContent = data.rating_label;
rBadge.dataset.rating = data.rating_class;
}
} catch {}
cycleRatingOptimistic(rBadge, id, false);
});
}
@@ -1582,9 +1587,10 @@
e.stopPropagation();
const itemId = slide.dataset.id;
try {
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
const resp = await fetch(`/api/v2/tags/${itemId}/${encodeURIComponent(t)}`, {
method: 'DELETE',
headers: { 'x-csrf-token': window.scrollerCsrf || '' }
headers: { ...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {}) }
});
const data = await resp.json();
if (data.success) pill.remove();
@@ -1688,13 +1694,14 @@
avatar: '/a/default.png',
stamp: p.time,
timeago: timeAgo(p.time * 1000),
tags: `4chan, /${data.board}/`,
tags: ``,
is_video: isVideo,
is_image: isImage,
is_audio: false,
comment_count: p.replies || 0,
rating_label: isWsg ? 'SFW' : (isGif ? 'NSFW' : 'External'),
rating_class: isWsg ? 'sfw' : (isGif ? 'nsfw' : 'untagged')
rating_class: isWsg ? 'sfw' : (isGif ? 'nsfw' : 'untagged'),
original_filename: p.filename ? `${decodeHtmlEntities(p.filename)}${ext}` : null
};
})
.filter(Boolean);
@@ -1825,7 +1832,7 @@
const target = hid ? feed.querySelector(`.scroll-slide[data-id="${hid}"]`) : null;
const first = feed.querySelector('.scroll-slide:not([data-lock])');
const toActivate = target || first;
if (toActivate) setTimeout(() => { activateSlide(toActivate); hideLoader(); }, 200);
if (toActivate) setTimeout(() => { toActivate.scrollIntoView({ behavior: 'instant', block: 'start' }); activateSlide(toActivate); hideLoader(); }, 200);
}
} catch (err) {
console.error('[SCROLLER] Fetch error:', err);
@@ -1849,17 +1856,19 @@
else if (item.external_board === 'gif') rating = 'nsfw';
try {
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
const resp = await fetch('/api/v2/scroller/rehost', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'x-csrf-token': window.scrollerCsrf || ''
...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {})
},
body: new URLSearchParams({
url: item.external_media_url || item.dest,
rating: rating,
tags: '4chan',
comment: `Rehosted from 4chan thread: ${applied.externalUrl || 'unknown'}`
tags: '',
comment: `Rehosted from 4chan thread: ${applied.externalUrl || 'unknown'}`,
...(item.original_filename ? { original_filename: item.original_filename } : {})
})
});
const data = await resp.json();
@@ -1885,7 +1894,7 @@
// Update button to link to the new site-internal post
setTimeout(() => {
btn.outerHTML = `
<a href="/${data.item_id}" target="_blank" class="scroll-btn success" style="text-decoration:none;">
<a href="/${data.item_id}" target="_blank" class="scroll-btn rehost-btn success" style="text-decoration:none;">
<div class="scroll-btn-icon"><i class="fa-solid fa-arrow-up-right-from-square"></i></div>
<span class="scroll-btn-label">View</span>
</a>
@@ -1925,6 +1934,74 @@
}
}
function cycleRatingOptimistic(badge, id, showToast = false) {
if (!badge || !id || isNaN(id)) return;
let currentRating = badge.dataset.rating || '';
if (!currentRating) {
if (badge.classList.contains('sfw')) currentRating = 'sfw';
else if (badge.classList.contains('nsfw')) currentRating = 'nsfw';
else if (badge.classList.contains('nsfl')) currentRating = 'nsfl';
}
let nextRating = 'sfw';
if (currentRating === 'sfw') nextRating = 'nsfw';
else if (currentRating === 'nsfw') nextRating = 'nsfl';
const mapping = {
sfw: { label: 'SFW', cls: 'sfw', toast: '🛡 SFW' },
nsfw: { label: 'NSFW', cls: 'nsfw', toast: '🔥 NSFW' },
nsfl: { label: 'NSFL', cls: 'nsfl', toast: '💀 NSFL' }
};
const info = mapping[nextRating];
const oldClassName = badge.className;
const oldTextContent = badge.textContent;
const oldDatasetRating = badge.dataset.rating;
// Track active request ID to ignore out-of-order race conditions on rapid keypresses
const reqId = (badge._lastCycleReqId || 0) + 1;
badge._lastCycleReqId = reqId;
// Optimistically apply new state
badge.className = `scroll-rating ${info.cls}${window.scrollerIsMod ? ' can-cycle' : ''}`;
badge.textContent = info.label;
badge.dataset.rating = info.cls;
if (showToast) {
showShareToast(info.toast);
}
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
fetch(`/api/v2/tags/${id}/cycle-rating`, {
method: 'PUT',
headers: { ...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {}) }
})
.then(r => r.json())
.then(data => {
if (badge._lastCycleReqId !== reqId) return; // ignore stale responses
if (!data.success) {
revert();
return;
}
// Verify we match actual server result
badge.className = `scroll-rating ${data.rating_class}${window.scrollerIsMod ? ' can-cycle' : ''}`;
badge.textContent = data.rating_label;
badge.dataset.rating = data.rating_class;
})
.catch(() => {
if (badge._lastCycleReqId !== reqId) return; // ignore stale responses
revert();
});
function revert() {
badge.className = oldClassName;
badge.textContent = oldTextContent;
badge.dataset.rating = oldDatasetRating;
showShareToast('⚠️ Failed to update rating');
}
}
function reloadFeed() {
clearCache();
@@ -2050,7 +2127,12 @@
const contentEl = commentEl.querySelector('.comment-content');
if (!contentEl) return;
const raw = (contentEl.dataset.raw || '').replace(/<br\s*\/?>/gi, '\n').trim();
let raw = (contentEl.dataset.raw || '').replace(/<br\s*\/?>/gi, '\n').trim();
if (raw.includes('&gt;') || raw.includes('&lt;') || raw.includes('&amp;')) {
const txt = document.createElement('textarea');
txt.innerHTML = raw;
raw = txt.value;
}
const lines = raw.split('\n');
const quote = `>>${id}\n${lines.map(line => `>${line}`).join('\n')}\n`;
@@ -2718,11 +2800,16 @@
if (!content || !commentsItemId || commentsPosting) return;
commentsPosting = true; commentSendBtn.disabled = true;
try {
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
let postBody = `item_id=${commentsItemId}&content=${encodeURIComponent(content)}`;
if (replyToCommentId) postBody += `&parent_id=${replyToCommentId}`;
if (csrfToken) postBody += `&csrf_token=${encodeURIComponent(csrfToken)}`;
const resp = await fetch('/api/comments', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {})
},
body: postBody
});
const data = await resp.json();
@@ -2736,7 +2823,7 @@
avatar: null,
username: window.scrollerUsername,
display_name: displayName,
content: content,
content: data.comment?.content ?? content,
created_at: null
}, !!window.scrollerLoggedIn);
// Set avatar from global
@@ -2830,10 +2917,14 @@
if (addTagSendBtn) addTagSendBtn.disabled = true;
closeSugg();
try {
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
const resp = await fetch(`/api/v2/tags/${targetId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `tagname=${encodeURIComponent(tag)}`
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {})
},
body: `tagname=${encodeURIComponent(tag)}${csrfToken ? `&csrf_token=${encodeURIComponent(csrfToken)}` : ''}`
});
const data = await resp.json();
if (data.success) {
@@ -3136,26 +3227,12 @@
else if (e.key === 'p' || e.key === 'P') {
e.preventDefault();
if (!currentSlide || !window.scrollerLoggedIn) return;
const itemId = currentSlide.dataset.id;
const itemId = currentSlide.dataset.localId || currentSlide.dataset.id;
if (!itemId) return;
fetch(`/api/v2/tags/${itemId}/cycle-rating`, {
method: 'PUT',
headers: { 'x-csrf-token': window.scrollerCsrf || '' }
})
.then(r => r.json())
.then(data => {
if (!data.success) return;
// Update the badge on the slide immediately
const badge = currentSlide.querySelector('.scroll-rating[data-item-id]');
if (badge) {
badge.className = `scroll-rating ${data.rating_class}${window.scrollerIsMod ? ' can-cycle' : ''}`;
badge.textContent = data.rating_label;
badge.dataset.rating = data.rating_class;
}
const labels = { sfw: '🛡 SFW', nsfw: '🔥 NSFW', nsfl: '💀 NSFL' };
showShareToast(labels[data.rating_class] ?? data.rating_label);
})
.catch(() => {});
const badge = currentSlide.querySelector('.scroll-rating[data-item-id]');
if (badge) {
cycleRatingOptimistic(badge, itemId, true);
}
}
else if (e.key === 'l' || e.key === 'L') { e.preventDefault(); if (currentSlide) toggleFav(currentSlide); }
else if (e.key === 'i' || e.key === 'I') { e.preventDefault(); if (currentSlide) openTagBar(currentSlide.dataset.id); }
@@ -3441,7 +3518,7 @@
// Tab type arrays
const SCROLLER_USER_TYPES = ['comment_reply', 'subscription', 'mention', 'upload_comment'];
const SCROLLER_SYSTEM_TYPES = ['approve', 'deny', 'item_deleted', 'upload_success', 'upload_error', 'admin_pending', 'report'];
const SCROLLER_SYSTEM_TYPES = ['approve', 'deny', 'item_deleted', 'upload_success', 'upload_error', 'admin_pending', 'report', 'warning'];
let sActiveTab = 'user';
let sCachedNotifs = [];
@@ -3545,6 +3622,9 @@
} else if (n.type === 'report') {
link = '/mod/reports'; user = i18n.notif_moderation || 'Moderator';
msg = i18n.notif_new_report || 'New user report';
} else if (n.type === 'warning') {
link = `/notifications?tab=system#notif-${n.id}`; user = i18n.notif_system || 'System';
msg = (i18n.account_warning && i18n.account_warning.title) || 'Account Warning';
} else {
link = `/${n.item_id}#c${n.reference_id}`;
if (n.type === 'comment_reply') msg = i18n.notif_replied || 'replied to you';
@@ -3552,8 +3632,13 @@
else if (n.type === 'mention') msg = i18n.notif_mentioned || 'highlighted you';
else msg = i18n.notif_commented || 'commented';
}
const thumbSrc = n.type === 'admin_pending' ? `/mod/pending/t/${n.item_id}.webp` : `/t/${n.item_id}.webp`;
const thumb = n.item_id ? `<div class="notif-thumb"><img src="${thumbSrc}" alt="" onerror="this.style.display='none'"></div>` : '';
let thumb;
if (n.type === 'warning') {
thumb = `<div class="notif-thumb" style="display:flex;align-items:center;justify-content:center;background:var(--bg-lighter);color:var(--danger);font-size:1.5em;"><i class="fa-solid fa-triangle-exclamation"></i></div>`;
} else {
const thumbSrc = n.type === 'admin_pending' ? `/mod/pending/t/${n.item_id}.webp` : `/t/${n.item_id}.webp`;
thumb = n.item_id ? `<div class="notif-thumb"><img src="${thumbSrc}" alt="" onerror="this.style.display='none'"></div>` : '';
}
return `<a href="${link}" target="_blank" class="notif-item ${n.is_read ? '' : 'unread'} notif-with-thumb" data-id="${n.id}">
${thumb}
<div class="notif-content">
@@ -3595,7 +3680,11 @@
if (sMarkAll) {
sMarkAll.addEventListener('click', async () => {
try {
await fetch('/api/notifications/read', { method: 'POST' });
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
await fetch('/api/notifications/read', {
method: 'POST',
headers: { ...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {}) }
});
updateScrollerNotifBadge(0);
sCachedNotifs = sCachedNotifs.map(n => ({ ...n, is_read: true }));
updateScrollerTabBadges(sCachedNotifs);
@@ -3610,7 +3699,12 @@
if (!item) return;
const nid = item.dataset.id;
if (nid && item.classList.contains('unread')) {
fetch(`/api/notifications/${nid}/read`, { method: 'POST', keepalive: true }).catch(() => {});
const csrfToken = window.f0ckSession?.csrf_token || window.scrollerCsrf || '';
fetch(`/api/notifications/${nid}/read`, {
method: 'POST',
keepalive: true,
headers: { ...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {}) }
}).catch(() => {});
item.classList.remove('unread');
// Update cache
const cached = sCachedNotifs.find(n => String(n.id) === String(nid));

File diff suppressed because it is too large Load Diff

View File

@@ -5,10 +5,19 @@
let currentPage = 1;
let hasMore = true;
let ioSentinel = null; // persistent sentinel element for IntersectionObserver
let lastRenderedIds = ''; // track rendered comment IDs to skip needless re-renders
// Shared cache for activity across AJAX loads
if (!window._sidebarActivityCache) window._sidebarActivityCache = [];
const loadEmojis = async () => {
// Prefer CommentSystem's already-fetched cache to avoid a redundant request
const csCache = (typeof CommentSystem !== 'undefined' && CommentSystem.emojiCache)
|| null;
if (csCache && Object.keys(csCache).length > 0) {
Object.assign(customEmojis, csCache);
return;
}
// No shared cache yet — fetch directly
if (Object.keys(customEmojis).length > 0) return;
try {
const res = await fetch('/api/v2/emojis');
@@ -25,7 +34,11 @@
const renderEmoji = (match, name) => {
if (customEmojis[name]) {
return `<img class="sidebar-comment-img emoji" src="${customEmojis[name]}" alt="${name}" title=":${name}:" loading="lazy">`;
const url = customEmojis[name];
if (url.endsWith('.webm')) {
return `<video class="sidebar-comment-img emoji" src="${url}" title=":${name}:" autoplay loop muted playsinline></video>`;
}
return `<img class="sidebar-comment-img emoji" src="${url}" alt="${name}" title=":${name}:" loading="lazy">`;
}
return match;
};
@@ -34,12 +47,22 @@
if (!unsafe) return '';
const div = document.createElement('div');
div.textContent = unsafe;
return div.innerHTML;
return div.innerHTML.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
};
const playSidebarEmojiVideos = (container) => {
if (!container) return;
container.querySelectorAll('video.emoji').forEach(v => {
v.play().catch(() => {
v.addEventListener('canplay', () => v.play().catch(() => {}), { once: true });
});
});
};
const ytOembedCache = new Map(); // videoId -> meta object
const ytOembedPending = new Map(); // videoId -> Promise
const fetchSidebarYoutubeTitles = async (container) => {
const links = container.querySelectorAll('.sidebar-video-link[data-yt-id]');
if (links.length === 0) return;
@@ -57,8 +80,40 @@
meta = await ytOembedPending.get(videoId);
} else {
const promise = (async () => {
const ytUrl = `https://www.youtube.com/watch?v=${encodeURIComponent(videoId)}`;
// 1. Try client-side oEmbed first (avoids Tor/proxy consent walls)
try {
const oembedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(ytUrl)}&format=json`;
const clientResp = await fetch(oembedUrl);
if (clientResp.ok) {
const clientData = await clientResp.json();
if (clientData.title) {
const metaObj = {
title: clientData.title,
site_name: 'youtube.com',
author: clientData.author_name || 'Unknown'
};
// Cache client-side
ytOembedCache.set(videoId, metaObj);
// Push to server cache so other clients/server benefit
try {
const csrf = window.f0ckSession?.csrf_token;
fetch('/api/v2/meta/cache', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(csrf ? { 'X-CSRF-Token': csrf } : {})
},
body: JSON.stringify({ url: ytUrl, meta: metaObj })
}).catch(() => {});
} catch (_) {}
return metaObj;
}
}
} catch (e) { }
// 2. Fall back to backend meta fetch
try {
const ytUrl = `https://www.youtube.com/watch?v=${encodeURIComponent(videoId)}`;
const r = await fetch(`/api/v2/meta/fetch?url=${encodeURIComponent(ytUrl)}`);
if (r.ok) {
const data = await r.json();
@@ -83,6 +138,12 @@
titleSpan.textContent = 'YouTube Video';
}
titleSpan.dataset.loaded = 'true';
// Re-check overflow since the new text might cause wrapping
const inner = link.closest('.comment-content-inner');
if (inner && typeof checkOverflow === 'function') {
checkOverflow(inner);
}
}
};
@@ -92,12 +153,6 @@
const renderCommentContent = (content, commentId = null, itemId = null) => {
if (!content) return '';
// Truncate extremely long comments before any processing to keep the sidebar
// fast and the DOM lean, regardless of markdown / regex complexity.
if (content.length > SIDEBAR_CONTENT_TRUNCATE) {
content = content.substring(0, SIDEBAR_CONTENT_TRUNCATE) + '\u2026';
}
if (typeof marked === 'undefined') {
return escapeHtml(content)
.replace(/:([a-z0-9_]+):/g, (m, n) => renderEmoji(m, n));
@@ -128,10 +183,10 @@
const hostsRegexPart = allowedHosts.join('|');
// "Safe non-whitespace" stops at protocol boundaries so concatenated URLs aren't merged.
const safeS = `(?:(?!https?:\\/\\/)\\S)`;
const domainOrRelative = `(?:(?:https?:\\/\\/|\\/\\/)?(?:${hostsRegexPart})|(?<!\\S)(?=\\/[a-zA-Z0-9_\\-]))`;
const domainOrRelative = `(?:(?:https?:\\/\\/|\\/\\/)?(?:${hostsRegexPart})|(?:(?<!\\S)|(?<=\\]))(?=\\/[a-zA-Z0-9_\\-]))`;
const imageRegex = new RegExp(`(?<![\\(\\[])(${domainOrRelative}(?:\\/${safeS}+\\.(?:jpg|jpeg|png|gif|webp)(?:\\?${safeS}+)?))(?![\\)\\]])`, 'gi');
const rawVideoRegex = new RegExp(`(?<![\\(\\[])(${domainOrRelative}(?:\\/[^\\s\\[\\]\\(\\)]*\\.(?:mp4|webm|ogv|mov)(?:\\?[^\\s\\[\\]\\(\\)]+)?(?:#gif)?))`, 'gi');
const mentionRegex = /(?<!\[)@([a-zA-Z0-9_\-\.]+)(?!\])|\[@([^\]]+)\]/g;
const mentionRegex = /(?<!\[)@([a-zA-Z0-9_\-\.]+)(?!\])|\[@([^\]]+)\]\(\/user\/([^)]+)\)|\[@([^\]]+)\]/g;
const renderer = new marked.Renderer();
renderer.blockquote = function (quote) {
@@ -207,9 +262,10 @@
// Manual greentext handling — apply emoji if the user preference allows it
const quoteContent = line.substring(line.indexOf('>') + 1);
const quoteEmojis = window.f0ckSession?.quote_emojis === true;
const escapedQuote = quoteContent.replace(/>/g, '&gt;');
const rendered = quoteEmojis
? quoteContent.replace(/:([a-z0-9_]+):/g, (m, n) => renderEmoji(m, n))
: quoteContent;
? escapedQuote.replace(/:([a-z0-9_]+):/g, (m, n) => renderEmoji(m, n))
: escapedQuote;
return `<span class="greentext">&gt;${rendered}</span>`;
}
@@ -222,9 +278,13 @@
let processedLine = line;
// Handle Mentions
processedLine = processedLine.replace(mentionRegex, (match, g1, g2) => {
const user = g1 || g2;
return `<a href="/user/${encodeURIComponent(user)}" class="mention">@${user}</a>`;
const mentionStore = [];
processedLine = processedLine.replace(mentionRegex, (match, g1, g2, g3, g4) => {
const user = g1 || g2 || g4;
const html = `<a href="/user/${encodeURIComponent(user)}" class="mention">@${user}</a>`;
const idx = mentionStore.length;
mentionStore.push(html);
return `\x02MNT${idx}\x03`;
});
// Handle Comment Context Links (>>ID)
@@ -247,13 +307,33 @@
return `[video](${fullUrl})`;
});
// Use marked for each line individually
let mdSafe = processedLine.replace(/\*/g, '\\*').replace(/_/g, '\\_');
const bs = String.fromCharCode(92);
mdSafe = mdSafe.split(bs + bs + '_').join(bs + bs + bs + '_');
// Use marked for each line individually.
// Protect URLs and already-formed Markdown link/image tokens from the
// italic-prevention pass so that underscores in query params
// (e.g. ?v=_FcvmypiHg4) are never turned into ?v=\_FcvmypiHg4.
const mdProtected = [];
// Match [text](url) / ![alt](url) tokens AND bare http(s) URLs
let mdSafe = processedLine.replace(
/(!?\[[^\]]*\]\([^)]*\))|https?:\/\/\S+/g,
(match) => {
const idx = mdProtected.length;
mdProtected.push(match);
return `\x02MDURL${idx}\x03`;
}
);
// Escape * and _ only in the non-URL portions
mdSafe = mdSafe
.replace(/\\/g, '\\\\')
.replace(/\*/g, '\\*')
.replace(/_/g, '\\_');
// Restore protected URLs/tokens
mdSafe = mdSafe.replace(/\x02MDURL(\d+)\x03/g, (_, i) => mdProtected[+i]);
let rendered = marked.parseInline ? marked.parseInline(mdSafe, { renderer: renderer }) : marked.parse(mdSafe, { renderer: renderer }).replace(/<p>|<\/p>/g, '');
// Restore Mentions
rendered = rendered.replace(/\x02MNT(\d+)\x03/g, (_, i) => mentionStore[+i]);
// Render emojis ONLY if this is NOT a quote line OR if the user prefers it
const quoteEmojis = window.f0ckSession?.quote_emojis === true;
if (!trimmed.startsWith('>') || quoteEmojis) {
@@ -290,6 +370,14 @@
}
);
// Abyss label replacement
md = md.replace(
/<a\s[^>]*href="(?:https?:\/\/[^\/]+)?\/abyss(?:#|\/)(\d+)"[^>]*>([\s\S]*?)<\/a>/gi,
(match, abyssId) => {
return `<a href="/abyss/${abyssId}" class="sidebar-abyss-link" data-abyss-id="${abyssId}"><i class="fa-solid fa-dice-d6"></i> /abyss/${abyssId}</a>`;
}
);
// Build regex for allowed media hosters (video/audio)
const escapedSiteHost = window.location.host.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const mediaHosts = [escapedSiteHost];
@@ -367,9 +455,49 @@
const SIDEBAR_MAX_CHARS = 200;
const SIDEBAR_MAX_EMOJIS = 12;
const renderCommentAttachments = (files, content = '') => {
if (!files || files.length === 0) return '';
const items = files.map(f => {
const url = `/c/${f.dest}`;
if (content.includes(url)) return ''; // Skip if already rendered in content
if (f.mime.startsWith('image/')) {
return `<a href="${url}" target="_blank" class="cf-attachment cf-image"><img src="${url}" class="sidebar-comment-img" alt="${escapeHtml(f.original_filename || 'image')}" loading="lazy"></a>`;
} else if (f.mime.startsWith('video/')) {
return `<div class="cf-attachment cf-video"><video src="${url}" class="sidebar-comment-img" controls preload="metadata"></video></div>`;
} else if (f.mime.startsWith('audio/')) {
return `<div class="cf-attachment cf-audio"><audio src="${url}" controls preload="metadata"></audio></div>`;
}
return '';
}).join('');
return items ? `<div class="comment-attachments">${items}</div>` : '';
};
const renderSidebarPoll = (poll, commentId, itemId) => {
if (!poll) return '';
const href = (itemId && commentId) ? `/${itemId}#c${commentId}` : (commentId ? `#sc${commentId}` : '#');
return `<a class="sidebar-poll-preview" href="${href}"><i class="fa-solid fa-chart-bar"></i> ${escapeHtml(poll.question)}</a>`;
};
const renderActivityItem = (c) => {
const rawContent = c.content || c.body || '';
const displayContent = renderCommentContent(rawContent, c.id, c.item_id);
let displayContent = renderCommentContent(rawContent, c.id, c.item_id);
displayContent = window.f0cklib?.processMentions ? window.f0cklib.processMentions(displayContent) : displayContent;
// Robust fallback for is_long if server didn't provide it, plus inline media checks
let isLong = c.is_long;
if (isLong === undefined) {
isLong = rawContent.length > 120
|| rawContent.split('\n').length > 2
|| (c.files && c.files.length > 0);
}
// Always force isLong if there are inline media tags that expand vertically or files are attached
if (!isLong && ((c.files && c.files.length > 0) || /\[(video|audio|youtube|img)\]|!\[|https?:\/\//i.test(rawContent) || displayContent.includes('<video') || displayContent.includes('<img'))) {
isLong = true;
}
const attachmentsHtml = renderCommentAttachments(c.files, rawContent);
const pollHtml = renderSidebarPoll(c.poll, c.id, c.item_id);
// Build avatar URL — same priority as the rest of the app
let avatarSrc = '/a/default.png';
@@ -383,71 +511,151 @@
const timeStr = c.created_at
? (window.f0ckTimeAgo ? window.f0ckTimeAgo(c.created_at) : (c.timeago || c.created_at))
: (c.timeago || 'just now');
const tsAttr = c.created_at ? ` data-ts="${escapeHtml(c.created_at)}"` : '';
const tsAttr = c.created_at ? ` data-ts="${escapeHtml(c.created_at)}" data-iso="${escapeHtml(c.created_at)}"` : '';
const fullDate = c.created_at
? (window.f0ckFormatDateFull ? window.f0ckFormatDateFull(c.created_at) : new Date(c.created_at).toISOString())
: '';
let itemPreview = '';
if (c.item_id) {
let mediaHtml = '';
const rClass = c.item_rating_class || 'untagged';
const blurNsfw = localStorage.getItem('blurNsfw') === 'true';
const blurNsfl = localStorage.getItem('blurNsfl') === 'true';
const blurSfw = localStorage.getItem('blurSfw') === 'true';
const blurUntagged = localStorage.getItem('blurUntagged') === 'true';
let isBlurred = false;
if (rClass === 'nsfw' && blurNsfw) isBlurred = true;
else if (rClass === 'nsfl' && blurNsfl) isBlurred = true;
else if (rClass === 'sfw' && blurSfw) isBlurred = true;
else if (rClass === 'untagged' && blurUntagged) isBlurred = true;
let thumbUrl = `/t/${c.item_id}.webp`;
if (isBlurred) {
thumbUrl = `/t/${c.item_id}_blur.webp`;
}
if (window.applyThumbCacheBust) thumbUrl = window.applyThumbCacheBust(thumbUrl);
mediaHtml = `<img src="${thumbUrl}" style="width: 32px; height: 32px; object-fit: cover; border-radius: 2px;" loading="lazy" onerror="this.style.display='none'" />`;
itemPreview = `
<div class="item-preview">
<a href="/${c.item_id}">${mediaHtml}</a>
<a href="/${c.item_id}" class="sidebar-thumb-link" data-mode="${rClass}">${mediaHtml}</a>
<a href="/${c.item_id}#c${c.id}" style="font-size: 0.8em; color: var(--accent); text-decoration: none;">${(window.f0ckI18n && window.f0ckI18n.sidebar_view) || 'View'} &raquo;</a>
</div>`;
}
return `
<div class="comment" id="sc${c.id}">
<div class="comment-body">
<div class="comment-header">
<div class="comment-header-left">
<a href="/user/${c.username.toLowerCase()}" class="sidebar-avatar-link">
<img src="${avatarSrc}" class="sidebar-avatar" alt="${c.username}" loading="lazy" />
<img src="${avatarSrc}" class="sidebar-avatar" loading="eager" onload="this.classList.add('loaded')" onerror="this.classList.add('loaded');this.src='/a/default.png'" />
</a>
<a href="/user/${c.username.toLowerCase()}" class="comment-author" ${c.username_color ? `style="color: ${c.username_color}"` : ''}>${escapeHtml(c.display_name || c.username)}</a>
</div>
<span class="comment-time timeago" style="font-size: 0.75em;"${tsAttr}>${timeStr}</span>
<span class="comment-time timeago" tooltip="${fullDate}" style="font-size: 0.75em;"${tsAttr}>${timeStr}</span>
</div>
<div class="comment-content"><div class="comment-content-inner">${displayContent}</div><button class="read-more-btn">${window.f0ckI18n?.sidebar_read_more || 'read more'}</button></div>
<div class="comment-content${isLong ? ' has-overflow' : ''}"><div class="comment-content-inner">${displayContent}${attachmentsHtml}${pollHtml}</div><button class="read-more-btn"${isLong ? ' style="display:block"' : ''}>${window.f0ckI18n?.sidebar_read_more || 'read more'}</button></div>
${itemPreview}
</div>
</div>`;
};
const checkOverflow = () => {
document.querySelectorAll('.sidebar-activity .comment-content-inner').forEach(inner => {
const checkOverflow = (targetElement) => {
const targets = targetElement
? (targetElement.classList.contains('comment-content-inner') ? [targetElement] : targetElement.querySelectorAll('.comment-content-inner'))
: document.querySelectorAll('.sidebar-activity .comment-content-inner');
const results = [];
// Read phase: batch layout reads first
targets.forEach(inner => {
const container = inner.parentElement;
const btn = container.querySelector('.read-more-btn');
const btn = container ? container.querySelector('.read-more-btn') : null;
if (!btn) return;
// If expanded, always show "see less"
if (container.classList.contains('expanded')) {
btn.style.display = 'block';
const isExpanded = container.classList.contains('expanded');
const scrollHeight = inner.scrollHeight;
const clientHeight = inner.clientHeight;
const hasUnloadedImages = Array.from(inner.querySelectorAll('img, video')).some(
media => {
if (media.tagName === 'IMG') {
return (!media.complete || media.naturalHeight === 0) && media.dataset.error !== 'true';
}
if (media.tagName === 'VIDEO') {
return media.readyState < 1 && media.dataset.error !== 'true'; // HAVE_METADATA
}
return false;
}
);
results.push({
container,
btn,
isExpanded,
scrollHeight,
clientHeight,
hasUnloadedImages
});
});
// Write phase: perform DOM updates after all reads are completed.
// Visibility of the button is controlled entirely by the CSS rule on
// .comment-content.has-overflow > .read-more-btn — no btn.style.display here.
results.forEach(({ container, btn, isExpanded, scrollHeight, clientHeight, hasUnloadedImages }) => {
// Clear any leftover inline display style (e.g. from the HTML template's
// style="display:block") so the CSS class-based rule is the single source of truth.
btn.style.display = '';
if (isExpanded) {
btn.textContent = window.f0ckI18n?.sidebar_see_less || 'see less';
return;
}
if (inner.scrollHeight > inner.clientHeight + 2) { // 2px buffer for rounding
btn.style.display = 'block';
if (scrollHeight > clientHeight + 2) { // 2px buffer for rounding
// Content overflows — ensure clamped state (may already be set from HTML default)
btn.textContent = window.f0ckI18n?.sidebar_read_more || 'read more';
container.classList.add('has-overflow');
} else if (hasUnloadedImages) {
// Images haven't loaded yet — their height is 0 so we can't tell if content
// will overflow. Keep has-overflow set; attachMediaLoadListeners will
// re-run checkOverflow once images finish loading.
} else {
btn.style.display = 'none';
// Content fits and all images are loaded — safe to remove clamped state
container.classList.remove('has-overflow');
}
});
};
const attachMediaLoadListeners = (element) => {
element.querySelectorAll('img, video').forEach(media => {
// Only target images and videos inside comment-content-inner.
// Avatars and item preview thumbnails have fixed sizes and do not affect text overflow.
element.querySelectorAll('.comment-content-inner img, .comment-content-inner video').forEach(media => {
if (media.dataset.loadListenerBound) return;
media.dataset.loadListenerBound = 'true';
media.addEventListener('load', checkOverflow, { once: true });
media.addEventListener('loadedmetadata', checkOverflow, { once: true });
const inner = media.closest('.comment-content-inner');
if (inner) {
const handler = () => checkOverflow(inner);
const errorHandler = () => {
media.dataset.error = 'true';
checkOverflow(inner);
};
media.addEventListener('load', handler, { once: true });
media.addEventListener('error', errorHandler, { once: true });
media.addEventListener('loadedmetadata', handler, { once: true });
// Also use ResizeObserver to catch layout changes (e.g. cached image layout deferred)
if (window.ResizeObserver) {
const ro = new ResizeObserver(() => checkOverflow(inner));
ro.observe(media);
}
}
});
};
@@ -459,7 +667,7 @@
const contentDiv = readBtn.closest('.comment-content');
if (contentDiv) {
contentDiv.classList.toggle('expanded');
checkOverflow(); // Re-sync button text and visibility
checkOverflow(contentDiv); // Re-sync button text and visibility for this element
}
return;
}
@@ -470,43 +678,28 @@
const showSkeletons = () => {
const container = document.getElementById('sidebar-activity-container');
if (!container) return;
const variants = [
`<div class="skeleton-line skeleton-text-long"></div>
<div class="skeleton-line skeleton-text-medium"></div>
<div class="skeleton-line skeleton-text-short"></div>`,
`<div class="skeleton-line skeleton-text-long"></div>
<div class="skeleton-line skeleton-text-short"></div>`,
`<div class="skeleton-line skeleton-text-medium"></div>
<div class="skeleton-line skeleton-text-long"></div>
<div class="skeleton-line skeleton-text-short"></div>`,
`<div class="skeleton-line skeleton-text-long"></div>
<div class="skeleton-line skeleton-text-medium"></div>`,
`<div class="skeleton-line skeleton-text-short"></div>
<div class="skeleton-line skeleton-text-long"></div>`,
];
let html = '';
for (let i = 0; i < SIDEBAR_SKELETON_COUNT; i++) {
html += `
<div class="sidebar-skeleton-item">
<div class="skeleton-header">
<div class="skeleton-avatar"></div>
<div class="skeleton-meta">
<div class="skeleton-line skeleton-name"></div>
<div class="skeleton-line skeleton-time"></div>
</div>
</div>
${variants[i % 5]}
</div>`;
}
container.innerHTML = html;
// Auto-play converted GIF videos
container.querySelectorAll('video.autoplay-gif').forEach(v => { v.autoplay = true; v.muted = true; v.play().catch(() => { v.addEventListener('canplay', () => v.play().catch(() => { }), { once: true }); }); });
container.innerHTML = `
<div class="sidebar-loading-state">
<i class="fa-solid fa-circle-notch fa-spin"></i>
<span>${window.f0ckI18n?.sidebar_loading_activity || 'Loading activity...'}</span>
</div>
`;
};
const renderFromCache = () => {
const renderFromCache = (force = false) => {
const container = document.getElementById('sidebar-activity-container');
if (!container || window._sidebarActivityCache.length === 0) return false;
const currentIds = window._sidebarActivityCache.map(c => String(c.id)).join(',');
// If the same comments are already rendered, leave the DOM completely untouched.
// This keeps video stickers playing and avoids any overflow state churn.
// force=true bypasses this guard for cases where content changed without ID changes
// (e.g. emojis just loaded and need to replace raw :codes: in existing comments).
if (!force && currentIds === lastRenderedIds && container.querySelector('.comment')) {
return true;
}
lastRenderedIds = currentIds;
let html = '';
window._sidebarActivityCache.forEach(c => {
html += renderActivityItem(c);
@@ -518,15 +711,35 @@
container.appendChild(ioSentinel);
}
attachMediaLoadListeners(container);
// has-overflow is now set per-comment by the server (via is_long) so the
// correct clamped/unclamped state is baked into the HTML on first paint.
// checkOverflow still runs deferred to handle two edge cases:
// 1. Comments with images whose heights are 0 at inject time — the server
// correctly marks them is_long:true, but images that load extra-tall
// still need a re-check after load (handled by attachMediaLoadListeners).
// 2. Any mis-estimates: content that the heuristic got wrong is corrected
// after layout so measurements are accurate.
// Run checkOverflow synchronously immediately after setting innerHTML.
// This forces a synchronous layout (reflow) but guarantees the browser
// will not paint the intermediate state, completely eliminating any "flash"
// of the button popping in or out.
checkOverflow();
// checkOverflow still runs deferred to handle image loads (attachMediaLoadListeners)
// and a fallback 1s timeout for any incredibly slow layout edge cases.
requestAnimationFrame(() => {
setTimeout(checkOverflow, 1000);
});
fetchSidebarYoutubeTitles(container);
// Auto-play converted GIF videos
// Auto-play converted GIF videos and webm emoji stickers
container.querySelectorAll('video.autoplay-gif').forEach(v => { v.autoplay = true; v.muted = true; v.play().catch(() => { v.addEventListener('canplay', () => v.play().catch(() => { }), { once: true }); }); });
playSidebarEmojiVideos(container);
return true;
};
const SIDEBAR_PAGE_LIMIT = 15;
const SIDEBAR_INITIAL_LIMIT = 15;
const SIDEBAR_MAX_COMMENTS = 20;
const loadActivity = async (silent = false) => {
const container = document.getElementById('sidebar-activity-container');
@@ -552,22 +765,21 @@
const data = await res.json();
if (data.success && data.comments && data.comments.length > 0) {
window._sidebarActivityCache = data.comments.map(c => ({
window._sidebarActivityCache = data.comments.slice(0, SIDEBAR_MAX_COMMENTS).map(c => ({
...c,
body: c.content || c.body
}));
hasMore = data.hasMore === true || data.comments.length === SIDEBAR_INITIAL_LIMIT;
renderFromCache();
// Also check after a delay to account for image/emoji loading shifts
setTimeout(checkOverflow, 500);
hasMore = (data.hasMore === true || data.comments.length === SIDEBAR_INITIAL_LIMIT)
&& window._sidebarActivityCache.length < SIDEBAR_MAX_COMMENTS;
renderFromCache(); // no-op if IDs unchanged (renderFromCache self-guards)
} else if (!hasCache) {
container.innerHTML = '<div style="text-align:center;padding:20px;color:#888;">No recent activity.</div>';
container.innerHTML = '<div style="text-align:center;padding:20px;color:#888;">' + (window.f0ckI18n?.sidebar_no_activity || 'No recent activity.') + '</div>';
hasMore = false;
}
} catch (e) {
console.error("Sidebar Activity: Failed to load activity", e);
if (!hasCache) {
container.innerHTML = '<div style="text-align:center;padding:20px;color:#888;">Failed to load.</div>';
container.innerHTML = '<div style="text-align:center;padding:20px;color:#888;">' + (window.f0ckI18n?.sidebar_failed_to_load || 'Failed to load.') + '</div>';
}
hasMore = false;
} finally {
@@ -589,7 +801,7 @@
const sentinel = document.createElement('div');
sentinel.id = 'sidebar-load-more-sentinel';
sentinel.style.cssText = 'text-align:center;padding:8px 0;font-size:0.78em;color:#666;';
sentinel.textContent = 'Loading…';
sentinel.textContent = window.f0ckI18n?.sidebar_loading_more || 'Loading…';
container.appendChild(sentinel);
try {
@@ -605,40 +817,65 @@
if (data.success && data.comments && data.comments.length > 0) {
currentPage++;
hasMore = data.hasMore === true;
// Append only comments not already in the cache
// Append only comments not already in the cache, up to the global cap
const remaining = SIDEBAR_MAX_COMMENTS - window._sidebarActivityCache.length;
const existingIds = new Set(window._sidebarActivityCache.map(c => String(c.id)));
const newComments = data.comments.filter(c => !existingIds.has(String(c.id))).map(c => ({
...c,
body: c.content || c.body
}));
const newComments = data.comments
.filter(c => !existingIds.has(String(c.id)))
.slice(0, remaining)
.map(c => ({ ...c, body: c.content || c.body }));
window._sidebarActivityCache.push(...newComments);
// Stop loading more if the hard cap is reached
hasMore = data.hasMore === true
&& window._sidebarActivityCache.length < SIDEBAR_MAX_COMMENTS;
// Append new items to DOM
let html = '';
newComments.forEach(c => { html += renderActivityItem(c); });
if (html) {
const temp = document.createElement('div');
temp.innerHTML = html;
const addedNodes = [];
while (temp.firstElementChild) {
container.appendChild(temp.firstElementChild);
const node = temp.firstElementChild;
container.appendChild(node);
addedNodes.push(node);
}
// Keep the IO sentinel at the very end so it triggers on the next scroll
if (ioSentinel) container.appendChild(ioSentinel);
attachMediaLoadListeners(container);
checkOverflow();
fetchSidebarYoutubeTitles(container);
// Auto-play converted GIF videos
addedNodes.forEach(node => {
attachMediaLoadListeners(node);
fetchSidebarYoutubeTitles(node);
playSidebarEmojiVideos(node);
});
// Defer overflow checks to after layout so measurements are accurate.
addedNodes.forEach(node => checkOverflow(node));
requestAnimationFrame(() => {
// Deferred re-check for image comments — mirrors renderFromCache behaviour.
// Images in newly appended nodes may not be laid out yet at append time.
setTimeout(() => addedNodes.forEach(node => checkOverflow(node)), 1000);
});
// Auto-play converted GIF videos and webm emoji stickers
container.querySelectorAll('video.autoplay-gif').forEach(v => { v.autoplay = true; v.muted = true; v.play().catch(() => { v.addEventListener('canplay', () => v.play().catch(() => { }), { once: true }); }); });
}
if (!hasMore) {
// Show end-of-feed indicator
const end = document.createElement('div');
end.style.cssText = 'text-align:center;padding:8px 0;font-size:0.75em;color:#444;';
end.textContent = window.f0ckI18n?.sidebar_end_of_activity || '─ end of activity ─';
container.appendChild(end);
}
} else {
hasMore = false;
// Show end-of-feed indicator
const end = document.createElement('div');
end.style.cssText = 'text-align:center;padding:8px 0;font-size:0.75em;color:#444;';
end.textContent = '─ end of activity ─';
end.textContent = window.f0ckI18n?.sidebar_end_of_activity || '─ end of activity ─';
container.appendChild(end);
}
} catch (e) {
@@ -659,7 +896,7 @@
return;
}
// 2. Update cache (prepend, no hard cap — infinite scroll handles depth)
// 2. Update cache (prepend, capped at SIDEBAR_MAX_COMMENTS)
const newItem = {
...data,
body: data.body || data.content,
@@ -667,9 +904,22 @@
};
window._sidebarActivityCache.unshift(newItem);
// Trim cache to the hard cap and remove the evicted DOM node (if any)
if (window._sidebarActivityCache.length > SIDEBAR_MAX_COMMENTS) {
const evicted = window._sidebarActivityCache.pop();
if (container && evicted) {
const evictedEl = document.getElementById('sc' + evicted.id);
if (evictedEl) evictedEl.remove();
}
}
// Update DOM if visible
if (container) {
const html = renderActivityItem(newItem);
// is_long may be provided by the server (SSE payload) or absent for legacy events.
// Default to true so the button is always visible; checkOverflow will hide it
// if the rendered content is actually short.
const itemWithLong = { ...newItem, is_long: newItem.is_long !== false };
const html = renderActivityItem(itemWithLong);
const temp = document.createElement('div');
temp.innerHTML = html;
const node = temp.firstElementChild;
@@ -677,15 +927,26 @@
node.classList.add('new-item-fade');
container.prepend(node);
attachMediaLoadListeners(node);
checkOverflow();
checkOverflow(node);
fetchSidebarYoutubeTitles(container);
playSidebarEmojiVideos(node);
}
}
};
const init = async () => {
await loadEmojis();
loadActivity();
// Run emoji loading and activity fetching in parallel — avatars appear
// immediately without waiting for the emoji API to respond first.
// After both settle, if emojis finished after the initial render, re-render
// from cache so custom emoji images show on first page load.
const emojiPromise = loadEmojis();
const activityPromise = loadActivity();
await activityPromise;
await emojiPromise;
// If emojis were not yet available when activity first rendered, re-render now.
if (Object.keys(customEmojis).length > 0 && window._sidebarActivityCache.length > 0) {
renderFromCache(true); // force: emojis are now loaded, content changed
}
};
// Listen for live activity from f0ckm.js
@@ -718,7 +979,7 @@
void el.offsetWidth;
el.classList.add('new-item-fade');
attachMediaLoadListeners(inner);
checkOverflow();
requestAnimationFrame(() => checkOverflow(inner));
fetchSidebarYoutubeTitles(el);
// Auto-play converted GIF videos
inner.querySelectorAll('video.autoplay-gif').forEach(v => { v.autoplay = true; v.muted = true; v.play().catch(() => { v.addEventListener('canplay', () => v.play().catch(() => { }), { once: true }); }); });
@@ -732,6 +993,20 @@
handleLiveEdit(e.detail);
});
// When emojis are refreshed (e.g. after sticker pack import), sync the sidebar
// cache and re-render so newly imported stickers appear in existing entries.
window.addEventListener('f0ck:emojis_ready', () => {
const csCache = (typeof CommentSystem !== 'undefined' && CommentSystem.emojiCache) || null;
if (!csCache || Object.keys(csCache).length === 0) return;
// Merge new emojis into local cache (additive — never removes)
const hadBefore = Object.keys(customEmojis).length;
Object.assign(customEmojis, csCache);
const hasNew = Object.keys(customEmojis).length > hadBefore;
if (hasNew && window._sidebarActivityCache.length > 0) {
renderFromCache(true); // force: new emoji images available, re-render
}
});
let lastBoundMode = typeof window.activeMode !== 'undefined' ? window.activeMode : null;
// Handle AJAX item loads
@@ -744,6 +1019,7 @@
if (modeChanged) {
window._sidebarActivityCache = [];
lastRenderedIds = '';
currentPage = 1;
hasMore = true;
loadActivity(false); // Force reload with loading state
@@ -765,6 +1041,7 @@
window.f0ckDebug("Sidebar Activity: Mode change detected", e.detail.mode);
lastBoundMode = e.detail.mode;
window._sidebarActivityCache = [];
lastRenderedIds = '';
currentPage = 1;
hasMore = true;
loadActivity(false);

View File

@@ -71,11 +71,13 @@ window.TagAutocomplete = (() => {
// Flag to prevent focusout from destroying dropdown while touching it
let dropdownTouching = false;
// Flag set when we intentionally blur to dismiss the keyboard on mobile
let keyboardDismissed = false;
dropdown.addEventListener('touchstart', () => { dropdownTouching = true; }, { passive: true });
dropdown.addEventListener('touchend', () => {
dropdownTouching = false;
// Re-focus input so user can keep typing after scrolling
input.focus();
// Note: do NOT re-focus input here — that would reopen the mobile keyboard.
// The keyboard only comes back when the user explicitly taps the input.
}, { passive: true });
dropdown.addEventListener('touchcancel', () => { dropdownTouching = false; }, { passive: true });
@@ -267,18 +269,51 @@ window.TagAutocomplete = (() => {
open(opts);
});
// Close when clicking/tapping outside
const onDocClick = (e) => {
// Close when clicking/tapping outside.
// Desktop (mousedown): close immediately.
// Mobile (touchstart): first tap outside dismisses the keyboard only (blur),
// leaving suggestions visible so the user can scroll up to see them.
// A second tap outside within 500 ms actually closes the dropdown.
let outsideTapCount = 0;
let outsideTapTimer = null;
const onDocMousedown = (e) => {
if (!wrapper.contains(e.target) && e.target !== anchorEl) {
document.removeEventListener('mousedown', onDocClick);
document.removeEventListener('touchstart', onDocClick);
document.removeEventListener('mousedown', onDocMousedown);
destroy();
}
};
// Delay attaching to avoid capturing the opening click
const onDocTouchstart = (e) => {
if (wrapper.contains(e.target) || e.target === anchorEl) return;
outsideTapCount++;
if (outsideTapCount === 1) {
// First outside tap — just blur to dismiss the keyboard.
// Suggestions remain visible so the user can scroll up to see them.
keyboardDismissed = true;
input.blur();
// Reset the flag after the blur event has fired.
setTimeout(() => { keyboardDismissed = false; }, 100);
// Reset the counter after the double-tap window expires.
outsideTapTimer = setTimeout(() => {
outsideTapCount = 0;
}, 500);
} else {
// Second outside tap — close the dropdown.
clearTimeout(outsideTapTimer);
outsideTapCount = 0;
document.removeEventListener('touchstart', onDocTouchstart);
destroy();
}
};
// Delay attaching to avoid capturing the opening touch.
setTimeout(() => {
document.addEventListener('mousedown', onDocClick);
document.addEventListener('touchstart', onDocClick, { passive: true });
document.addEventListener('mousedown', onDocMousedown);
document.addEventListener('touchstart', onDocTouchstart, { passive: true });
}, 0);
// Click on the wrapper area should refocus the input
@@ -293,6 +328,7 @@ window.TagAutocomplete = (() => {
// Delay to allow suggestion tap/scroll to complete first
setTimeout(() => {
if (dropdownTouching) return; // user is interacting with dropdown
if (keyboardDismissed) return; // intentional blur to hide mobile keyboard
// Don't close if focus is still within the wrapper
if (activeInstance && wrapper.contains(document.activeElement)) return;
if (activeInstance && input.value.length === 0 && document.activeElement !== input) {

View File

@@ -15,7 +15,7 @@
}
};
const themes = window.f0ckThemes || ['amoled', 'atmos', 'f0ck', 'f0ck95d', 'iced', 'orange', 'p1nk', '4d'];
const themes = window.f0ckThemes || ['amoled', 'atmos', 'f0ck', 'f0ck95d', 'f0ck98', 'iced', 'orange', 'p1nk', '4d'];
const defaultTheme = window.f0ckDefaultTheme || (window.f0ckSession && window.f0ckSession.default_theme) || themes[0] || 'amoled';
const setTheme = (theme) => {

File diff suppressed because it is too large Load Diff

View File

@@ -56,7 +56,7 @@
a.textContent = tag.tag;
const span = document.createElement("span");
span.classList.add("badge", "mr-2");
span.classList.add("badge");
if (highlightTag && (tag.tag === highlightTag || tag.normalized === highlightTag)) {
span.classList.add('new-tag-glow');
}
@@ -120,7 +120,13 @@
postid,
existingTags: tags,
anchorEl: anchor,
onSubmit: async (tag) => post("/api/v2/tags/" + postid, { tagname: tag }),
onSubmit: async (tag) => {
const res = await post("/api/v2/tags/" + postid, { tagname: tag });
if (res.success && window.invalidateItemCache) {
window.invalidateItemCache(postid);
}
return res;
},
renderTags
});
};
@@ -189,7 +195,6 @@
a.appendChild(img);
favcontainer.appendChild(a);
favcontainer.appendChild(document.createTextNode('\u00A0'));
});
favcontainer.hidden = false;
} else {

View File

@@ -1,12 +1,15 @@
class UserCommentSystem {
constructor() {
this.container = document.getElementById('user-comments-container');
this.username = this.container ? this.container.dataset.user : null;
this.page = 1;
this.loading = false;
this.finished = false;
this.userColor = null;
this.customEmojis = UserCommentSystem.emojiCache || {};
if (!window.UserCommentSystem) {
window.UserCommentSystem = class UserCommentSystem {
constructor() {
this.container = document.getElementById('user-comments-container');
this.username = this.container ? this.container.dataset.user : null;
this.page = 1;
this.loading = false;
this.finished = false;
this.userColor = null;
this.customEmojis = UserCommentSystem.emojiCache || {};
this.icons = {
reply: `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 10 20 15 15 20"></polyline><path d="M4 4v7a4 4 0 0 0 4 4h12"></path></svg>`,
@@ -23,12 +26,16 @@ class UserCommentSystem {
}
handleLiveEdit(data) {
if (!this.container) return;
if (!this.container || !document.body.contains(this.container)) {
window.removeEventListener('f0ck:comment_edited', this.editListener);
return;
}
const el = document.getElementById('c' + data.comment_id);
if (el && this.container.contains(el)) {
const contentEl = el.querySelector('.comment-content');
if (contentEl) {
contentEl.innerHTML = this.renderCommentContent(data.content, data.item_id);
this.playEmojiVideos(contentEl);
el.classList.remove('new-item-fade');
void el.offsetWidth;
el.classList.add('new-item-fade');
@@ -37,7 +44,7 @@ class UserCommentSystem {
}
async init() {
this.loadEmojis();
await this.loadEmojis();
this.loadMore();
this.loadMore();
this.bindEvents();
@@ -112,6 +119,7 @@ class UserCommentSystem {
const html = this.renderComment(c);
this.container.insertAdjacentHTML('beforeend', html);
});
this.playEmojiVideos(this.container);
this.page++;
} else {
this.finished = true;
@@ -127,13 +135,89 @@ class UserCommentSystem {
}
}
playEmojiVideos(container) {
if (!container) return;
container.querySelectorAll('video.emoji').forEach(v => {
v.play().catch(() => {
v.addEventListener('canplay', () => v.play().catch(() => {}), { once: true });
});
});
}
renderEmoji(match, name) {
if (this.customEmojis && this.customEmojis[name]) {
return `<img src="${this.customEmojis[name]}" style="height:60px;vertical-align:middle;" alt="${name}">`;
const url = this.customEmojis[name];
if (url.endsWith('.webm')) {
return `<video src="${url}" class="emoji" autoplay loop muted playsinline title=":${name}:"></video>`;
}
return `<img src="${url}" class="emoji" alt="${match}" title="${match}">`;
}
return match;
}
renderCommentAttachments(files, content = '') {
if (!files || files.length === 0) return '';
const items = files.map(f => {
const url = `/c/${f.dest}`;
if (content && content.includes(url)) return ''; // Skip if already rendered in content
if (f.mime && f.mime.startsWith('image/')) {
return `<a href="${url}" target="_blank" class="cf-attachment cf-image"><img src="${url}" alt="${this.escapeHtml(f.original_filename || 'image')}" loading="lazy"></a>`;
} else if (f.mime && f.mime.startsWith('video/')) {
return `<div class="cf-attachment cf-video"><video src="${url}" controls preload="metadata"></video></div>`;
} else if (f.mime && f.mime.startsWith('audio/')) {
return `<div class="cf-attachment cf-audio"><audio src="${url}" controls preload="metadata"></audio></div>`;
}
return '';
}).join('');
return items ? `<div class="comment-attachments">${items}</div>` : '';
}
renderCommentPoll(poll, commentId) {
if (!poll) return '';
const i18n = window.f0ckI18n || {};
const session = window.f0ckSession || {};
const total = poll.total_votes || 0;
const voted = !!poll.user_vote_option_id;
const expired = poll.expires_at && new Date(poll.expires_at) < new Date();
const isAnon = poll.is_anonymous !== false;
const optionsHtml = (poll.options || []).map(opt => {
const pct = total > 0 ? Math.round((opt.vote_count / total) * 100) : 0;
const isVoted = poll.user_vote_option_id === opt.id;
const clickable = session.logged_in && !expired && !voted;
const voterAvatars = (!isAnon && Array.isArray(opt.voters) && opt.voters.length > 0)
? `<div class="poll-option-voters">${opt.voters.map(v => {
const u = (v && typeof v === 'object') ? v : { username: String(v || ''), avatar: null, avatar_file: null };
const name = String(u.username || '');
const src = u.avatar_file ? `/a/${u.avatar_file}` : u.avatar ? `/t/${u.avatar}.webp` : '/a/default.png';
return name ? `<a href="/user/${this.escapeHtml(name)}" title="${this.escapeHtml(name)}"><img class="poll-voter-avatar" src="${src}" alt="${this.escapeHtml(name)}" loading="lazy"></a>` : '';
}).join('')}</div>`
: '';
return `<div class="poll-option ${isVoted ? 'poll-option-voted' : ''} ${clickable ? 'poll-option-clickable' : ''}"
data-option-id="${opt.id}" data-poll-id="${poll.id}" data-comment-id="${commentId}">
<div class="poll-option-bar" style="width:${pct}%"></div>
<span class="poll-option-text">${this.escapeHtml(opt.text)}</span>
<span class="poll-option-pct">${pct}%</span>
${isVoted ? `<i class="fa-solid fa-check poll-vote-check" title="${i18n.poll_voted || 'You voted'}"></i>` : ''}
${voterAvatars}
</div>`;
}).join('');
const anonBadge = isAnon
? `<span class="poll-anon-badge" title="${i18n.poll_anonymous || 'Anonymous'}"><i class="fa-solid fa-user-secret"></i></span>`
: `<span class="poll-anon-badge poll-public-badge" title="${i18n.poll_public || 'Public votes'}"><i class="fa-solid fa-eye"></i></span>`;
return `<div class="comment-poll" data-poll-id="${poll.id}" data-is-anonymous="${isAnon ? '1' : '0'}">
<div class="poll-question">${this.escapeHtml(poll.question)}</div>
<div class="poll-options">${optionsHtml}</div>
<div class="poll-footer">
<span class="poll-total">${total} ${total === 1 ? (i18n.poll_vote_single || 'vote') : (i18n.poll_votes || 'votes')}</span>
${anonBadge}
${expired ? `<span class="poll-expired-badge">${i18n.poll_expired || 'Poll closed'}</span>` : ''}
</div>
</div>`;
}
renderCommentContent(content, itemId = null) {
if (!content) return '';
@@ -152,7 +236,7 @@ class UserCommentSystem {
let escaped = this.escapeHtml(content).replace(/&gt;/g, ">");
// 2. Mentions
const mentionRegex = /(?<!\[)@([a-zA-Z0-9_\-\.]+)(?!\])/g;
const mentionRegex = /(?<!\[)@([a-zA-Z0-9_\-\.]+)(?!\])|\[@([^\]]+)\]\(\/user\/([^)]+)\)|\[@([^\]]+)\]/g;
const siteOrigin = window.location.origin;
const renderer = new marked.Renderer();
@@ -191,19 +275,60 @@ class UserCommentSystem {
return `<a href="${href}"${titleAttr}>${displayText}</a>`;
};
renderer.image = (href, title, text) => {
const src = (typeof href === 'object' && href !== null) ? (href.href || '') : (href || '');
const imgHtml = `<img src="${src}" alt="${text || ''}"${title ? ` title="${title}"` : ''} onerror="this.onerror=null; this.outerHTML='<span class=\\'broken-image-text\\'>[image not found]</span>';">`;
if (window.f0ckSession?.is_admin && src && src.startsWith('/c/')) {
const filename = src.substring(3); // Remove '/c/'
return `<span class="image-embed-wrap">${imgHtml}<button class="admin-delete-attachment-btn" data-filename="${filename}" title="Delete attachment">[x]</button></span>`;
}
return imgHtml;
};
// Pre-compile regexes for image/video/audio embeds matching comments.js
const escapedSiteHost = window.location.host.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const allowedHosts = [escapedSiteHost];
if (window.f0ckAllowedImages && Array.isArray(window.f0ckAllowedImages)) {
window.f0ckAllowedImages.forEach(h => {
const escapedHost = h.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
allowedHosts.push(`(?:[a-z0-9-]+\\.)*${escapedHost}`);
});
}
const hostsRegexPart = allowedHosts.join('|');
const domainOrRelative = `(?:(?:https?:\\/\\/|\\/\\/)?(?:${hostsRegexPart})|(?:(?<!\\S)|(?<=\\]))(?=\\/[a-zA-Z0-9_\\-]))`;
const safeS = `(?:(?!https?:\\/\\/)\\S)`;
const imageRegex = new RegExp(`(?<![\\(\\[])(${domainOrRelative}(?:\\/${safeS}+\\.(?:jpg|jpeg|png|gif|webp)(?:\\?${safeS}+)?(?:#gif)?))(?![\\)\\]])`, 'gi');
const rawVideoRegex = new RegExp(`(?<![\\(\\[])(${domainOrRelative}(?:\\/[^\\s\\[\\]\\(\\)]*\\.(?:mp4|webm|ogv|mov)(?:\\?[^\\s\\[\\]\\(\\)]+)?(?:#gif)?))`, 'gi');
const rawAudioRegex = new RegExp(`(?<![\\(\\[])(${domainOrRelative}(?:\\/[^\\s\\[\\]\\(\\)]*\\.(?:mp3|ogg|wav|flac|aac|opus|m4a)(?:\\?[^\\s\\[\\]\\(\\)]+)?))`, 'gi');
// 3. Line-by-line rendering to avoid paragraph collapsing and recursion
const renderedLines = escaped.split('\n').map(line => {
const trimmed = line.trimStart();
if (trimmed.startsWith('>') && !trimmed.match(/^>>\d+/)) {
const quoteContent = line.substring(line.indexOf('>') + 1);
return `<span class="greentext">&gt;${quoteContent}</span>`;
const quoteEmojis = window.f0ckSession?.quote_emojis === true;
const escapedQuote = quoteContent.replace(/>/g, '&gt;');
const rendered = quoteEmojis
? escapedQuote.replace(/:([a-z0-9_]+):/g, (m, n) => this.renderEmoji(m, n))
: escapedQuote;
return `<span class="greentext">&gt;${rendered}</span>`;
}
// Per-line limit
if (line.length > 10000) return line;
if (!line.trim()) return '&nbsp;';
let processedLine = line.replace(mentionRegex, '[@$1](/user/$1)');
let processedLine = line;
// Handle Mentions
const mentionStore = [];
processedLine = processedLine.replace(mentionRegex, (match, g1, g2, g3, g4) => {
const user = g1 || g2 || g4;
const html = `<a href="/user/${encodeURIComponent(user)}" class="mention">@${user}</a>`;
const idx = mentionStore.length;
mentionStore.push(html);
return `\x02MNT${idx}\x03`;
});
// Handle Comment Context Links (>>ID)
processedLine = processedLine.replace(/(?<!\w)>>(\d+)/g, (match, id) => {
@@ -211,9 +336,34 @@ class UserCommentSystem {
return `<a href="${targetHref}" class="comment-context-link" data-id="${id}">>>${id}</a>`;
});
// Handle Image Embeds
processedLine = processedLine.replace(imageRegex, (match, url) => {
let fullUrl = url;
if (!url.startsWith('http') && !url.startsWith('//') && !url.startsWith('/')) {
fullUrl = '//' + url;
}
return `![image](${fullUrl})`;
});
// Handle Raw Video/Audio links so Marked converts them to <a>
processedLine = processedLine.replace(rawVideoRegex, (match, url) => {
let fullUrl = url;
if (!url.startsWith('http') && !url.startsWith('//') && !url.startsWith('/')) fullUrl = '//' + url;
return `[video](${fullUrl})`;
});
processedLine = processedLine.replace(rawAudioRegex, (match, url) => {
let fullUrl = url;
if (!url.startsWith('http') && !url.startsWith('//') && !url.startsWith('/')) fullUrl = '//' + url;
return `[audio](${fullUrl})`;
});
const escapedAsterisks = processedLine.replace(/\*/g, '\\*');
let rendered = marked.parseInline ? marked.parseInline(escapedAsterisks, { renderer: renderer }) : marked.parse(escapedAsterisks, { renderer: renderer }).replace(/<p>|<\/p>/g, '');
// Restore Mentions
rendered = rendered.replace(/\x02MNT(\d+)\x03/g, (_, i) => mentionStore[+i]);
// Render emojis ONLY if this is NOT a quote line OR if the user prefers it
const quoteEmojis = window.f0ckSession?.quote_emojis === true;
if (!trimmed.startsWith('>') || quoteEmojis) {
@@ -264,35 +414,7 @@ class UserCommentSystem {
const fullDate = new Date(c.created_at).toISOString();
const content = this.renderCommentContent(c.content, c.item_id);
// Replicating the structure of comments.js but adapting for the list view
// We add a header indicating which item this comment belongs to
return `
<div class="comment" id="c${c.id}">
<div class="comment-avatar">
<a href="/${c.item_id}">
<img src="/t/${c.item_id}.webp" alt="">
</a>
</div>
<div class="comment-body">
<div class="comment-header">
<div class="comment-header-left">
<span class="comment-author" tooltip="ID: ${c.user_id}" ${this.userColor ? `style="color: ${this.userColor}"` : ''}>${this.username}</span>
</div>
<span class="comment-time timeago" title="${fullDate}">${timeAgo}</span>
</div>
<div class="comment-content">${content}</div>
<div class="comment-footer">
<div class="comment-footer-right">
<div class="comment-actions">
${window.f0ckSession && window.f0ckSession.logged_in ? `<button class="report-comment-btn" data-id="${c.id}" title="Report Comment" style="background:none;border:none;color:inherit;cursor:pointer;opacity:0.75;padding:0;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 512 512" fill="currentColor"><path d="M506.3 417l-213.3-364c-16.3-28-57.5-28-73.8 0l-213.2 364C-10.6 445.1 9.7 480 42.7 480h426.6C502.5 480 522.6 445.1 506.3 417zM256 384c-14.1 0-25.6-11.5-25.6-25.6 0-14.1 11.5-25.6 25.6-25.6 14.1 0 25.6 11.5 25.6 25.6C281.6 372.5 270.1 384 256 384zM281.6 264.4c0 14.1-11.5 25.6-25.6 25.6-14.1 0-25.6-11.5-25.6-25.6v-96c0-14.1 11.5-25.6 25.6-25.6 14.1 0 25.6 11.5 25.6 25.6V264.4z"/></svg></button>` : ''}
</div>
</div>
</div>
</div>
<a href="/${c.item_id}#c${c.id}" class="comment-permalink" title="Permalink">#${c.id}</a>
</div>
`;
return `<div class="comment" id="c${c.id}"><div class="comment-avatar"><a href="/${c.item_id}"><img src="/t/${c.item_id}.webp" alt=""></a></div><div class="comment-body"><div class="comment-header"><div class="comment-header-left"><span class="comment-author" tooltip="ID: ${c.user_id}" ${this.userColor ? `style="color: ${this.userColor}"` : ''}>${this.username}</span></div><span class="comment-time timeago" title="${fullDate}">${timeAgo}</span></div><div class="comment-content" data-raw="${this.escapeHtml(c.content)}">${content}</div>${this.renderCommentAttachments(c.files, c.content)}${this.renderCommentPoll(c.poll, c.id)}<div class="comment-footer"><div class="comment-footer-right"><div class="comment-actions">${window.f0ckSession && window.f0ckSession.logged_in ? `<button class="report-comment-btn" data-id="${c.id}" title="Report Comment" style="background:none;border:none;color:inherit;cursor:pointer;opacity:0.75;padding:0;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 512 512" fill="currentColor"><path d="M506.3 417l-213.3-364c-16.3-28-57.5-28-73.8 0l-213.2 364C-10.6 445.1 9.7 480 42.7 480h426.6C502.5 480 522.6 445.1 506.3 417zM256 384c-14.1 0-25.6-11.5-25.6-25.6 0-14.1 11.5-25.6 25.6-25.6 14.1 0 25.6 11.5 25.6 25.6C281.6 372.5 270.1 384 256 384zM281.6 264.4c0 14.1-11.5 25.6-25.6 25.6-14.1 0-25.6-11.5-25.6-25.6v-96c0-14.1 11.5-25.6 25.6-25.6 14.1 0 25.6 11.5 25.6 25.6V264.4z"/></svg></button>` : ''}</div></div></div></div><a href="/${c.item_id}#c${c.id}" class="comment-permalink" title="Permalink">#${c.id}</a></div>`;
}
startLiveTimestamps() {
@@ -333,18 +455,24 @@ class UserCommentSystem {
if (!unsafe) return '';
const div = document.createElement('div');
div.textContent = unsafe;
return div.innerHTML;
return div.innerHTML.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
}
}
// Initializer for AJAX and standard load
window.initUserComments = () => {
// Prevent multiple instances if already running on this container
if (document.getElementById('user-comments-container')) {
const container = document.getElementById('user-comments-container');
if (container && !container.dataset.initialized) {
container.dataset.initialized = 'true';
new UserCommentSystem();
}
};
window.addEventListener('DOMContentLoaded', () => {
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', () => {
window.initUserComments();
});
} else {
window.initUserComments();
});
}

View File

@@ -5,33 +5,33 @@ const tpl_player = (svg, size) => `<div class="v0ck_player_controls">
<div class="v0ck_progress_filled"></div>
<div class="v0ck_seek_marker"></div>
</div>
<button class="v0ck_player_button v0ck_tplay v0ck_toggle" title="Play">
<button class="v0ck_player_button v0ck_tplay v0ck_toggle" title="Play" tabindex="-1">
<svg style="width: 20px; height: 20px;">
<use id="v0ck_svg_play" href="${svg}#play"></use>
<use id="v0ck_svg_pause" class="v0ck_hidden" href="${svg}#pause"></use>
</svg>
</button>
<div class="v0ck_volume_group">
<button class="v0ck_player_button v0ck_volume">
<button class="v0ck_player_button v0ck_volume" tabindex="-1">
<svg style="width: 20px; height: 20px;">
<use id="v0ck_svg_volume_full" href="${svg}#volume_full"></use>
<use id="v0ck_svg_volume_mid" class="v0ck_hidden" href="${svg}#volume_mid"></use>
<use id="v0ck_svg_volume_mute" class="v0ck_hidden" href="${svg}#volume_mute"></use>
</svg>
</button>
<input type="range" name="volume" min="0" max="1" step="0.01" value="1" />
<input type="range" name="volume" min="0" max="1" step="0.01" value="1" tabindex="-1" />
</div>
<button class="v0ck_player_button v0ck_playtime">00:00 / 00:00</button>
<button class="v0ck_player_button v0ck_playtime" tabindex="-1">00:00 / 00:00</button>
<span style="flex: 30"></span>
<div class="v0ck_settings_container">
<button class="v0ck_player_button v0ck_settings_btn" title="Settings">
<button class="v0ck_player_button v0ck_settings_btn" title="Settings" tabindex="-1">
<svg viewBox="0 0 24 24" style="width: 20px; height: 20px;">
<path d="M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.06-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.22-0.37-0.29-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.47,0.41L9.25,5.35C8.66,5.59,8.12,5.92,7.63,6.29L5.24,5.33c-0.22-0.08-0.47,0-0.59,0.22L2.74,8.87 C2.62,9.08,2.66,9.34,2.86,9.48l2.03,1.58C4.84,11.36,4.8,11.69,4.8,12s0.02,0.64,0.06,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.22,0.37,0.29,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.36,2.54 c0.05,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.44-0.17,0.47-0.41l0.36-2.54c0.59-0.24,1.13-0.56,1.62-0.94l2.39,0.96 c0.22,0.08,0.47,0,0.59-0.22l1.92-3.32c0.12-0.22,0.07-0.47-0.12-0.61L19.14,12.94z M12,15.6c-1.98,0-3.6-1.62-3.6-3.6 s1.62-3.6,3.6-3.6s3.6,1.62,3.6,3.6S13.98,15.6,12,15.6z"/>
</svg>
</button>
<div class="v0ck_settings_menu v0ck_hidden">
<button id="toggleswf" class="v0ck_menu_item" title="Flash Yank">SWF</button>
<button id="toggleswf" class="v0ck_menu_item" title="Flash Yank" tabindex="-1">SWF</button>
<div class="v0ck_menu_item v0ck_bg_row">
<span class="v0ck_switch_label">Background</span>
<div id="togglebg" class="v0ck_cool_switch" title="Toggle Background"></div>
@@ -44,22 +44,32 @@ const tpl_player = (svg, size) => `<div class="v0ck_player_controls">
<span class="v0ck_switch_label">Danmaku</span>
<div id="toggledanmaku" class="v0ck_cool_switch" title="Toggle Danmaku comments"></div>
</div>
<button id="v0ck_download" class="v0ck_menu_item" title="Download File">Download${size ? ` (${size})` : ''}</button>
<button id="v0ck_download" class="v0ck_menu_item" title="Download File" tabindex="-1">Download${size ? ` (${size})` : ''}</button>
</div>
</div>
<button class="v0ck_player_button v0ck_toggle v0ck_fs_btn" title="Full Screen">
<button class="v0ck_player_button v0ck_toggle v0ck_fs_btn" title="Full Screen" tabindex="-1">
<svg style="width: 20px; height: 20px;"><use id="v0ck_svg_fullscreen" href="${svg}#fullscreen"></use></svg>
</button>
</div>
<div class="v0ck_loader v0ck_hidden"><div></div></div>
<div class="v0ck_speed_indicator v0ck_hidden">
<svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor; display: inline-block; vertical-align: middle; margin-right: 6px;">
<path d="M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z"/>
</svg>
<span>2X Speed</span>
</div>
<div class="v0ck_overlay">
<svg style="width: 60px; height: 60px;">
<use href="${svg}#play"></use>
</svg>
</div>
<div class="v0ck_hud v0ck_hidden">
<svg><use class="v0ck_hud_icon" href="${svg}#volume_full"></use></svg>
<svg>
<use class="v0ck_hud_icon v0ck_hud_volume_full" href="${svg}#volume_full"></use>
<use class="v0ck_hud_icon v0ck_hud_volume_mid v0ck_hidden" href="${svg}#volume_mid"></use>
<use class="v0ck_hud_icon v0ck_hud_volume_mute v0ck_hidden" href="${svg}#volume_mute"></use>
</svg>
<div class="v0ck_hud_bar_container">
<div class="v0ck_hud_bar"></div>
</div>
@@ -111,10 +121,7 @@ class v0ck {
setTimeout(() => parent.classList.remove("v0ck_no_transition"), 50);
}
if (!isMobile) {
parent.addEventListener('mouseenter', () => parent.classList.add("v0ck_hover"));
parent.addEventListener('mouseleave', () => parent.classList.remove("v0ck_hover"));
}
if (!document.querySelector('link[href^="/s/css/v0ck.css"]')) {
document.head.insertAdjacentHTML("beforeend", `<link rel="stylesheet" href="/s/css/v0ck.css">`); // inject css
@@ -157,18 +164,35 @@ class v0ck {
const playtime = player.querySelector('.v0ck_playtime');
const overlay = player.querySelector('.v0ck_overlay');
const volumeButton = player.querySelector('.v0ck_volume');
const volumeSymbols = volumeButton.querySelectorAll('.v0ck use');
const volumeSymbols = volumeButton.querySelectorAll('use');
const defaultVolume = 0.5;
let mousedown = false;
let _volume;
// Hold to speedup (2x) states
let speedUpTimeout;
let isSpeedingUp = false;
let restorePlaybackRate = 1;
let ignoreNextClick = false;
let wasPausedWhenStarted = false;
// Mobile tap-to-show-controls: true when this touch revealed the controls bar
let controlsJustShown = false;
const speedIndicator = player.querySelector('.v0ck_speed_indicator');
// (mouse position is now tracked via docMouseX/docMouseY in resetControlsTimer block)
function handleVolumeButton(vol) {
[...volumeSymbols].forEach(s => !s.classList.contains('v0ck_hidden') ? s.classList.add('v0ck_hidden') : null);
switch (true) {
case (vol === 0): [...volumeSymbols].filter(s => s.id === "v0ck_svg_volume_mute")[0].classList.toggle('v0ck_hidden'); break;
case (vol <= 0.5 && vol > 0): [...volumeSymbols].filter(s => s.id === "v0ck_svg_volume_mid")[0].classList.toggle('v0ck_hidden'); break;
case (vol > 0.5): [...volumeSymbols].filter(s => s.id === "v0ck_svg_volume_full")[0].classList.toggle('v0ck_hidden'); break;
[...volumeSymbols].forEach(s => s.classList.add('v0ck_hidden'));
let targetId = 'v0ck_svg_volume_full';
if (vol === 0) {
targetId = 'v0ck_svg_volume_mute';
} else if (vol <= 0.5) {
targetId = 'v0ck_svg_volume_mid';
}
const activeSymbol = [...volumeSymbols].find(s => s.id === targetId);
if (activeSymbol) {
activeSymbol.classList.remove('v0ck_hidden');
}
localStorage.setItem("volume", vol);
}
@@ -262,14 +286,31 @@ class v0ck {
player.classList.toggle('v0ck_fullscreen', !!isThisPlayerFS);
}
// Mobile: on touchstart, record whether controls were hidden so the
// subsequent click can decide whether to show controls or toggle play.
player.addEventListener('touchstart', () => {
if (isMobile) {
controlsJustShown = !player.classList.contains('v0ck_hover');
}
}, { passive: true, capture: true });
player.addEventListener('click', e => {
if (ignoreNextClick) {
e.stopPropagation();
e.preventDefault();
ignoreNextClick = false;
return;
}
const path = e.path || (e.composedPath && e.composedPath());
const isControls = !!path.filter(f => f.classList?.contains('v0ck_player_controls')).length;
if (!isControls) {
if (isMobile && !player.classList.contains('v0ck_hover')) {
if (isMobile && controlsJustShown) {
// First tap: controls were just revealed by this touch — don't toggle play
controlsJustShown = false;
player.classList.add('v0ck_hover');
return;
}
controlsJustShown = false;
togglePlay(e);
}
});
@@ -301,9 +342,18 @@ class v0ck {
}
});
// Loader events
const showLoader = () => loader.classList.remove('v0ck_hidden');
const hideLoader = () => loader.classList.add('v0ck_hidden');
// Loader events with debounce to prevent flicker on fast starts/seeking
let loaderTimeout = null;
const showLoader = () => {
if (loaderTimeout) clearTimeout(loaderTimeout);
loaderTimeout = setTimeout(() => {
loader.classList.remove('v0ck_hidden');
}, 250);
};
const hideLoader = () => {
if (loaderTimeout) clearTimeout(loaderTimeout);
loader.classList.add('v0ck_hidden');
};
video.addEventListener('waiting', showLoader);
video.addEventListener('stalled', showLoader);
video.addEventListener('canplay', hideLoader);
@@ -325,11 +375,21 @@ class v0ck {
hud.classList.remove('v0ck_hidden');
hudBar.style.width = `${vol * 100}%`;
// Update HUD icon based on volume
let icon = 'volume_full';
if (vol === 0) icon = 'volume_mute';
else if (vol <= 0.5) icon = 'volume_mid';
hudIcon.setAttribute('href', `${hudIcon.getAttribute('href').split('#')[0]}#${icon}`);
// Update HUD icon based on volume by toggling hidden class
const hudSymbols = hud.querySelectorAll('.v0ck_hud_icon');
hudSymbols.forEach(s => s.classList.add('v0ck_hidden'));
let targetClass = 'v0ck_hud_volume_full';
if (vol === 0) {
targetClass = 'v0ck_hud_volume_mute';
} else if (vol <= 0.5) {
targetClass = 'v0ck_hud_volume_mid';
}
const activeSymbol = [...hudSymbols].find(s => s.classList.contains(targetClass));
if (activeSymbol) {
activeSymbol.classList.remove('v0ck_hidden');
}
clearTimeout(hudTimer);
hudTimer = setTimeout(() => hud.classList.add('v0ck_hidden'), 1000);
@@ -348,7 +408,7 @@ class v0ck {
startY = touch.clientY;
startVol = video.volume;
}
}, { passive: true });
}, { passive: false });
player.addEventListener('touchmove', e => {
if (!isMobile || !isRightSide || gestureType === 'other') return;
@@ -361,6 +421,8 @@ class v0ck {
if (gestureType === 'none') {
if (dy > dx && dy > 5) {
gestureType = 'volume';
clearTimeout(speedUpTimeout);
endSpeedUp();
} else if (dx > dy && dx > 5) {
gestureType = 'other'; // Probably seeking or horizontal swipe
return;
@@ -370,6 +432,9 @@ class v0ck {
}
if (gestureType === 'volume') {
clearTimeout(speedUpTimeout);
endSpeedUp();
const deltaY = startY - touch.clientY; // swipe up is positive
const sensitivity = 200; // pixels for 0 to 1 range (reverted to original)
let newVol = startVol + (deltaY / sensitivity);
@@ -384,9 +449,86 @@ class v0ck {
if (e.cancelable) e.preventDefault();
}
}, { passive: false });
// Desktop mouse volume gesture support (clicking and dragging vertically on the player)
let activeMouseGesture = false;
player.addEventListener('mousedown', e => {
if (isMobile) return;
if (e.button !== 0) return;
const path = e.path || (e.composedPath && e.composedPath());
const isControls = !!path.filter(f => f.classList?.contains('v0ck_player_controls')).length;
if (isControls) return;
gestureType = 'none';
startX = e.clientX;
startY = e.clientY;
startVol = video.volume;
activeMouseGesture = true;
});
window.addEventListener('mousemove', e => {
if (!activeMouseGesture || gestureType === 'other') return;
const dx = Math.abs(e.clientX - startX);
const dy = Math.abs(e.clientY - startY);
if (gestureType === 'none') {
if (dy > dx && dy > 5) {
gestureType = 'volume';
clearTimeout(speedUpTimeout);
endSpeedUp();
} else if (dx > dy && dx > 5) {
gestureType = 'other';
return;
} else {
return;
}
}
if (gestureType === 'volume') {
clearTimeout(speedUpTimeout);
endSpeedUp();
ignoreNextClick = true;
const deltaY = startY - e.clientY; // swipe up is positive
const sensitivity = 200;
let newVol = startVol + (deltaY / sensitivity);
newVol = Math.max(0, Math.min(1, newVol));
video.volume = newVol;
volumeSlider.value = newVol;
_volume = newVol;
handleVolumeButton(newVol);
showHUD(newVol);
e.preventDefault();
}
});
window.addEventListener('mouseup', () => {
if (activeMouseGesture) {
activeMouseGesture = false;
setTimeout(() => {
ignoreNextClick = false;
}, 100);
}
});
skipButtons.forEach(button => button.addEventListener('click', skip));
ranges.forEach(range => range.addEventListener('change', handleRangeUpdate));
ranges.forEach(range => range.addEventListener('input', handleRangeUpdate));
ranges.forEach(range => range.addEventListener('mousemove', handleRangeUpdate));
// Prevent touch events on the volume slider from bubbling to the player container (avoiding gesture conflicts and page scrolls)
if (volumeSlider) {
['touchstart', 'touchmove', 'touchend', 'touchcancel'].forEach(evt => {
volumeSlider.addEventListener(evt, e => {
e.stopPropagation();
}, { passive: false });
});
}
progress.addEventListener('mousedown', scrub);
progress.addEventListener('touchstart', scrub, { passive: false });
progress.addEventListener('touchmove', scrub, { passive: false });
@@ -394,11 +536,197 @@ class v0ck {
document.addEventListener('fullscreenchange', toggleFullScreenClasses);
toggleFullScreenClasses(); // Check initial state (important for transitions)
let keyHoldTimer = null;
let isHoldingKey = false;
let heldKey = null;
let reverseInterval = null;
function handleKeyDown(e) {
if (!document.body.contains(video)) {
cleanupKeyboardListeners();
return;
}
// Block interaction if content warning is visible
const cwModal = document.getElementById('content-warning-modal');
if (cwModal && cwModal.style.display !== 'none') return;
// Don't fire if user is typing in an input, textarea or editing content
if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA" || e.target.isContentEditable) return;
if (e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
let newVol = video.volume;
if (e.key === "ArrowUp") {
newVol = Math.min(1, newVol + 0.05);
} else {
newVol = Math.max(0, newVol - 0.05);
}
video.volume = newVol;
if (volumeSlider) {
volumeSlider.value = newVol;
}
_volume = newVol;
handleVolumeButton(newVol);
showHUD(newVol);
}
if (e.key === "." || e.key === ",") {
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
if (!Number.isFinite(video.currentTime)) return;
const duration = Number.isFinite(video.duration) ? video.duration : video.currentTime;
const direction = e.key === "." ? 1 : -1;
if (heldKey && heldKey !== e.key) return;
const isCurrentHold = heldKey === e.key;
if (video.paused || isCurrentHold) {
if (!e.repeat) {
heldKey = e.key;
isHoldingKey = false;
if (keyHoldTimer) clearTimeout(keyHoldTimer);
keyHoldTimer = setTimeout(() => {
isHoldingKey = true;
if (heldKey === ".") {
video.play();
} else if (heldKey === ",") {
if (reverseInterval) clearInterval(reverseInterval);
reverseInterval = setInterval(() => {
if (video.currentTime > 0) {
video.currentTime = Math.max(0, video.currentTime - 0.04);
} else {
clearInterval(reverseInterval);
reverseInterval = null;
}
}, 40);
}
}, 200);
} else {
if (keyHoldTimer && !isHoldingKey) {
clearTimeout(keyHoldTimer);
keyHoldTimer = null;
isHoldingKey = true;
if (heldKey === ".") {
video.play();
} else if (heldKey === ",") {
if (reverseInterval) clearInterval(reverseInterval);
reverseInterval = setInterval(() => {
if (video.currentTime > 0) {
video.currentTime = Math.max(0, video.currentTime - 0.04);
} else {
clearInterval(reverseInterval);
reverseInterval = null;
}
}, 40);
}
}
}
} else {
video.currentTime = Math.max(0, Math.min(duration, video.currentTime + direction * 5));
}
showControlsAndReset();
}
}
function handleKeyUp(e) {
if (!document.body.contains(video)) {
cleanupKeyboardListeners();
return;
}
if (e.key === "." || e.key === ",") {
if (heldKey === e.key) {
if (keyHoldTimer) {
clearTimeout(keyHoldTimer);
keyHoldTimer = null;
}
if (isHoldingKey) {
if (heldKey === ".") {
video.pause();
} else if (heldKey === ",") {
if (reverseInterval) {
clearInterval(reverseInterval);
reverseInterval = null;
}
}
} else {
if (Number.isFinite(video.currentTime)) {
const duration = Number.isFinite(video.duration) ? video.duration : video.currentTime;
const direction = heldKey === "." ? 1 : -1;
const frameTime = 1 / 30;
video.currentTime = Math.max(0, Math.min(duration, video.currentTime + direction * frameTime));
}
}
heldKey = null;
isHoldingKey = false;
showControlsAndReset();
}
}
}
function handleBlur() {
if (!document.body.contains(video)) {
cleanupKeyboardListeners();
return;
}
if (keyHoldTimer) clearTimeout(keyHoldTimer);
if (reverseInterval) clearInterval(reverseInterval);
keyHoldTimer = null;
reverseInterval = null;
if (isHoldingKey) {
if (heldKey === ".") {
video.pause();
}
}
heldKey = null;
isHoldingKey = false;
}
function cleanupKeyboardListeners() {
document.removeEventListener('keydown', handleKeyDown);
document.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('blur', handleBlur);
if (keyHoldTimer) clearTimeout(keyHoldTimer);
if (reverseInterval) clearInterval(reverseInterval);
}
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
window.addEventListener('blur', handleBlur);
video.volume = _volume = volumeSlider.value = +(localStorage.getItem('volume') ?? defaultVolume);
handleVolumeButton(video.volume);
const mediaObj = player.closest('.media-object');
let isBlurredDetail = false;
if (mediaObj && localStorage.getItem('blurDetail') !== 'false') {
const mode = mediaObj.getAttribute('data-mode');
const blurNsfw = localStorage.getItem('blurNsfw') === 'true';
const blurNsfl = localStorage.getItem('blurNsfl') === 'true';
const blurSfw = localStorage.getItem('blurSfw') === 'true';
const blurUntagged = localStorage.getItem('blurUntagged') === 'true';
let shouldBlurThis = false;
if (mode === 'nsfw') shouldBlurThis = blurNsfw;
else if (mode === 'nsfl') shouldBlurThis = blurNsfl;
else if (mode === 'sfw') shouldBlurThis = blurSfw;
else if (mode === 'untagged') shouldBlurThis = blurUntagged;
if (shouldBlurThis && !mediaObj.classList.contains('revealed')) {
isBlurredDetail = true;
}
}
// Upgrade preload from 'metadata' → 'auto' for video elements so the browser
// starts buffering data immediately during player setup. With just 'metadata',
// play() triggers a brand-new range request and the user sees the loader spinner
// until enough data arrives. 'auto' closes that gap for both autoplay and manual play.
if (video.tagName === 'VIDEO' && video.preload !== 'auto') {
video.preload = 'auto';
}
// Attempt autoplay and show overlay if blocked
const shouldAutoplay = window.f0ckSession?.disable_autoplay !== true;
const shouldAutoplay = !isBlurredDetail && window.f0ckSession?.disable_autoplay !== true;
if (shouldAutoplay) {
const playPromise = togglePlay();
if (playPromise !== undefined) {
@@ -541,6 +869,162 @@ class v0ck {
else toggleDanmakuSwitch.addEventListener('click', handleDanmakuToggle);
}
}
// Controls auto-hide logic (auto hide controls after 2.5 seconds of inactivity)
let controlsTimer;
// True while the cursor is physically inside .v0ck_player_controls
let mouseIsOverControls = false;
// Track real mouse position at document level — completely independent of
// any element animation or synthetic events.
let docMouseX = -1;
let docMouseY = -1;
const onDocMouseMove = (e) => {
docMouseX = e.clientX;
docMouseY = e.clientY;
};
document.addEventListener('mousemove', onDocMouseMove, { passive: true });
function resetControlsTimer() {
clearTimeout(controlsTimer);
// Never schedule auto-hide while the user is mousing over the controls bar
if (mouseIsOverControls) return;
const isFullscreen = player.classList.contains('v0ck_fullscreen');
if (!video.paused || isFullscreen) {
controlsTimer = setTimeout(() => {
player.classList.remove('v0ck_hover');
if (settingsMenu && !settingsMenu.classList.contains('v0ck_hidden')) {
settingsMenu.classList.add('v0ck_hidden');
document.dispatchEvent(new CustomEvent('v0ck_settings_closed'));
}
}, 2500);
}
}
function showControlsAndReset(e) {
// Ignore synthetic pointer events fired by the browser during CSS animations
// (element shifts under stationary cursor). We compare against docMouseX/Y
// which is only ever updated by genuine user mouse movement.
if (e && e.clientX !== undefined && e.clientY !== undefined) {
if (e.clientX === docMouseX && e.clientY === docMouseY &&
player.classList.contains('v0ck_hover')) {
// Coordinates unchanged and controls already visible — synthetic event, skip.
return;
}
docMouseX = e.clientX;
docMouseY = e.clientY;
}
player.classList.add('v0ck_hover');
resetControlsTimer();
}
// Events that should show controls and reset/extend the auto-hide timer
const resetEvents = ['touchstart', 'touchmove', 'touchend', 'click', 'mousemove', 'mouseenter'];
resetEvents.forEach(evt => {
player.addEventListener(evt, showControlsAndReset, { capture: true, passive: true });
});
// While hovering the controls bar: freeze the auto-hide timer completely.
const controlsBar = player.querySelector('.v0ck_player_controls');
if (controlsBar) {
controlsBar.addEventListener('mouseenter', () => {
mouseIsOverControls = true;
clearTimeout(controlsTimer); // cancel any countdown already in progress
}, { passive: true });
controlsBar.addEventListener('mouseleave', (e) => {
mouseIsOverControls = false;
// Only restart the timer if the cursor re-entered the player area
// (not when it left the player entirely — the player mouseleave handles that)
const r = player.getBoundingClientRect();
const stillInPlayer = e.clientX >= r.left && e.clientX <= r.right &&
e.clientY >= r.top && e.clientY <= r.bottom;
if (stillInPlayer) resetControlsTimer();
}, { passive: true });
}
// Hide when cursor leaves the player entirely.
// NO capture:true — that would incorrectly intercept mouseleave events from
// child elements (e.g. the progress bar animating away from the cursor).
// Without capture, this only fires when the mouse truly leaves .v0ck itself.
player.addEventListener('mouseleave', (e) => {
const r = player.getBoundingClientRect();
// Grace zone: the controls bar peeks ~3px below the player when hidden.
// If the cursor is still in that strip, don't hide.
if (e.clientX >= r.left && e.clientX <= r.right &&
e.clientY > r.bottom && e.clientY <= r.bottom + 8) {
return;
}
// If the cursor moved into the controls bar itself (or any child of it),
// keep the controls visible — the user is interacting with them.
const controls = player.querySelector('.v0ck_player_controls');
if (controls && e.relatedTarget && controls.contains(e.relatedTarget)) {
return;
}
docMouseX = -1;
docMouseY = -1;
player.classList.remove('v0ck_hover');
clearTimeout(controlsTimer);
});
video.addEventListener('play', resetControlsTimer);
video.addEventListener('playing', resetControlsTimer);
video.addEventListener('pause', () => clearTimeout(controlsTimer));
// Speedup 2x on Hold logic
function startSpeedUp(e) {
if (e.type === 'mousedown' && isMobile) return;
// Only left mouse click or touch triggers speedup
if (e.type === 'mousedown' && e.button !== 0) return;
// Don't speed up if clicking on controls or settings panel
const path = e.path || (e.composedPath && e.composedPath());
const isControls = !!path.filter(f => f.classList?.contains('v0ck_player_controls')).length;
if (isControls) return;
clearTimeout(speedUpTimeout);
speedUpTimeout = setTimeout(() => {
isSpeedingUp = true;
ignoreNextClick = true;
wasPausedWhenStarted = video.paused;
restorePlaybackRate = video.playbackRate;
video.playbackRate = 2.0;
if (wasPausedWhenStarted) {
video.play();
}
if (speedIndicator) {
speedIndicator.classList.remove('v0ck_hidden');
}
}, 500);
}
function endSpeedUp(e) {
clearTimeout(speedUpTimeout);
if (isSpeedingUp) {
isSpeedingUp = false;
video.playbackRate = restorePlaybackRate;
if (wasPausedWhenStarted) {
video.pause();
wasPausedWhenStarted = false;
}
if (speedIndicator) {
speedIndicator.classList.add('v0ck_hidden');
}
// Brief timeout before allowing normal clicking again to bypass the immediate click event
setTimeout(() => {
ignoreNextClick = false;
}, 100);
}
}
player.addEventListener('mousedown', startSpeedUp);
player.addEventListener('touchstart', startSpeedUp, { passive: true });
player.addEventListener('mouseup', endSpeedUp);
player.addEventListener('mouseleave', endSpeedUp);
player.addEventListener('touchend', endSpeedUp);
player.addEventListener('touchcancel', endSpeedUp);
this.toggleFullScreen = toggleFullScreen;
this.enterFullScreen = enterFullScreen;

View File

@@ -0,0 +1,162 @@
/**
* Backfill script: populate width/height for existing image and video items.
*
* Usage:
* node scripts/backfill_dimensions.mjs
* node scripts/backfill_dimensions.mjs --dry-run (print without writing)
* node scripts/backfill_dimensions.mjs --limit 500 (process first N items)
*
* Skips: audio, flash, PDF, YouTube items (width/height left as NULL).
* Skips: items where the physical file is missing.
* Safe to run multiple times — only processes rows where width IS NULL.
*/
import { spawn as _spawn } from 'child_process';
import db from '../src/inc/sql.mjs';
import cfg from '../src/inc/config.mjs';
import path from 'path';
import fs from 'fs/promises';
const isDryRun = process.argv.includes('--dry-run');
const limitArg = process.argv.indexOf('--limit');
const limit = limitArg !== -1 ? parseInt(process.argv[limitArg + 1], 10) : null;
const BATCH = 50;
// ---- tiny spawn helper (no shell) ----
const spawn = (cmd, args, opts = {}) =>
new Promise((resolve, reject) => {
const child = _spawn(cmd, args, opts);
let out = '';
let err = '';
child.stdout?.on('data', d => { out += d; });
child.stderr?.on('data', d => { err += d; });
child.on('close', code => {
if (code !== 0 && !opts.ignoreExitCode) {
const e = new Error(`${cmd} exited ${code}`);
e.stderr = err;
return reject(e);
}
resolve(out);
});
child.on('error', reject);
});
// ---- probe helpers ----
async function getDimsImage(filePath) {
try {
// magick identify -format "%wx%h" reports raw pixel dimensions
const out = await spawn('magick', ['identify', '-format', '%wx%h\n', filePath + '[0]'], { ignoreExitCode: true });
// Take the first line (multi-frame GIF etc. may have many)
const line = out.trim().split('\n')[0];
const match = line.match(/^(\d+)x(\d+)$/);
if (match) return { w: parseInt(match[1], 10), h: parseInt(match[2], 10) };
} catch (_) {}
return null;
}
async function getDimsVideo(filePath) {
try {
const out = await spawn('ffprobe', [
'-v', 'error', '-select_streams', 'v:0',
'-show_entries', 'stream=width,height',
'-of', 'csv=p=0', filePath
], { ignoreExitCode: true });
const parts = out.trim().split(',');
if (parts.length < 2) return null;
const w = parseInt(parts[0], 10);
const h = parseInt(parts[1], 10);
if (w > 0 && h > 0) return { w, h };
} catch (_) {}
return null;
}
// ---- main ----
async function run() {
console.log(`[BACKFILL] Starting dimension backfill${isDryRun ? ' (DRY RUN)' : ''}${limit ? ` (limit: ${limit})` : ''}`);
// Count pending
const [{ count }] = await db`
SELECT count(*) FROM items
WHERE width IS NULL
AND (mime LIKE 'image/%' OR (mime LIKE 'video/%' AND mime != 'video/youtube'))
`;
const total = parseInt(count, 10);
const toProcess = limit ? Math.min(total, limit) : total;
console.log(`[BACKFILL] ${total} items need backfill${limit ? `, processing up to ${toProcess}` : ''}`);
let processed = 0;
let updated = 0;
let skipped = 0;
let failed = 0;
// NOTE: Always query at OFFSET 0 — updated rows leave the WHERE width IS NULL set,
// so the result set shrinks naturally each batch. Using a moving OFFSET would skip
// as many rows as were just updated (pagination-with-mutation bug).
while (processed < toProcess) {
const batchSize = limit ? Math.min(BATCH, toProcess - processed) : BATCH;
const rows = await db`
SELECT id, dest, mime FROM items
WHERE width IS NULL
AND (mime LIKE 'image/%' OR (mime LIKE 'video/%' AND mime != 'video/youtube'))
ORDER BY id DESC
LIMIT ${batchSize}
`;
if (rows.length === 0) break;
for (const row of rows) {
if (processed >= toProcess) break;
processed++;
const filePath = path.join(cfg.paths.b, row.dest);
// Check file exists (may be deleted/purged)
try {
await fs.access(filePath);
} catch {
console.log(`[BACKFILL] SKIP #${row.id} — file missing: ${row.dest}`);
skipped++;
// Mark with 0 so it doesn't re-appear in future runs
if (!isDryRun) await db`UPDATE items SET width = 0, height = 0 WHERE id = ${row.id}`;
continue;
}
let dims = null;
try {
if (row.mime.startsWith('image/')) {
dims = await getDimsImage(filePath);
} else if (row.mime.startsWith('video/')) {
dims = await getDimsVideo(filePath);
}
} catch (e) {
console.warn(`[BACKFILL] PROBE ERROR #${row.id}: ${e.message}`);
failed++;
continue;
}
if (!dims) {
console.log(`[BACKFILL] SKIP #${row.id} — no dimensions found (${row.mime})`);
skipped++;
// Mark with 0 so it doesn't re-appear in future runs and cause infinite loops
if (!isDryRun) await db`UPDATE items SET width = 0, height = 0 WHERE id = ${row.id}`;
continue;
}
console.log(`[BACKFILL] ${isDryRun ? '[DRY]' : 'UPDATE'} #${row.id}${dims.w}×${dims.h}`);
if (!isDryRun) {
await db`UPDATE items SET width = ${dims.w}, height = ${dims.h} WHERE id = ${row.id}`;
}
updated++;
}
console.log(`[BACKFILL] Progress: ${processed} / ${toProcess} (updated=${updated}, skipped=${skipped}, failed=${failed})`);
}
console.log(`[BACKFILL] Done. updated=${updated}, skipped=${skipped}, failed=${failed}`);
process.exit(0);
}
run().catch(err => {
console.error('[BACKFILL] Fatal error:', err);
process.exit(1);
});

View File

@@ -0,0 +1,248 @@
import db from '../src/inc/sql.mjs';
import cfg from '../src/inc/config.mjs';
import path from 'path';
import fs from 'fs/promises';
import crypto from 'crypto';
const isDryRun = process.argv.includes('--dry-run');
const limitArg = process.argv.indexOf('--limit');
const limit = limitArg !== -1 ? parseInt(process.argv[limitArg + 1], 10) : null;
const BATCH_SIZE = 1000;
async function run() {
console.log(`[BACKFILL] Starting long UUID migration & backfill script${isDryRun ? ' (DRY RUN)' : ''}${limit ? ` (Limit: ${limit})` : ''}`);
if (!isDryRun) {
console.log('[MIGRATION] Applying database schema migrations...');
// Drop views first because they depend on columns we want to alter
await db`DROP VIEW IF EXISTS public.items_sfw CASCADE`;
await db`DROP VIEW IF EXISTS public.items_li CASCADE`;
// Alter dest columns in items and comment_files
await db`ALTER TABLE public.items ALTER COLUMN dest TYPE character varying(255)`;
await db`ALTER TABLE public.comment_files ALTER COLUMN dest TYPE character varying(255)`;
// Recreate public.items_li view
await db`
CREATE OR REPLACE VIEW public.items_li AS
SELECT items.id,
items.src,
items.dest,
items.mime,
items.size,
items.checksum,
items.username,
items.userchannel,
items.usernetwork,
items.stamp
FROM ((public.items
JOIN public.tags_assign ta1 ON (((ta1.tag_id = 1) AND (ta1.item_id = items.id))))
JOIN public.tags_assign ta2 ON (((NOT (ta2.tag_id IN ( SELECT tags_nsfp.id
FROM public.tags_nsfp))) AND (ta2.item_id = items.id))))
WHERE items.active
GROUP BY items.id;
`;
// Recreate public.items_sfw view
await db`
CREATE OR REPLACE VIEW public.items_sfw AS
SELECT ( SELECT
CASE
WHEN (tags_assign.tag_id > 0) THEN tags_assign.tag_id
ELSE 0
END AS "case"
FROM public.tags_assign
WHERE ((tags_assign.tag_id = ANY (ARRAY[1, 2])) AND (tags_assign.item_id = items.id))) AS sfw,
( SELECT
CASE
WHEN (tags_assign.tag_id > 0) THEN 1
ELSE 0
END AS "case"
FROM public.tags_assign
WHERE ((tags_assign.tag_id IN ( SELECT tags_nsfp.id
FROM public.tags_nsfp)) AND (tags_assign.item_id = items.id))
LIMIT 1) AS nsfp,
id,
src,
dest,
mime,
size,
checksum,
username,
userchannel,
usernetwork,
stamp,
active
FROM public.items;
`;
console.log('[MIGRATION] Schema changes applied and views successfully recreated.');
}
// Map to keep track of all renamed files: old_filename -> new_filename
const renameMap = new Map();
// 1. Process items
console.log('[BACKFILL] Fetching items to process...');
const items = await db`SELECT id, dest, mime FROM items`;
console.log(`[BACKFILL] Found ${items.length} items in DB.`);
let itemsProcessed = 0;
let itemsRenamedCount = 0;
for (const item of items) {
if (limit && itemsProcessed >= limit) break;
itemsProcessed++;
// YouTube embeds store dest as "yt:VIDEO_ID" — not a real file, skip entirely
if (item.mime === 'video/youtube') {
continue;
}
const ext = path.extname(item.dest);
const base = path.basename(item.dest, ext);
// If name is already 48 characters long, skip
if (base.length === 48) {
continue;
}
const newUuid = crypto.randomBytes(24).toString('hex');
const newDest = `${newUuid}${ext}`;
renameMap.set(item.dest, newDest);
// Physical files could be in active, pending or deleted folders
const pathsToCheck = [
path.join(cfg.paths.b, item.dest),
path.join(cfg.paths.pending, 'b', item.dest),
path.join(cfg.paths.deleted, 'b', item.dest)
];
let foundPath = null;
for (const p of pathsToCheck) {
try {
const stat = await fs.lstat(p);
if (!stat.isSymbolicLink()) {
foundPath = p;
break;
}
} catch (e) {}
}
if (foundPath) {
const newPath = path.join(path.dirname(foundPath), newDest);
console.log(`[BACKFILL] Renaming item file: ${foundPath} -> ${newPath}`);
if (!isDryRun) {
await fs.rename(foundPath, newPath);
}
} else {
console.log(`[BACKFILL] [WARNING] Item physical file not found/is symlink for: ${item.dest}`);
}
if (!isDryRun) {
await db`UPDATE items SET dest = ${newDest} WHERE id = ${item.id}`;
}
itemsRenamedCount++;
if (itemsRenamedCount % BATCH_SIZE === 0) {
console.log(`[BACKFILL] Processed ${itemsRenamedCount} item renames...`);
}
}
// 2. Process comment_files
console.log('[BACKFILL] Fetching comment files to process...');
const commentFiles = await db`SELECT id, dest FROM comment_files`;
console.log(`[BACKFILL] Found ${commentFiles.length} comment files in DB.`);
let commentsProcessed = 0;
let commentsRenamedCount = 0;
for (const cf of commentFiles) {
if (limit && commentsProcessed >= limit) break;
commentsProcessed++;
const ext = path.extname(cf.dest);
const base = path.basename(cf.dest, ext);
if (base.length === 48) {
continue;
}
const newUuid = crypto.randomBytes(24).toString('hex');
const newDest = `${newUuid}${ext}`;
renameMap.set(cf.dest, newDest);
const oldPath = path.join(cfg.paths.c, cf.dest);
const newPath = path.join(cfg.paths.c, newDest);
try {
const stat = await fs.lstat(oldPath);
if (!stat.isSymbolicLink()) {
console.log(`[BACKFILL] Renaming comment file: ${oldPath} -> ${newPath}`);
if (!isDryRun) {
await fs.rename(oldPath, newPath);
}
}
} catch (e) {}
// Rename corresponding thumbnail in t/ (cf_${old_uuid}.webp -> cf_${new_uuid}.webp)
const oldThumbPath = path.join(cfg.paths.t, `cf_${base}.webp`);
const newThumbPath = path.join(cfg.paths.t, `cf_${newUuid}.webp`);
try {
await fs.access(oldThumbPath);
console.log(`[BACKFILL] Renaming comment thumbnail: ${oldThumbPath} -> ${newThumbPath}`);
if (!isDryRun) {
await fs.rename(oldThumbPath, newThumbPath);
}
} catch (e) {}
if (!isDryRun) {
await db`UPDATE comment_files SET dest = ${newDest} WHERE id = ${cf.id}`;
}
commentsRenamedCount++;
if (commentsRenamedCount % BATCH_SIZE === 0) {
console.log(`[BACKFILL] Processed ${commentsRenamedCount} comment file renames...`);
}
}
// 3. Update Symlinks in c/
console.log('[BACKFILL] Scanning /c/ directory for symlinks to update...');
try {
const filesInC = await fs.readdir(cfg.paths.c);
for (const f of filesInC) {
const filePath = path.join(cfg.paths.c, f);
try {
const stat = await fs.lstat(filePath);
if (stat.isSymbolicLink()) {
const target = await fs.readlink(filePath);
const targetBasename = path.basename(target);
if (renameMap.has(targetBasename)) {
const newTargetBasename = renameMap.get(targetBasename);
// Re-construct the symlink target path, pointing to public/b or public/c
const resolvedTargetAbs = path.resolve(path.dirname(filePath), target);
const resolvedTargetNewAbs = path.join(path.dirname(resolvedTargetAbs), newTargetBasename);
const relativeNewTarget = path.relative(path.dirname(filePath), resolvedTargetNewAbs);
console.log(`[BACKFILL] Updating symlink: ${filePath} -> ${relativeNewTarget}`);
if (!isDryRun) {
await fs.unlink(filePath);
await fs.symlink(relativeNewTarget, filePath);
}
}
}
} catch (e) {
console.error(`[BACKFILL] [ERROR] Failed processing file/symlink ${filePath}:`, e.message);
}
}
} catch (e) {
console.error('[BACKFILL] Error reading /c/ directory:', e.message);
}
console.log(`[BACKFILL] Completed. Items renamed: ${itemsRenamedCount}. Comment files renamed: ${commentsRenamedCount}.`);
process.exit(0);
}
run().catch(err => {
console.error('[BACKFILL] Fatal error:', err);
process.exit(1);
});

View File

@@ -2,7 +2,7 @@ import fs from 'fs';
import path from 'path';
const cssDir = path.join(process.cwd(), 'public/s/css');
const files = ['f0ckm.css', 'v0ck.css'];
const files = ['f0ckm.css', 'v0ck.css', '98.css'];
const outputFile = path.join(cssDir, 'bundle.css');
let combined = '';

View File

@@ -1,7 +1,6 @@
import db from "../src/inc/sql.mjs";
import lib from "../src/inc/lib.mjs";
import cfg from "../src/inc/config.mjs";
import { getDefaultLayout } from "../src/inc/settings.mjs";
const [username, password] = process.argv.slice(2);
@@ -48,7 +47,7 @@ async function createAdmin() {
await db`
insert into user_options (user_id, mode, theme, fullscreen, avatar, avatar_file, use_new_layout, disable_autoplay, disable_swiping)
values (${userId}, 3, 'amoled', 0, null, 'default.png', ${getDefaultLayout() === 'modern'}, false, false)
values (${userId}, 3, 'amoled', 0, null, 'default.png', ${(cfg.websrv.default_layout ?? 'modern') !== 'legacy'}, false, false)
`;
console.log(`--- Admin User ${username} Created Successfully ---`);

View File

@@ -0,0 +1,83 @@
/**
* fix_youtube_dest.mjs
*
* One-time fix: the backfill_uuid_filenames.mjs script failed to exclude
* YouTube items, which store dest as "yt:VIDEO_ID" rather than a real file.
* As a result, those dest values were replaced with random UUIDs, breaking
* embed URLs like youtube.com/embed/<uuid>.
*
* This script:
* 1. Finds all items with mime = 'video/youtube'
* 2. For each, re-extracts the video ID from the src column
* (src holds the original YouTube watch URL: https://www.youtube.com/watch?v=VIDEO_ID)
* 3. Restores dest to "yt:VIDEO_ID"
*
* Usage:
* node scripts/fix_youtube_dest.mjs # live run
* node scripts/fix_youtube_dest.mjs --dry-run # preview only, no DB changes
*/
import db from '../src/inc/sql.mjs';
const isDryRun = process.argv.includes('--dry-run');
const ytRegex = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\/?\/?\?(?:\S*?&?v=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/i;
async function run() {
console.log(`[FIX-YT-DEST] Starting${isDryRun ? ' (DRY RUN)' : ''}...`);
const rows = await db`
SELECT id, dest, src
FROM items
WHERE mime = 'video/youtube'
ORDER BY id
`;
console.log(`[FIX-YT-DEST] Found ${rows.length} YouTube item(s) to check.`);
let fixed = 0;
let skipped = 0;
let failed = 0;
for (const row of rows) {
// Already correct format
if (row.dest && row.dest.startsWith('yt:')) {
skipped++;
continue;
}
// Try to extract video ID from src URL
const match = row.src && row.src.match(ytRegex);
if (!match) {
console.warn(`[FIX-YT-DEST] [WARN] Item ${row.id}: cannot extract video ID from src="${row.src}", dest="${row.dest}" — skipping`);
failed++;
continue;
}
const videoId = match[1];
const newDest = `yt:${videoId}`;
console.log(`[FIX-YT-DEST] Item ${row.id}: "${row.dest}" → "${newDest}" (src: ${row.src})`);
if (!isDryRun) {
await db`UPDATE items SET dest = ${newDest} WHERE id = ${row.id}`;
}
fixed++;
}
console.log(`\n[FIX-YT-DEST] Done.`);
console.log(` Fixed: ${fixed}`);
console.log(` Skipped: ${skipped} (already correct)`);
console.log(` Failed: ${failed} (no video ID recoverable from src)`);
if (isDryRun) {
console.log('\n[FIX-YT-DEST] DRY RUN — no changes were written to the database.');
}
process.exit(0);
}
run().catch(err => {
console.error('[FIX-YT-DEST] Fatal error:', err);
process.exit(1);
});

View File

@@ -8,6 +8,10 @@
* node regen.mjs --all - Regenerate ALL items
* node regen.mjs --audio - Regenerate all audio items
* node regen.mjs --pdf - Regenerate all PDF items
* node regen.mjs --blur - Regenerate ONLY the blurred thumbnails for all items
*
* Flash (SWF) items are always excluded — their thumbnails are set via the
* Ruffle snapshot mechanism and must never be touched by this script.
*/
import db from "../src/inc/sql.mjs";
@@ -26,14 +30,40 @@ if (args.length === 0) {
console.log(' node regen.mjs --audio - Regenerate all audio items');
console.log(' node regen.mjs --pdf - Regenerate all PDF items');
console.log(' node regen.mjs --youtube - Regenerate all YouTube thumbnails');
console.log(' node regen.mjs --blur - Regenerate ONLY the blurred thumbnails for all items');
process.exit(0);
}
// Flash mime types — never regenerate these
const FLASH_MIMES = [
'application/x-shockwave-flash',
'application/vnd.adobe.flash.movie',
];
const isFlash = (mime) => FLASH_MIMES.includes(mime?.toLowerCase());
const THUMB_SIZE = 512;
const blurOnly = args.includes('--blur');
console.log(`[regen] Thumb size: ${THUMB_SIZE}px\n`);
const regen = async (item) => {
const { id, dest, mime, src } = item;
if (isFlash(mime)) {
console.log(`[${id}] Skipped (Flash/SWF — thumbnail managed by Ruffle snapshot)`);
return;
}
if (blurOnly) {
console.log(`[${id}] Regenerating blurred thumbnail only: ${dest}`);
try {
await queue.genBlurredThumbnail(id, false);
console.log(`[${id}] ✓ Blurred thumbnail regenerated`);
} catch (err) {
console.error(`[${id}] ✗ FAILED:`, err.message || err);
}
return;
}
console.log(`[${id}] Regenerating: ${dest} (${mime})`);
try {
@@ -49,23 +79,23 @@ const regen = async (item) => {
console.log(`[${id}] ✓ Thumbnail regenerated`);
}
// Regenerate blurred thumbnail if item has NSFW tag
const nsfw = await db`SELECT 1 FROM tags_assign WHERE item_id = ${id} AND tag_id = 2 LIMIT 1`;
if (nsfw.length > 0) {
await queue.genBlurredThumbnail(id, false);
console.log(`[${id}] ✓ Blurred thumbnail regenerated`);
}
// Regenerate blurred thumbnail unconditionally
await queue.genBlurredThumbnail(id, false);
console.log(`[${id}] ✓ Blurred thumbnail regenerated`);
} catch (err) {
console.error(`[${id}] ✗ FAILED:`, err.message || err);
}
};
// Shared NOT IN clause for Flash exclusion
const flashExclude = db`mime NOT IN (${db(FLASH_MIMES)})`;
try {
let items;
if (args.includes('--all')) {
items = await db`SELECT id, dest, mime, src FROM items WHERE active = true AND is_deleted = false ORDER BY id`;
console.log(`Regenerating ALL ${items.length} items...\n`);
items = await db`SELECT id, dest, mime, src FROM items WHERE active = true AND is_deleted = false AND ${flashExclude} ORDER BY id`;
console.log(`Regenerating ALL ${items.length} non-Flash items...\n`);
} else if (args.includes('--audio')) {
items = await db`SELECT id, dest, mime, src FROM items WHERE active = true AND is_deleted = false AND mime ILIKE 'audio/%' ORDER BY id`;
console.log(`Regenerating ${items.length} audio items...\n`);
@@ -75,6 +105,14 @@ try {
} else if (args.includes('--youtube')) {
items = await db`SELECT id, dest, mime, src FROM items WHERE active = true AND is_deleted = false AND mime = 'video/youtube' ORDER BY id`;
console.log(`Regenerating ${items.length} YouTube items...\n`);
} else if (blurOnly) {
items = await db`
SELECT id, dest, mime, src
FROM items
WHERE active = true AND is_deleted = false AND ${flashExclude}
ORDER BY id
`;
console.log(`Regenerating ONLY blurred thumbnails for all ${items.length} non-Flash items...\n`);
} else {
const ids = args.map(Number).filter(n => !isNaN(n) && n > 0);
if (ids.length === 0) {
@@ -97,3 +135,4 @@ try {
console.error('Fatal error:', err);
process.exit(1);
}

View File

@@ -19,7 +19,8 @@ const sendJson = (res, data, code = 200) => {
// Generate UUID using the same method as video uploads
const genuuid = async () => {
return (await db`select gen_random_uuid() as uuid`)[0].uuid.substring(0, 8);
const raw = (await db`select replace(gen_random_uuid()::text, '-', '') || replace(gen_random_uuid()::text, '-', '') as uuid`)[0].uuid;
return raw.substring(0, 48);
};
export const handleAvatarUpload = async (req, res) => {
@@ -161,6 +162,14 @@ export const handleAvatarUpload = async (req, res) => {
where user_id = ${+req.session.id}
`;
const payloadStr = JSON.stringify({
user_id: req.session.id,
user: req.session.user,
avatar_file: finalFilename,
avatar: null
});
await db`select pg_notify('profile_update', ${payloadStr})`;
console.log('[AVATAR HANDLER] Upload complete:', finalFilename);
return sendJson(res, {
success: true,
@@ -224,6 +233,13 @@ export const handleAvatarDelete = async (req, res) => {
where user_id = ${+req.session.id}
`;
const payloadStr = JSON.stringify({
user_id: req.session.id,
user: req.session.user,
avatar_file: null
});
await db`select pg_notify('profile_update', ${payloadStr})`;
console.log('[AVATAR HANDLER] Delete complete');
return sendJson(res, { success: true, msg: 'Custom avatar removed' }, 200);
} catch (err) {

289
src/banner_handler.mjs Normal file
View File

@@ -0,0 +1,289 @@
import cfg from "./inc/config.mjs";
import path from "path";
import { promises as fs } from "fs";
import db from "./inc/sql.mjs";
import lib from "./inc/lib.mjs";
import { parseMultipart, collectBody } from "./inc/multipart.mjs";
import { execFile as _execFile } from "child_process";
import { promisify } from "util";
const execFile = promisify(_execFile);
// Helper for JSON response
const sendJson = (res, data, code = 200) => {
res.writeHead(code, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
};
// Generate UUID using the same method as video uploads
const genuuid = async () => {
const raw = (await db`select replace(gen_random_uuid()::text, '-', '') || replace(gen_random_uuid()::text, '-', '') as uuid`)[0].uuid;
return raw.substring(0, 48);
};
export const handleBannerUpload = async (req, res) => {
console.log('[BANNER HANDLER] Upload started');
// Manual Session Lookup
let user = [];
if (req.cookies && req.cookies.session) {
user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user_sessions".id as sess_id, "user_sessions".csrf_token, "user_options".*
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
left join "user_options" on "user_options".user_id = "user_sessions".user_id
where "user_sessions".session = ${lib.sha256(req.cookies.session)}
limit 1
`;
}
if (user.length === 0) {
console.log('[BANNER HANDLER] Unauthorized - No valid session found');
return sendJson(res, { success: false, msg: 'Unauthorized' }, 401);
}
req.session = user[0];
console.log('[BANNER HANDLER] Authorized:', req.session.user);
// CSRF validation
if (req.session.csrf_token) {
const csrfToken = req.headers['x-csrf-token'];
if (!csrfToken || csrfToken !== req.session.csrf_token) {
console.warn(`[CSRF] Blocked banner upload for user ${req.session.user}. Invalid token.`);
return sendJson(res, { success: false, msg: 'Invalid CSRF token' }, 403);
}
}
try {
const contentType = req.headers['content-type'] || '';
const boundaryMatch = contentType.match(/boundary=(.+)$/);
if (!boundaryMatch) {
console.log('[BANNER HANDLER] No boundary');
return sendJson(res, { success: false, msg: 'Invalid content type' }, 400);
}
console.log('[BANNER HANDLER] Collecting body...');
const body = await collectBody(req);
console.log('[BANNER HANDLER] Body collected, size:', body.length);
console.log('[BANNER HANDLER] Parsing multipart...');
const parts = parseMultipart(body, boundaryMatch[1]);
const file = parts.file;
console.log('[BANNER HANDLER] Parsed, file present:', !!file, 'keys:', Object.keys(parts));
if (!file || !file.data) {
return sendJson(res, { success: false, msg: 'No file provided' }, 400);
}
// Validate file size (5MB max)
const maxSize = 5 * 1024 * 1024;
if (file.data.length > maxSize) {
return sendJson(res, {
success: false,
msg: `File too large. Maximum size is 5MB, got ${(file.data.length / 1024 / 1024).toFixed(2)}MB`
}, 400);
}
// Allowed MIME types
const allowedMimes = [
'image/gif',
'image/jpeg',
'image/jpg',
'image/png',
'image/webp'
];
// Validate MIME type from content-type header
let mime = (file.contentType || '').toLowerCase().split(';')[0].trim();
console.log('[BANNER HANDLER] File MIME from header:', mime);
if (!allowedMimes.includes(mime)) {
return sendJson(res, {
success: false,
msg: `Invalid file type. Allowed: gif, jpg, jpeg, png, webp. Got: ${mime}`
}, 400);
}
// Save to tmp and verify with file magic
console.log('[BANNER HANDLER] Generating UUID...');
const uuid = await genuuid();
const tmpPath = path.join(cfg.paths.tmp, `banner_${uuid}_tmp`);
const finalFilename = `banner_${uuid}.webp`;
const finalPath = path.join(cfg.paths.a, finalFilename);
await fs.mkdir(cfg.paths.tmp, { recursive: true });
await fs.mkdir(cfg.paths.a, { recursive: true });
console.log('[BANNER HANDLER] Writing tmp file:', tmpPath);
await fs.writeFile(tmpPath, file.data);
// Verify MIME with file magic
console.log('[BANNER HANDLER] Checking MIME with file magic...');
const { stdout: actualMime } = await execFile('file', ['--mime-type', '-b', tmpPath]);
console.log('[BANNER HANDLER] Actual MIME:', actualMime.trim());
const allowedActualMimes = [
'image/gif',
'image/jpeg',
'image/png',
'image/webp'
];
if (!allowedActualMimes.includes(actualMime.trim())) {
await fs.unlink(tmpPath).catch(() => { });
return sendJson(res, {
success: false,
msg: `Invalid file type detected: ${actualMime.trim()}`
}, 400);
}
// Convert to webp using ImageMagick — landscape banner crop (1200x400)
// NOTE: [0] frame selector must be appended to the input path, not a separate arg
console.log('[BANNER HANDLER] Running magick...');
try {
await execFile('magick', [`${tmpPath}[0]`, '-resize', '3840x3840>', '-quality', '85', finalPath]);
} catch (err) {
console.error('[BANNER HANDLER] Magick error:', err.message, err.stderr);
await fs.unlink(tmpPath).catch(() => { });
return sendJson(res, { success: false, msg: 'Failed to process image: ' + err.message }, 500);
}
console.log('[BANNER HANDLER] Magick done, output:', finalPath);
const file_orig = parts.file_orig;
if (file_orig && file_orig.data) {
console.log('[BANNER HANDLER] Processing original file...');
const origTmpPath = path.join(cfg.paths.tmp, `banner_${uuid}_orig_tmp`);
const finalOrigPath = path.join(cfg.paths.a, `banner_${uuid}_orig.webp`);
await fs.writeFile(origTmpPath, file_orig.data);
try {
await execFile('magick', [`${origTmpPath}[0]`, '-resize', '3840x3840>', '-quality', '85', finalOrigPath]);
} catch (err) {
console.error('[BANNER HANDLER] Magick error on original:', err.message);
}
await fs.unlink(origTmpPath).catch(() => { });
}
// Get current banner_file to delete old one (after magick succeeds)
let currentBanner = null;
try {
currentBanner = (await db`
select banner_file from user_options where user_id = ${+req.session.id}
`)[0]?.banner_file;
} catch (dbErr) {
console.error('[BANNER HANDLER] Could not fetch current banner (column may not exist yet):', dbErr.message);
}
// Clean up tmp file
await fs.unlink(tmpPath).catch(() => { });
// Delete old banner file if exists
if (currentBanner) {
const oldPath = path.join(cfg.paths.a, currentBanner);
await fs.unlink(oldPath).catch(() => { });
const oldOrigPath = path.join(cfg.paths.a, currentBanner.replace('.webp', '_orig.webp'));
await fs.unlink(oldOrigPath).catch(() => { });
}
// Update database
console.log('[BANNER HANDLER] Updating database...');
try {
await db`
update user_options
set banner_file = ${finalFilename},
banner_position = ${parts.banner_position || 'center'},
banner_size = ${parts.banner_size || 'cover'}
where user_id = ${+req.session.id}
`;
const payloadStr = JSON.stringify({
user_id: +req.session.id,
user: req.session.user,
banner_file: finalFilename,
banner_position: parts.banner_position || 'center',
banner_size: parts.banner_size || 'cover'
});
await db`select pg_notify('profile_update', ${payloadStr})`;
} catch (dbErr) {
console.error('[BANNER HANDLER] DB update failed:', dbErr.message);
await fs.unlink(finalPath).catch(() => {});
return sendJson(res, { success: false, msg: 'DB error — did you run the migration? ' + dbErr.message }, 500);
}
console.log('[BANNER HANDLER] Upload complete:', finalFilename);
return sendJson(res, {
success: true,
banner_file: finalFilename,
msg: 'Banner uploaded successfully'
}, 200);
} catch (err) {
if (err.code === 'BODY_TOO_LARGE') {
return sendJson(res, { success: false, msg: 'File too large (5 MB max for banners)' }, 413);
}
console.error('[BANNER HANDLER ERROR]', err.message, err.stack);
try {
return sendJson(res, { success: false, msg: err.message || 'Banner upload failed' }, 500);
} catch (_) {}
}
};
export const handleBannerDelete = async (req, res) => {
console.log('[BANNER HANDLER] Delete started');
// Manual Session Lookup
let user = [];
if (req.cookies && req.cookies.session) {
user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user_sessions".id as sess_id, "user_sessions".csrf_token, "user_options".*
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
left join "user_options" on "user_options".user_id = "user_sessions".user_id
where "user_sessions".session = ${lib.sha256(req.cookies.session)}
limit 1
`;
}
if (user.length === 0) {
return sendJson(res, { success: false, msg: 'Unauthorized' }, 401);
}
req.session = user[0];
// CSRF validation
if (req.session.csrf_token) {
const csrfToken = req.headers['x-csrf-token'];
if (!csrfToken || csrfToken !== req.session.csrf_token) {
console.warn(`[CSRF] Blocked banner delete for user ${req.session.user}. Invalid token.`);
return sendJson(res, { success: false, msg: 'Invalid CSRF token' }, 403);
}
}
try {
const currentBanner = (await db`
select banner_file from user_options where user_id = ${+req.session.id}
`)[0]?.banner_file;
if (currentBanner) {
const oldPath = path.join(cfg.paths.a, currentBanner);
await fs.unlink(oldPath).catch(() => { });
const oldOrigPath = path.join(cfg.paths.a, currentBanner.replace('.webp', '_orig.webp'));
await fs.unlink(oldOrigPath).catch(() => { });
}
await db`
update user_options
set banner_file = null
where user_id = ${+req.session.id}
`;
const payloadStr = JSON.stringify({
user_id: +req.session.id,
user: req.session.user,
banner_file: null
});
await db`select pg_notify('profile_update', ${payloadStr})`;
console.log('[BANNER HANDLER] Delete complete');
return sendJson(res, { success: true, msg: 'Custom banner removed' }, 200);
} catch (err) {
console.error('[BANNER DELETE ERROR]', err);
return sendJson(res, { success: false, msg: 'Failed to remove banner' }, 500);
}
};

View File

@@ -12,7 +12,6 @@ const sendJson = (res, data, code = 200) => {
res.end(JSON.stringify(data));
};
// One-time migration: ensure comment_files table exists
db`CREATE TABLE IF NOT EXISTS public.comment_files (
id SERIAL PRIMARY KEY,
comment_id INTEGER REFERENCES public.comments(id) ON DELETE CASCADE,
@@ -25,8 +24,12 @@ db`CREATE TABLE IF NOT EXISTS public.comment_files (
original_filename TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
)`.catch(() => { });
db`CREATE SEQUENCE IF NOT EXISTS comment_files_id_seq`.catch(() => { });
db`ALTER TABLE comment_files ALTER COLUMN id SET DEFAULT nextval('comment_files_id_seq')`.catch(() => { });
db`CREATE INDEX IF NOT EXISTS idx_comment_files_comment_id ON public.comment_files(comment_id)`.catch(() => { });
db`CREATE INDEX IF NOT EXISTS idx_comment_files_checksum ON public.comment_files(checksum)`.catch(() => { });
db`ALTER TABLE public.comment_files ADD CONSTRAINT comment_files_pkey PRIMARY KEY (id)`.catch(() => { });
db`ALTER TABLE public.comment_files REPLICA IDENTITY DEFAULT`.catch(() => { });
/**
* Parse multipart form data supporting multiple files with the same field name.
@@ -92,12 +95,19 @@ const parseMultipartFiles = (buffer, boundary) => {
};
/**
* Build the allowed MIME list for comment uploads (image/*, video/*, audio/*).
* Filters from cfg.mimes, excluding PDF, SWF, etc.
* Build the allowed MIME list for comment uploads.
* Respects cfg.websrv.fileupload_comments_mimes (e.g. ["image", "video", "audio"]) to
* allow a different set of categories than the global allowedMimes used for page uploads.
* Falls back to image/video/audio if the setting is absent.
*/
const getAllowedCommentMimes = () => {
const allowedCats = Array.isArray(cfg.websrv.fileupload_comments_mimes)
? cfg.websrv.fileupload_comments_mimes.map(c => c.toLowerCase())
: ['image', 'video', 'audio'];
return Object.keys(cfg.mimes).filter(mime =>
mime.startsWith('image/') || mime.startsWith('video/') || mime.startsWith('audio/')
allowedCats.some(cat =>
cat.includes('/') ? mime === cat : mime.startsWith(`${cat}/`)
)
);
};
@@ -174,6 +184,7 @@ export const handleCommentUpload = async (req, res) => {
return sendJson(res, { success: false, msg: 'Only one file allowed per comment' }, 400);
}
const allowedMimes = getAllowedCommentMimes();
const results = [];
@@ -374,29 +385,23 @@ export const handleCommentUpload = async (req, res) => {
try {
phash = await queue.generatePHash(tmpPath);
if (phash && !linkedToExisting) {
// Check comment_files for visual duplicate
const cfItems = await db`
SELECT id, phash, dest FROM comment_files
WHERE phash IS NOT NULL AND phash != '' AND phash NOT LIKE '00000000%'
`;
for (const cf of cfItems) {
if (isPhashMatch(phash, cf.phash)) {
const existingAbsPath = path.join(cfg.paths.c, cf.dest);
try {
const realTarget = await fs.realpath(existingAbsPath);
const destPath = path.join(cfg.paths.c, filename);
const relTarget = path.relative(path.dirname(destPath), realTarget);
await fs.symlink(relTarget, destPath);
linkedToExisting = true;
console.log(`[COMMENT_UPLOAD] PHash match in comment_files: ${filename}${relTarget}`);
} catch (e) {
console.error(`[COMMENT_UPLOAD] PHash symlink failed:`, e.message);
}
break;
// Check comment_files for visual duplicate using fast SQL query
const commentMatch = await queue.checkcommentrepostphash(phash);
if (commentMatch) {
const existingAbsPath = path.join(cfg.paths.c, commentMatch.dest);
try {
const realTarget = await fs.realpath(existingAbsPath);
const destPath = path.join(cfg.paths.c, filename);
const relTarget = path.relative(path.dirname(destPath), realTarget);
await fs.symlink(relTarget, destPath);
linkedToExisting = true;
console.log(`[COMMENT_UPLOAD] PHash match in comment_files: ${filename}${relTarget}`);
} catch (e) {
console.error(`[COMMENT_UPLOAD] PHash symlink failed:`, e.message);
}
}
// Also check items table for visual duplicate
// Also check items table for visual duplicate using fast SQL query
if (!linkedToExisting) {
const phashMatch = await queue.checkrepostphash(phash);
if (phashMatch) {
@@ -478,6 +483,74 @@ export const handleCommentUpload = async (req, res) => {
}
};
/**
* DELETE /api/v2/comments/upload/:id
* Called by the client when the user removes a staged (not-yet-posted) attachment
* from the compose area. Only deletes if the row still has comment_id = NULL
* (i.e. it was never linked to a real comment) and belongs to the requesting user.
*/
export const handleCommentUploadCancel = async (req, res, fileId) => {
// Manual session lookup (same pattern as handleCommentUpload)
if (req.cookies?.session) {
try {
const user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user".is_moderator, "user_sessions".id as sess_id, "user_sessions".csrf_token, "user_options".*
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
left join "user_options" on "user_options".user_id = "user_sessions".user_id
where "user_sessions".session = ${lib.sha256(req.cookies.session)}
limit 1
`;
if (user.length > 0) {
req.session = user[0];
}
} catch (err) {
// Session lookup failed
}
}
if (!req.session) {
return sendJson(res, { success: false, msg: 'Unauthorized' }, 401);
}
const id = parseInt(fileId, 10);
if (!id || isNaN(id)) {
return sendJson(res, { success: false, msg: 'Invalid file ID' }, 400);
}
try {
// Only allow deletion of own unlinked files
const rows = await db`
SELECT id, dest FROM comment_files
WHERE id = ${id}
AND user_id = ${req.session.id}
AND comment_id IS NULL
`;
if (!rows.length) {
// Either doesn't exist, belongs to someone else, or already linked — silently OK
return sendJson(res, { success: true });
}
const { dest } = rows[0];
await db`DELETE FROM comment_files WHERE id = ${id}`;
// Delete file and thumbnail from disk
const filePath = path.join(cfg.paths.c, dest);
const uuid = dest.split('.')[0];
const thumbPath = path.join(cfg.paths.t, `cf_${uuid}.webp`);
await fs.unlink(filePath).catch(() => {});
await fs.unlink(thumbPath).catch(() => {});
console.log(`[COMMENT_UPLOAD] Cancelled (user-removed) attachment deleted: ${dest}`);
return sendJson(res, { success: true });
} catch (err) {
console.error('[COMMENT_UPLOAD] Cancel error:', err);
return sendJson(res, { success: false, msg: 'Delete failed' }, 500);
}
};
/**
* Generate thumbnail for a comment file.
* Outputs to /t/cf_<uuid>.webp
@@ -501,7 +574,33 @@ async function generateCommentThumbnail(filename, mime, uuid, size = 512) {
const ffThumbSize = Math.max(size, 512);
const seeks = ['20%', '40%', '60%', '80%'];
for (const seek of seeks) {
await queue.spawn('ffmpegthumbnailer', ['-i', realSource, '-s', String(ffThumbSize), '-t', seek, '-o', tmpFile]);
try {
await queue.spawn('ffmpegthumbnailer', ['-i', realSource, '-s', String(ffThumbSize), '-t', seek, '-o', tmpFile]);
} catch (err) {
console.warn(`[COMMENT_UPLOAD] ffmpegthumbnailer failed at ${seek} for ${filename}, trying ffmpeg fallback: ${err.message}`);
let seekSeconds = 0;
try {
const durationStr = (await queue.spawn('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', realSource])).stdout.trim();
const duration = parseFloat(durationStr);
if (!isNaN(duration) && duration > 0) {
const pct = parseFloat(seek) / 100;
seekSeconds = duration * pct;
}
} catch (probeErr) {
seekSeconds = seek === '20%' ? 2 : seek === '40%' ? 5 : seek === '60%' ? 8 : 10;
}
// Fallback to ffmpeg, overriding the color transfer characteristic to standard bt709 (1) in case of unsupported trc properties (e.g. log316)
await queue.spawn('ffmpeg', [
'-y',
'-ss', String(seekSeconds),
'-color_trc', '1',
'-i', realSource,
'-frames:v', '1',
'-update', '1',
'-vf', `scale=${ffThumbSize}:${ffThumbSize}:force_original_aspect_ratio=increase,crop=${ffThumbSize}:${ffThumbSize}`,
tmpFile
]);
}
try {
const { stdout } = await queue.spawn('magick', [tmpFile, '-colorspace', 'Gray', '-format', '%[fx:mean]', 'info:']);
if (parseFloat(stdout.trim()) > 0.05) break;
@@ -541,41 +640,4 @@ async function generateCommentThumbnail(filename, mime, uuid, size = 512) {
await fs.unlink(tmpFile).catch(() => { });
}
/**
* PHash matching helper (same logic as queue.checkrepostphash)
*/
function isPhashMatch(newHash, dbHash) {
if (!newHash || !dbHash) return false;
const newHashes = newHash.split('_');
const dbHashes = dbHash.split('_');
const THRESHOLD = 15;
const getHammingDistance = (h1, h2) => {
if (!h1 || !h2 || h1.length !== h2.length) return 9999;
let distance = 0;
for (let i = 0; i < h1.length; i += 2) {
const v1 = parseInt(h1.substr(i, 2), 16);
const v2 = parseInt(h2.substr(i, 2), 16);
let xor = v1 ^ v2;
while (xor) {
distance += xor & 1;
xor >>= 1;
}
}
return distance;
};
const framesToCompare = Math.min(newHashes.length, dbHashes.length);
let matches = 0;
for (let i = 0; i < framesToCompare; i++) {
const dist = getHammingDistance(newHashes[i], dbHashes[i]);
if (dist <= THRESHOLD) matches++;
}
if (framesToCompare >= 3 && matches >= 2) return true;
if (framesToCompare === 1 && matches === 1) return true;
if (framesToCompare === 2 && matches >= 2) return true;
return false;
}

View File

@@ -0,0 +1,262 @@
/**
* dm_attachment_handler.mjs — Server-side handler for encrypted DM attachments.
*
* All uploaded content is opaque AES-GCM ciphertext — the server cannot read it.
* Files are stored at /e/<id> (configured via DM_ATTACHMENT_DIR env or /e/).
*
* Routes (registered as bypass middlewares in index.mjs):
* POST /api/dm/attachment/upload/:recipientId — receive ciphertext blob, store on disk
* GET /api/dm/attachment/:id — stream ciphertext back (auth required)
* DELETE /api/dm/attachment/:id — delete (sender only or admin)
*/
import { promises as fs } from 'fs';
import path from 'path';
import db from './inc/sql.mjs';
import lib from './inc/lib.mjs';
import cfg from './inc/config.mjs';
import { collectBody } from './inc/multipart.mjs';
import { getDmAttachments, getDmAttachmentExpiryDays } from './inc/settings.mjs';
// ─── Config ──────────────────────────────────────────────────────────────────
const ATTACHMENT_DIR = process.env.DM_ATTACHMENT_DIR || cfg.paths.e;
const MAX_BYTES = 50 * 1024 * 1024; // 50 MB plaintext; ciphertext is ~1.33× due to base64url
// Ensure storage dir exists at startup
fs.mkdir(ATTACHMENT_DIR, { recursive: true }).catch(e =>
console.error('[DM_ATT] Failed to create attachment dir:', e.message)
);
// ─── Expiry cleanup ───────────────────────────────────────────────────────────
export async function cleanupExpiredAttachments() {
try {
const expired = await db`
SELECT id, file_path FROM dm_attachments
WHERE expires_at < now()
`;
if (!expired.length) return;
let deleted = 0;
for (const row of expired) {
await fs.unlink(row.file_path).catch(() => {}); // ignore already-missing files
deleted++;
}
const ids = expired.map(r => r.id);
await db`DELETE FROM dm_attachments WHERE id = ANY(${ids})`;
console.log(`[DM_ATT] Cleanup: removed ${deleted} expired attachment(s)`);
} catch (e) {
console.error('[DM_ATT] Cleanup error:', e.message);
}
}
// Run once at startup, then every 6 hours
cleanupExpiredAttachments();
setInterval(cleanupExpiredAttachments, 6 * 60 * 60 * 1000);
// ─── Session helper ───────────────────────────────────────────────────────────
async function resolveSession(req) {
if (!req.cookies?.session) return null;
try {
const rows = await db`
SELECT u.id, u.login, u.user, u.admin, u.is_moderator, s.csrf_token
FROM user_sessions s
LEFT JOIN "user" u ON u.id = s.user_id
WHERE s.session = ${lib.sha256(req.cookies.session)}
LIMIT 1
`;
return rows.length ? rows[0] : null;
} catch { return null; }
}
function sendJson(res, data, code = 200) {
res.writeHead(code, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
function validateCsrf(req, session) {
const token = req.headers['x-csrf-token'];
return session?.csrf_token && token && token === session.csrf_token;
}
// ─── Multipart parser (minimal — only parses fields + one binary file part) ───
function parseAttachmentMultipart(buffer, boundary) {
const boundaryBuf = Buffer.from(`--${boundary}`);
const segments = [];
let start = 0, idx;
while ((idx = buffer.indexOf(boundaryBuf, start)) !== -1) {
if (start !== 0) segments.push(buffer.slice(start, idx - 2));
start = idx + boundaryBuf.length + 2;
}
const result = { fields: {}, file: null };
for (const seg of segments) {
const hdrEnd = seg.indexOf('\r\n\r\n');
if (hdrEnd === -1) continue;
const headers = seg.slice(0, hdrEnd).toString();
const body = seg.slice(hdrEnd + 4);
const nameM = headers.match(/name="([^"]+)"/);
if (!nameM) continue;
const hasFile = headers.includes('filename=') || headers.includes('filename*=');
if (hasFile && !result.file) {
const ctM = headers.match(/Content-Type:\s*([^\r\n]+)/i);
result.file = {
data: body,
contentType: ctM ? ctM[1].trim() : 'application/octet-stream'
};
} else if (!hasFile) {
result.fields[nameM[1]] = body.toString().trim();
}
}
return result;
}
// ─── Upload handler ───────────────────────────────────────────────────────────
export async function handleDmAttachmentUpload(req, res, recipientId) {
if (!getDmAttachments()) return sendJson(res, { success: false, msg: 'Not found' }, 404);
const session = await resolveSession(req);
if (!session) return sendJson(res, { success: false, msg: 'Unauthorized' }, 401);
if (!validateCsrf(req, session)) return sendJson(res, { success: false, msg: 'CSRF mismatch' }, 403);
const rid = parseInt(recipientId, 10);
if (!rid || rid === session.id) return sendJson(res, { success: false, msg: 'Invalid recipient' }, 400);
// Check recipient exists
const recip = await db`SELECT id FROM "user" WHERE id = ${rid} LIMIT 1`;
if (!recip.length) return sendJson(res, { success: false, msg: 'Recipient not found' }, 404);
const ct = req.headers['content-type'] || '';
const bndM = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/);
if (!ct.includes('multipart/form-data') || !bndM) {
return sendJson(res, { success: false, msg: 'Expected multipart/form-data' }, 400);
}
let rawBody;
try {
// MAX_BYTES * 1.4 overhead for base64url encoding + multipart framing
rawBody = await collectBody(req, Math.ceil(MAX_BYTES * 1.4) + 4096);
} catch (e) {
if (e.code === 'BODY_TOO_LARGE') return sendJson(res, { success: false, msg: 'Attachment too large (max 50 MB)' }, 413);
throw e;
}
const boundary = bndM[1] || bndM[2];
const { fields, file } = parseAttachmentMultipart(rawBody, boundary);
if (!file) return sendJson(res, { success: false, msg: 'No file part found' }, 400);
const iv = (fields.iv || '').trim();
const originalName = (fields.original_name || '').slice(0, 255);
const mimeHint = (fields.mime_hint || '').slice(0, 100);
const sizeBytes = parseInt(fields.size_bytes || '0', 10) || 0;
if (!iv || iv.length > 32) return sendJson(res, { success: false, msg: 'Missing or invalid iv' }, 400);
if (file.data.length > Math.ceil(MAX_BYTES * 1.4)) {
return sendJson(res, { success: false, msg: 'Attachment too large (max 50 MB)' }, 413);
}
try {
// Insert DB record first to get an ID
const expiresAt = new Date(Date.now() + getDmAttachmentExpiryDays() * 86400000);
const [row] = await db`
INSERT INTO dm_attachments ${db({
sender_id: session.id,
recipient_id: rid,
iv,
file_path: '',
original_name: originalName,
mime_hint: mimeHint,
size_bytes: sizeBytes,
expires_at: expiresAt
})}
RETURNING id
`;
const filePath = path.join(ATTACHMENT_DIR, String(row.id));
await fs.writeFile(filePath, file.data);
// Update file_path now that we know the ID
await db`UPDATE dm_attachments SET file_path = ${filePath} WHERE id = ${row.id}`;
return sendJson(res, { success: true, id: String(row.id) });
} catch (err) {
console.error('[DM_ATT] Upload error:', err);
return sendJson(res, { success: false, msg: 'Server error' }, 500);
}
}
// ─── Download handler ─────────────────────────────────────────────────────────
export async function handleDmAttachmentDownload(req, res, attachmentId) {
const session = await resolveSession(req);
if (!session) return sendJson(res, { success: false, msg: 'Unauthorized' }, 401);
const id = parseInt(attachmentId, 10);
if (!id) return sendJson(res, { success: false, msg: 'Invalid id' }, 400);
const rows = await db`
SELECT id, sender_id, recipient_id, iv, file_path, original_name, mime_hint
FROM dm_attachments
WHERE id = ${id}
LIMIT 1
`;
if (!rows.length) return sendJson(res, { success: false, msg: 'Not found' }, 404);
const att = rows[0];
// Only sender or recipient may download
if (att.sender_id !== session.id && att.recipient_id !== session.id && !session.admin) {
return sendJson(res, { success: false, msg: 'Forbidden' }, 403);
}
try {
const data = await fs.readFile(att.file_path);
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Length': String(data.length),
'Cache-Control': 'private, no-store',
'X-DM-IV': att.iv,
'X-Original-Name': encodeURIComponent(att.original_name || 'attachment'),
'X-Mime-Hint': att.mime_hint || ''
});
res.end(data);
} catch (err) {
console.error('[DM_ATT] Download error:', err);
return sendJson(res, { success: false, msg: 'File not found on disk' }, 404);
}
}
// ─── Delete handler ───────────────────────────────────────────────────────────
export async function handleDmAttachmentDelete(req, res, attachmentId) {
const session = await resolveSession(req);
if (!session) return sendJson(res, { success: false, msg: 'Unauthorized' }, 401);
if (!validateCsrf(req, session)) return sendJson(res, { success: false, msg: 'CSRF mismatch' }, 403);
const id = parseInt(attachmentId, 10);
if (!id) return sendJson(res, { success: false, msg: 'Invalid id' }, 400);
const rows = await db`SELECT id, sender_id, file_path FROM dm_attachments WHERE id = ${id} LIMIT 1`;
if (!rows.length) return sendJson(res, { success: false, msg: 'Not found' }, 404);
const att = rows[0];
if (att.sender_id !== session.id && !session.admin) {
return sendJson(res, { success: false, msg: 'Forbidden' }, 403);
}
try {
await fs.unlink(att.file_path).catch(() => {});
await db`DELETE FROM dm_attachments WHERE id = ${id}`;
return sendJson(res, { success: true });
} catch (err) {
console.error('[DM_ATT] Delete error:', err);
return sendJson(res, { success: false, msg: 'Server error' }, 500);
}
}

View File

@@ -7,6 +7,7 @@ import path from "path";
import { fileURLToPath } from "url";
import { execFile as _execFile } from "child_process";
import { promisify } from "util";
import crypto from "crypto";
const execFile = promisify(_execFile);
@@ -80,11 +81,11 @@ export const handleEmojiUpload = async (req, res) => {
const file = parts.file;
if (file && file.data && file.data.length > 0) {
const randSuffix = Math.random().toString(36).substring(7);
const randSuffix = crypto.randomBytes(24).toString('hex');
const extMatch = file.filename.match(/\.([a-z0-9]+)$/i);
const originalExt = extMatch ? extMatch[1].toLowerCase() : 'png';
const webpFilename = `${name}_${randSuffix}.webp`;
const webpFilename = `${randSuffix}.webp`;
const webpPath = path.join(cfg.paths.emojis, webpFilename);
if (originalExt === 'webp') {
@@ -135,3 +136,133 @@ export const handleEmojiUpload = async (req, res) => {
return sendJson(res, { success: false, message: err.message }, 500);
}
};
export const handleEmojiEdit = async (req, res) => {
// Manual Session Lookup
let user = [];
if (req.cookies && req.cookies.session) {
user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user".is_moderator, "user_sessions".id as sess_id, "user_sessions".csrf_token
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
where "user_sessions".session = ${lib.sha256(req.cookies.session)}
limit 1
`;
}
if (user.length === 0 || !user[0].admin) {
return sendJson(res, { success: false, message: 'Unauthorized' }, 403);
}
req.session = user[0];
// CSRF validation
if (req.session.csrf_token) {
const csrfToken = req.headers['x-csrf-token'];
if (!csrfToken || csrfToken !== req.session.csrf_token) {
console.warn(`[CSRF] Blocked emoji edit for user ${req.session.user}. Invalid token.`);
return sendJson(res, { success: false, message: 'Invalid CSRF token' }, 403);
}
}
const id = req.params.id;
try {
const contentType = req.headers['content-type'] || '';
const boundaryMatch = contentType.match(/boundary=([^;]+)/);
if (!boundaryMatch) {
return sendJson(res, { success: false, message: 'Invalid content type' }, 400);
}
let boundary = boundaryMatch[1].trim();
if (boundary.startsWith('"') && boundary.endsWith('"')) {
boundary = boundary.substring(1, boundary.length - 1);
}
const bodyBuffer = await collectBody(req);
const parts = parseMultipart(bodyBuffer, boundary);
const name = (parts.name || '').trim().toLowerCase();
let url = (parts.url || '').trim();
if (!name) {
return sendJson(res, { success: false, message: 'Emoji name is required' }, 400);
}
if (!/^[a-z0-9_-]+$/.test(name)) {
return sendJson(res, { success: false, message: 'Invalid name. Use lowercase a-z, 0-9, _, - only.' }, 400);
}
// Fetch the current emoji record
const current = await db`SELECT id, name, url FROM custom_emojis WHERE id = ${id} LIMIT 1`;
if (current.length === 0) {
return sendJson(res, { success: false, message: 'Emoji not found' }, 404);
}
// Check name collision (allow keeping the same name)
if (name !== current[0].name) {
const conflict = await db`SELECT id FROM custom_emojis WHERE name = ${name} AND id != ${id} LIMIT 1`;
if (conflict.length > 0) {
return sendJson(res, { success: false, message: 'Emoji name already exists' }, 400);
}
}
const file = parts.file;
if (file && file.data && file.data.length > 0) {
const randSuffix = crypto.randomBytes(24).toString('hex');
const extMatch = file.filename.match(/\.([a-z0-9]+)$/i);
const originalExt = extMatch ? extMatch[1].toLowerCase() : 'png';
const webpFilename = `${randSuffix}.webp`;
const webpPath = path.join(cfg.paths.emojis, webpFilename);
if (originalExt === 'webp') {
await fs.writeFile(webpPath, file.data);
} else {
const tmpFilename = `${name}_${randSuffix}_tmp.${originalExt}`;
const tmpPath = path.join(cfg.paths.emojis, tmpFilename);
await fs.writeFile(tmpPath, file.data);
try {
await execFile('magick', [tmpPath, '-coalesce', '-quality', '80', webpPath], { env: magickEnv });
} finally {
await fs.unlink(tmpPath).catch(() => {});
}
}
const stat = await fs.stat(webpPath);
if (!stat || stat.size === 0) throw new Error('File write/conversion verification failed');
// Delete the old local file if it was a hosted emoji
if (current[0].url && current[0].url.startsWith('/s/emojis/')) {
const oldFilename = path.basename(current[0].url);
const oldPath = path.join(cfg.paths.emojis, oldFilename);
await fs.unlink(oldPath).catch(() => {});
}
url = `/s/emojis/${webpFilename}`;
}
// If no new file and no new URL, keep the existing URL
if (!url) {
url = current[0].url;
}
const updated = await db`
UPDATE custom_emojis
SET name = ${name}, url = ${url}
WHERE id = ${id}
RETURNING id, name, url
`;
await db`NOTIFY emojis_updated, '{}'`;
return sendJson(res, { success: true, emoji: updated[0] });
} catch (err) {
if (err.code === '23505') {
return sendJson(res, { success: false, message: 'Emoji name already exists' }, 400);
}
console.error('[EMOJI EDIT ERROR]', err);
return sendJson(res, { success: false, message: err.message }, 500);
}
};

View File

@@ -269,6 +269,9 @@ export const handleHallUpdate = async (req, res) => {
// POST /api/v2/admin/halls — create a new hall
export const handleHallCreate = async (req, res) => {
const session = await lookupSession(req);
if (!session || (!session.admin && !session.is_moderator)) return sendJson(res, { success: false, msg: 'Unauthorized' }, 403);
// CSRF check
const token = req.headers['x-csrf-token'] || req.url?.qs?.csrf_token;
if (!token || token !== session.csrf_token) {

View File

@@ -30,7 +30,7 @@ const resolvePath = (defaultRel) => {
const absStorage = path.resolve(storage);
if (defaultRel.startsWith('public/')) {
const sub = defaultRel.replace('public/', '');
if (sub === 's/emojis' || sub === 's/koepfe') {
if (sub === 's/emojis' || sub === 's/koepfe' || sub === 's/fonts') {
const storagePath = path.join(absStorage, sub.split('/').pop());
if (fs.existsSync(storagePath)) return path.resolve(storagePath);
return local;
@@ -51,7 +51,9 @@ config.paths = {
s: path.join(base, 'public/s'),
emojis: resolvePath('public/s/emojis'),
koepfe: resolvePath('public/s/koepfe'),
fonts: resolvePath('public/s/fonts'),
memes: resolvePath('public/memes'),
e: resolvePath('e'),
pending: resolvePath('pending'),
deleted: resolvePath('deleted'),
logs: resolvePath('logs'),

View File

@@ -81,6 +81,37 @@ export default new class {
}
return tmp;
};
/**
* Build a multi-rating SQL WHERE clause fragment from an array of rating strings.
* Supported values: 'sfw', 'nsfw', 'nsfl', 'untagged'
* Returns null if the ratings array is empty or contains all possible values (treat as ALL).
*/
getMultiRatingMode(ratings) {
if (!Array.isArray(ratings) || ratings.length === 0) return null;
const valid = ['sfw', 'nsfw', 'nsfl', 'untagged'];
const filtered = ratings.filter(r => valid.includes(r));
if (filtered.length === 0) return null;
// If all 4 are selected, treat as ALL
if (filtered.includes('sfw') && filtered.includes('nsfw') && filtered.includes('untagged') &&
(!cfg.enable_nsfl || filtered.includes('nsfl'))) return '1 = 1';
const parts = [];
if (filtered.includes('sfw')) {
parts.push('items.id in (select item_id from tags_assign where tag_id = 1)');
}
if (filtered.includes('nsfw')) {
parts.push('items.id in (select item_id from tags_assign where tag_id = 2)');
}
if (filtered.includes('nsfl') && cfg.enable_nsfl) {
parts.push(`items.id in (select item_id from tags_assign where tag_id = ${parseInt(cfg.nsfl_tag_id, 10) || 3})`);
}
if (filtered.includes('untagged')) {
parts.push('not exists (select 1 from tags_assign where item_id = items.id)');
}
if (parts.length === 0) return null;
return '(' + parts.join(' OR ') + ')';
};
createID() {
return crypto.randomBytes(16).toString("hex") + Date.now().toString(24);
};
@@ -101,9 +132,16 @@ export default new class {
// Build suffix with query params
let suffix = env.strict ? '?strict=1' : '';
if (env.tagger) suffix += (suffix ? '&' : '?') + `tagger=${encodeURIComponent(env.tagger)}`;
// mainDisplay: decoded for human-readable display (e.g. div.location)
// main: keeps percent-encoding for use in href attributes
let mainDisplay = tmp;
try { mainDisplay = decodeURIComponent(tmp); } catch (_) {}
return {
main: tmp,
mainDisplay,
path: env.path ? env.path : '',
suffix: suffix
};
@@ -183,10 +221,30 @@ export default new class {
return "$f0ck$" + salt + ":" + derivedKey.toString("hex");
};
async verify(str, hash) {
const [salt, key] = hash.substring(6).split(":");
const keyBuffer = Buffer.from(key, "hex");
const derivedKey = await scrypt(str, salt, 64);
return crypto.timingSafeEqual(keyBuffer, derivedKey);
if (typeof hash !== 'string') return false;
if (hash.startsWith("$f0ck$")) {
const parts = hash.substring(6).split(":");
if (parts.length !== 2) return false;
const [salt, key] = parts;
try {
const keyBuffer = Buffer.from(key, "hex");
const derivedKey = await scrypt(str, salt, 64);
return crypto.timingSafeEqual(keyBuffer, derivedKey);
} catch (e) {
return false;
}
}
if (hash.length === 32) {
return this.md5(str) === hash;
}
if (hash.length === 64) {
return this.sha256(str) === hash;
}
return false;
};
async getTags(itemid) {
const tags = await db`
@@ -314,6 +372,67 @@ export default new class {
return next();
};
// Middleware: authenticate via X-Api-Key header (upload-only)
async apiKeyAuth(req, res, next) {
const key = req.headers['x-api-key'];
if (!key) {
return res.reply({
code: 401,
body: JSON.stringify({ success: false, msg: 'API key required' }),
type: 'application/json'
});
}
let row;
try {
const rows = await db`
SELECT
u.id, u.user, u.login, u.admin, u.is_moderator, u.banned,
uo.display_name, uo.mode, uo.theme, uo.avatar, uo.avatar_file,
uo.username_color, uo.show_motd, uo.disable_autoplay,
uo.disable_swiping, uo.use_new_layout, uo.excluded_tags,
uo.ruffle_background, uo.ruffle_volume, uo.quote_emojis,
uo.embed_youtube_in_comments, uo.hide_koepfe,
uo.use_alternative_infobox, uo.language, uo.comment_display_mode,
uo.force_comment_display_mode, uo.min_xd_score, uo.show_background,
uo.font, uo.receive_system_notifications, uo.receive_user_notifications,
uo.do_not_disturb, uo.description
FROM user_api_keys k
JOIN "user" u ON u.id = k.user_id
LEFT JOIN user_options uo ON uo.user_id = u.id
WHERE k.api_key = ${key}
LIMIT 1
`;
row = rows[0];
} catch (err) {
console.error('[API KEY AUTH] DB error:', err);
return res.reply({
code: 500,
body: JSON.stringify({ success: false, msg: 'Internal server error' }),
type: 'application/json'
});
}
if (!row) {
return res.reply({
code: 401,
body: JSON.stringify({ success: false, msg: 'Invalid API key' }),
type: 'application/json'
});
}
if (row.banned) {
return res.reply({
code: 403,
body: JSON.stringify({ success: false, msg: 'Account banned' }),
type: 'application/json'
});
}
req.session = { ...row, api_key_auth: true };
return next();
};
getCookieOptions(expires = null, httpOnly = true) {
const isSecure = cfg.main.url.full && cfg.main.url.full.startsWith('https');
let options = "Path=/; SameSite=Lax";
@@ -341,4 +460,15 @@ export default new class {
console.error(`[ERROR REF ${errId}] ${context}:`, err);
return `Internal Error. Reference: ${errId}`;
}
isOnionRequest(req) {
if (!req || !req.headers) return false;
const rawHost = req.headers['x-forwarded-host'] || req.headers['host'] || req.headers['x-forwarded-server'] || '';
if (!rawHost) return false;
const hostStr = Array.isArray(rawHost) ? rawHost[0] : String(rawHost);
const firstHost = hostStr.split(',')[0].trim();
const hostNoPort = firstHost.split(':')[0].trim().toLowerCase();
return hostNoPort.endsWith('.onion');
}
};

View File

@@ -70,7 +70,17 @@
"btn_add_urls": "URL(s) hinzufügen",
"tags_required_shitpost": "Alle Beiträge benötigen Tags",
"url_queued_background": "URL Verarbeitung im Hintergrund gestartet.",
"add_more": "Mehr hinzufügen"
"add_more": "Mehr hinzufügen",
"url_tracker_title": "URL-Uploads",
"url_tracker_queued": "Warteschlange",
"url_tracker_downloading": "Wird heruntergeladen",
"url_tracker_analyzing": "Wird analysiert",
"url_tracker_saving": "Wird gespeichert",
"url_tracker_processing": "Wird verarbeitet",
"url_tracker_extracting": "Wird extrahiert",
"url_tracker_complete": "Fertig!",
"url_tracker_failed": "Upload fehlgeschlagen",
"url_tracker_view": "Ansehen →"
},
"auth": {
"registering": "Wird registriert...",
@@ -120,6 +130,7 @@
"switching": "Wird umgeschaltet...",
"generating": "Wird generiert...",
"title": "Einstellungen",
"profile": "Profil",
"avatar": "Avatar",
"current_avatar": "Aktueller Avatar",
"upload_custom_avatar": "Eigenen Avatar hochladen",
@@ -128,26 +139,46 @@
"no_file_selected": "Keine Datei ausgewählt",
"upload_btn": "Hochladen",
"remove_custom": "Eigenen entfernen",
"current_banner": "Aktuelles Banner",
"banner_hint": "Max. 5 MB. Erlaubt: gif, jpg, png, webp",
"no_banner_set": "Kein Banner gesetzt",
"custom_description": "Eigene Beschreibung",
"description_placeholder": "Beschreibung zum Profil hinzufügen",
"save_description": "Beschreibung speichern",
"clear": "Löschen",
"preferences": "Einstellungen",
"ui_section": "Benutzeroberfläche",
"content_preferences_section": "Inhaltseinstellungen",
"appearance_section": "Erscheinungsbild",
"show_motd": "Nachricht des Tages (MOTD) anzeigen",
"modern_layout": "Modernes Layout",
"modern_layout_hint": "3-Spalten-Layout",
"alternative_infobox": "Alternativer Autor-Infoblock",
"alternative_infobox_hint": "Zeigt einen erweiterten Autor-Block mit Avatar und Bio auf Beitragsseiten",
"alternative_steuerung": "Icon-Navigationsstil",
"alternative_steuerung_hint": "Ersetzt die Text-Navigation (← zurück | Zufall | weiter →) durch kompakte Chevron-Icons",
"f_for_fullscreen": "F is for Fullscreen",
"f_for_fullscreen_hint": "Das Drücken von F schaltet das Vollbild im Videoplayer statt den Beitrag zu favorisieren.",
"disable_autoplay": "Automatische Wiedergabe deaktivieren",
"disable_autoplay_hint": "Verhindert die automatische Wiedergabe von Videos und Audio",
"hide_item_ratings": "Item-Bewertungen ausblenden",
"hide_item_ratings_hint": "Zeige keine SFW/NSFW-Bewertungsindikatoren bei Elementen auf der Hauptseite",
"disable_swiping": "Wischen deaktivieren",
"disable_swiping_hint": "Navigation per Wischen auf Mobilgeräten deaktivieren",
"image_expand_on_click": "Bilder beim Klicken inline erweitern",
"image_expand_on_click_hint": "Anstatt das Scroll-Zoom-Modal zu öffnen, wird ein Bild beim Klicken innerhalb der Seite auf volle Größe erweitert.",
"enable_bg_blur": "Hintergrundunschärfe aktivieren",
"enable_bg_blur_hint": "Unscharfen Hintergrund bei Beiträgen anzeigen",
"blur_nsfw": "NSFW weichzeichnen",
"blur_nsfw_hint": "Zeichnet NSFW-Vorschaubilder weich.",
"blur_nsfl": "NSFL weichzeichnen",
"blur_nsfl_hint": "Zeichnet NSFL-Vorschaubilder weich.",
"blur_sfw": "SFW weichzeichnen",
"blur_sfw_hint": "Zeichnet SFW-Vorschaubilder weich.",
"blur_untagged": "Unmarkierte weichzeichnen",
"blur_untagged_hint": "Zeichnet unmarkierte Vorschaubilder weich.",
"blur_detail": "Beiträge weichzeichnen",
"blur_detail_hint": "Erfordert das Anklicken zum Anzeigen von weichgezeichneten Medien auf der Beitragsseite.",
"render_emojis": "Emojis in Zitatantworten anzeigen",
"render_emojis_hint": ":emoji:-Bilder in >zitierten Zeilen anzeigen",
"embed_yt": "YouTube-Videos in Kommentaren einbetten",
@@ -156,7 +187,7 @@
"hide_koepfe_hint": "Die Köpfe deaktivieren",
"comment_display_mode": "Kommentar-Anzeigemodus",
"comment_display_tree": "Antwort-Baum (Standard)",
"comment_display_linear": "Linear / Flach (4chan-Stil)",
"comment_display_linear": "Linear",
"comment_display_mode_hint": "Wähle aus, wie Kommentare angezeigt werden sollen.",
"forced_mode_notice": "Diese Einstellung wird von einem Administrator verwaltet.",
"language": "Sprache",
@@ -262,7 +293,9 @@
"toggle_rating": "Beitragsbewertung umschalten",
"play_pause": "Abspielen/Pause",
"next_prev": "Weiter/Zurück",
"volume": "Lautstärke",
"scroll_nav": "Weiter/Zurück",
"frame_skip": "Einzelbildsteuerung (pausiert) / 5s Sprung",
"show_help": "Hilfe anzeigen"
},
"notifications": {
@@ -299,7 +332,10 @@
"scroll_for_more": "Scrollen für mehr..."
},
"error": {
"label": "Fehler"
"label": "Fehler",
"post_not_visible": "Dieser Beitrag ist derzeit leider nicht sichtbar.",
"filter_hint": "Dein aktueller Filter ist auf {mode} gesetzt.",
"filter_hint_link": "Um diesen Inhalt zu sehen, ändere deinen Filter entsprechend."
},
"drop": {
"drop_anywhere": "Überall ablegen zum Hochladen"
@@ -311,7 +347,20 @@
"attach_file": "Datei anhängen",
"uploading_file": "Wird hochgeladen...",
"remove_file": "Datei entfernen",
"file_too_large": "Datei zu groß"
"file_too_large": "Datei zu groß",
"poll_btn_title": "Umfrage erstellen",
"poll_question_placeholder": "Umfragefrage...",
"poll_option_placeholder": "Option...",
"poll_add_option": "Option hinzufügen",
"poll_remove": "Umfrage entfernen",
"poll_vote": "Abstimmen",
"poll_voted": "Abgestimmt",
"poll_votes": "Stimmen",
"poll_vote_single": "Stimme",
"poll_delete": "Umfrage löschen",
"poll_expired": "Umfrage geschlossen",
"poll_anonymous": "Anonym",
"poll_public": "Öffentliche Stimmen"
},
"upload_btn": {
"select_file": "Datei auswählen",
@@ -406,6 +455,10 @@
},
"sidebar": {
"loading_activity": "Aktivität wird geladen...",
"no_activity": "Keine kürzliche Aktivität.",
"failed_to_load": "Laden fehlgeschlagen.",
"loading_more": "Laden…",
"end_of_activity": "─ Ende der Aktivität ─",
"view": "Ansehen",
"read_more": "mehr sehen",
"see_less": "weniger anzeigen",
@@ -430,13 +483,13 @@
},
"ranking": {
"title": "Rangliste",
"top_contributors": "Top-Mitwirkende",
"top_contributors": "Größte Etikettierer",
"col_rank": "Rang",
"col_avatar": "Avatar",
"col_username": "Nutzername",
"col_tagged": "Markiert",
"tag_stats": "Statistiken",
"stat_total": "Gesamt",
"stat_total": "Gesamt Inhalte",
"stat_tagged": "Markiert",
"stat_untagged": "Unmarkiert",
"stat_sfw": "SFW-Inhalte",
@@ -446,6 +499,7 @@
"stat_comments": "Gesamt Kommentare",
"stat_favs": "Gesamt Favoriten",
"stat_disk_usage": "Dateigröße Gesamt",
"stat_users": "Gesamt Benutzer",
"most_favorited": "Meiste Favs",
"favs": "Favs",
"top_xd": "Top xD-Score"
@@ -518,6 +572,24 @@
"found": "Gefundene Metadaten:",
"no_results": "Keine weiteren Metadaten in dieser Datei gefunden."
},
"info_modal": {
"title": "Post- & Datei-Informationen",
"button_title": "Post- & Datei-Informationen",
"id": "Post-ID",
"source": "Quelle",
"uploader": "Hochgeladen von",
"uploaded_at": "Hochgeladen am",
"file_size": "Dateigröße",
"mime_type": "MIME-Typ",
"rating": "Bewertung",
"oc": "Originaler Inhalt (OC)",
"no": "Nein",
"direct_url": "Direkt-Link",
"view_file": "Datei anzeigen",
"metadata": "Metadaten",
"sha256": "SHA-256-Hash",
"dimensions": "Abmessungen"
},
"meme": {
"add_text_layer": "Textebene hinzufügen",
"tags_label": "Tags (kommagetrennt)",
@@ -528,7 +600,12 @@
"text_layer": "Textebene",
"enter_text": "Text eingeben...",
"size_label": "Größe",
"create_meme": "Meme erstellen:"
"create_meme": "Meme erstellen:",
"custom_template_title": "Eigene Vorlage",
"custom_template_tag": "Lokale Datei",
"select_image": "Eigenes Bild auswählen",
"choose_file_btn": "Bild aussuchen",
"choose_image_first": "Bitte wählen Sie zuerst ein Bild aus!"
},
"timeago": {
"just_now": "gerade eben",
@@ -693,5 +770,30 @@
"left_hand_desc": "Du weißt bescheid.",
"replying_to": "Antwort an {user}",
"reply": "Antworten"
},
"invites": {
"section_title": "Einladungen",
"section_desc": "Lade neue Nutzer ein. Du musst alle unten stehenden Kriterien erfüllen, um Einladungstokens zu generieren.",
"eligible": "✓ Du bist berechtigt, Einladungen zu generieren.",
"not_eligible": "✗ Du erfüllst noch nicht alle Kriterien.",
"slots_used": "{used} / {total} Einladungsslots genutzt",
"criteria_uploads": "Uploads",
"criteria_age": "Kontoalter",
"criteria_comments": "Kommentare",
"criteria_tags": "Vergebene Tags",
"criteria_days": " Tage",
"generate_btn": "Einladung generieren",
"generating": "Wird generiert…",
"loading": "Wird geladen…",
"no_invites": "Noch keine Einladungstokens generiert.",
"status_unused": "Ungenutzt",
"status_used_by": "Genutzt von {user}",
"copy_btn": "Kopieren",
"copied": "Kopiert!",
"delete_btn": "Löschen",
"delete_confirm": "Diesen Einladungstoken löschen?",
"slot_refreshes_on": "Slot erneuert sich am {date}",
"slot_refreshed": "Slot erneuert",
"admin_desc": "Du bist Admin, leg los."
}
}

View File

@@ -64,13 +64,23 @@
"remove_file": "Remove File",
"cancel_upload": "Cancel Upload",
"shitpost_success": "Successfully shitposted {n} items!",
"shitposting_status": "Shitposting",
"item_comment_placeholder": "Comment (optional)...",
"shitposting_status": "Uploading",
"item_comment_placeholder": "Write a Comment...",
"item_tags_placeholder": "Tags...",
"btn_add_urls": "Add URL(s)",
"tags_required_shitpost": "All items need tags",
"url_queued_background": "URL processing started in background.",
"add_more": "Add more"
"add_more": "Add more",
"url_tracker_title": "URL Uploads",
"url_tracker_queued": "Queued",
"url_tracker_downloading": "Downloading",
"url_tracker_analyzing": "Analyzing",
"url_tracker_saving": "Saving",
"url_tracker_processing": "Processing",
"url_tracker_extracting": "Extracting",
"url_tracker_complete": "Complete!",
"url_tracker_failed": "Upload failed",
"url_tracker_view": "View →"
},
"auth": {
"registering": "Registering...",
@@ -120,6 +130,7 @@
"switching": "Switching...",
"generating": "Generating...",
"title": "Settings",
"profile": "Profile",
"avatar": "Avatar",
"current_avatar": "Current Avatar",
"upload_custom_avatar": "Upload Custom Avatar",
@@ -128,26 +139,46 @@
"no_file_selected": "No file selected",
"upload_btn": "Upload",
"remove_custom": "Remove Custom",
"current_banner": "Current Banner",
"banner_hint": "Max 5MB. Allowed: gif, jpg, png, webp",
"no_banner_set": "No banner set",
"custom_description": "Custom Description",
"description_placeholder": "Add a description to your profile",
"save_description": "Save Description",
"clear": "Clear",
"preferences": "Preferences",
"ui_section": "User Interface",
"content_preferences_section": "Content Preferences",
"appearance_section": "Appearance",
"show_motd": "Show Message of the Day (MOTD)",
"modern_layout": "Modern layout",
"modern_layout_hint": "3 Column Layout",
"alternative_infobox": "Alternative Author Infobox",
"alternative_infobox_hint": "Show a rich author card with avatar and bio on item pages",
"alternative_steuerung": "Icon nav style",
"alternative_steuerung_hint": "Replace text navigation (← prev | random | next →) with compact chevron icons",
"f_for_fullscreen": "F is for Fullscreen",
"f_for_fullscreen_hint": "Pressing F will toggle fullscreen in the video player instead of favoriting the post.",
"disable_autoplay": "Disable Autoplay",
"disable_autoplay_hint": "Prevent videos and audio from playing automatically",
"hide_item_ratings": "Hide Item Ratings",
"hide_item_ratings_hint": "Don't show SFW/NSFW rating indicators on main page items",
"disable_swiping": "Disable Swiping",
"disable_swiping_hint": "Disable swipe-to-navigate on mobile devices",
"image_expand_on_click": "Expand images inline on click",
"image_expand_on_click_hint": "Instead of opening the scroll zoom modal, clicking an image will expand it to full size within the page.",
"enable_bg_blur": "Enable Background blur",
"enable_bg_blur_hint": "Show blurred background on items",
"blur_nsfw": "Blur NSFW",
"blur_nsfw_hint": "Blur NSFW-rated thumbnails.",
"blur_nsfl": "Blur NSFL",
"blur_nsfl_hint": "Blur NSFL-rated/shock thumbnails.",
"blur_sfw": "Blur SFW",
"blur_sfw_hint": "Blur SFW-rated thumbnails.",
"blur_untagged": "Blur Untagged",
"blur_untagged_hint": "Blur thumbnails with no tags or rating.",
"blur_detail": "Click to reveal item on detail page",
"blur_detail_hint": "Require clicking to reveal blurred media on the post detail page.",
"render_emojis": "Render emojis in quote replies",
"render_emojis_hint": "Show :emoji: images inside >quoted lines",
"embed_yt": "Embed YouTube links in comments",
@@ -156,7 +187,7 @@
"hide_koepfe_hint": "Disable the Köpfe",
"comment_display_mode": "Comment Display Mode",
"comment_display_tree": "Reply Tree (Default)",
"comment_display_linear": "Linear / Flat (4chan style)",
"comment_display_linear": "Linear",
"comment_display_mode_hint": "Choose how you want comments to be displayed.",
"forced_mode_notice": "This setting is managed by an administrator.",
"language": "Language",
@@ -262,7 +293,9 @@
"toggle_rating": "toggle item rating",
"play_pause": "play/pause",
"next_prev": "next/prev",
"volume": "volume",
"scroll_nav": "next/prev",
"frame_skip": "frame step (paused) / 5s skip",
"show_help": "show help"
},
"notifications": {
@@ -299,7 +332,10 @@
"scroll_for_more": "Scroll for more..."
},
"error": {
"label": "Error"
"label": "Error",
"post_not_visible": "Sorry, this post is currently not visible.",
"filter_hint": "Your current filter is set to {mode}.",
"filter_hint_link": "To view this content, change your filter accordingly."
},
"drop": {
"drop_anywhere": "Drop anywhere to upload"
@@ -311,7 +347,20 @@
"attach_file": "Attach file",
"uploading_file": "Uploading...",
"remove_file": "Remove file",
"file_too_large": "File too large"
"file_too_large": "File too large",
"poll_btn_title": "Create poll",
"poll_question_placeholder": "Poll question...",
"poll_option_placeholder": "Option...",
"poll_add_option": "Add option",
"poll_remove": "Remove poll",
"poll_vote": "Vote",
"poll_voted": "You voted",
"poll_votes": "votes",
"poll_vote_single": "vote",
"poll_delete": "Delete poll",
"poll_expired": "Poll closed",
"poll_anonymous": "Anonymous",
"poll_public": "Public votes"
},
"upload_btn": {
"select_file": "Select a file",
@@ -410,6 +459,10 @@
},
"sidebar": {
"loading_activity": "Loading activity...",
"no_activity": "No recent activity.",
"failed_to_load": "Failed to load.",
"loading_more": "Loading…",
"end_of_activity": "─ end of activity ─",
"view": "View",
"read_more": "read more",
"see_less": "see less",
@@ -450,6 +503,7 @@
"stat_comments": "Total Comments",
"stat_favs": "Total Favorites",
"stat_disk_usage": "Total File Size",
"stat_users": "Total Users",
"most_favorited": "Most Favorited",
"favs": "favs",
"top_xd": "Top xD Scores"
@@ -522,6 +576,24 @@
"found": "Found in metadata:",
"no_results": "No additional metadata fields found in this file."
},
"info_modal": {
"title": "Post & File Information",
"button_title": "Post & File Info",
"id": "Post ID",
"source": "Source",
"uploader": "Uploader",
"uploaded_at": "Uploaded At",
"file_size": "File Size",
"mime_type": "MIME Type",
"rating": "Rating",
"oc": "Original Content (OC)",
"no": "No",
"direct_url": "Direct URL",
"view_file": "View File",
"metadata": "Metadata",
"sha256": "SHA-256 Hash",
"dimensions": "Dimensions"
},
"meme": {
"add_text_layer": "Add Text Layer",
"tags_label": "Tags (comma separated)",
@@ -532,7 +604,12 @@
"text_layer": "Text Layer",
"enter_text": "Enter text...",
"size_label": "Size",
"create_meme": "Create Meme:"
"create_meme": "Create Meme:",
"custom_template_title": "Use Own Template",
"custom_template_tag": "Local File",
"select_image": "Select Custom Image",
"choose_file_btn": "Choose Image",
"choose_image_first": "Please select an image first!"
},
"timeago": {
"just_now": "just now",
@@ -695,5 +772,30 @@
"left_hand_desc": "You know why.",
"replying_to": "Replying to {user}",
"reply": "Reply"
},
"invites": {
"section_title": "Invites",
"section_desc": "Invite new users to join. You must meet all criteria below to generate invite tokens.",
"eligible": "✓ You are eligible to generate invites.",
"not_eligible": "✗ You do not yet meet all criteria.",
"slots_used": "{used} / {total} invite slots used",
"criteria_uploads": "Uploads",
"criteria_age": "Account age",
"criteria_comments": "Comments",
"criteria_tags": "Tags assigned",
"criteria_days": " days",
"generate_btn": "Generate invite",
"generating": "Generating…",
"loading": "Loading…",
"no_invites": "No invite tokens generated yet.",
"status_unused": "Unused",
"status_used_by": "Used by {user}",
"copy_btn": "Copy",
"copied": "Copied!",
"delete_btn": "Delete",
"delete_confirm": "Delete this invite token?",
"slot_refreshes_on": "slot refreshes on {date}",
"slot_refreshed": "slot refreshed",
"admin_desc": "You are an admin, go ahead."
}
}

View File

@@ -70,7 +70,17 @@
"btn_add_urls": "URL(s) toevoegen",
"tags_required_shitpost": "Alle items hebben tags nodig",
"url_queued_background": "URL wordt op de achtergrond verwerkt.",
"add_more": "Meer toevoegen"
"add_more": "Meer toevoegen",
"url_tracker_title": "URL Uploads",
"url_tracker_queued": "In wachtrij",
"url_tracker_downloading": "Downloaden",
"url_tracker_analyzing": "Analyseren",
"url_tracker_saving": "Opslaan",
"url_tracker_processing": "Verwerken",
"url_tracker_extracting": "Extraheren",
"url_tracker_complete": "Klaar!",
"url_tracker_failed": "Upload mislukt",
"url_tracker_view": "Bekijken →"
},
"auth": {
"registering": "Registreren...",
@@ -120,6 +130,7 @@
"switching": "Omschakelen...",
"generating": "Genereren...",
"title": "Instellingen",
"profile": "Profiel",
"avatar": "Avatar",
"current_avatar": "Huidige Avatar",
"upload_custom_avatar": "Aangepaste Avatar Uploaden",
@@ -128,26 +139,46 @@
"no_file_selected": "Geen bestand geselecteerd",
"upload_btn": "Uploaden",
"remove_custom": "Aangepaste Verwijderen",
"current_banner": "Huidige Banner",
"banner_hint": "Max 5MB. Toegestaan: gif, jpg, png, webp",
"no_banner_set": "Geen banner ingesteld",
"custom_description": "Aangepaste Beschrijving",
"description_placeholder": "Voeg een beschrijving toe aan je profiel",
"save_description": "Beschrijving Opslaan",
"clear": "Wissen",
"preferences": "Voorkeuren",
"ui_section": "Gebruikersinterface",
"content_preferences_section": "Inhoudsvoorkeuren",
"appearance_section": "Uiterlijk",
"show_motd": "Toon Bericht van de Dag (MOTD)",
"modern_layout": "Moderne layout",
"modern_layout_hint": "Indeling met 3 kolommen",
"alternative_infobox": "Alternatief auteur-informatievak",
"alternative_infobox_hint": "Toont een uitgebreide auteurkaart met avatar en bio op itempagina's",
"alternative_steuerung": "Icoon-navigatiestijl",
"alternative_steuerung_hint": "Vervangt tekstnavigatie (← terug | willekeurig | verder →) door compacte chevron-iconen",
"f_for_fullscreen": "F is for Fullscreen",
"f_for_fullscreen_hint": "Drukken op F schakelt het volledige scherm in de videospeler in plaats van de post te favorieten.",
"disable_autoplay": "Automatisch afspelen uitschakelen",
"disable_autoplay_hint": "Voorkomen dat video's en audio automatisch worden afgespeeld",
"hide_item_ratings": "Itembeoordelingen verbergen",
"hide_item_ratings_hint": "Toon geen SFW/NSFW beoordelingsindicatoren op hoofdpagina items",
"disable_swiping": "Swipen uitschakelen",
"disable_swiping_hint": "Swipe-to-navigate uitschakelen op mobiele apparaten",
"image_expand_on_click": "Afbeeldingen inline vergroten bij klikken",
"image_expand_on_click_hint": "In plaats van de scroll-zoom-modal te openen, wordt een afbeelding bij klikken vergroot tot volledige grootte binnen de pagina.",
"enable_bg_blur": "Achtergrondvervaging inschakelen",
"enable_bg_blur_hint": "Vervaagde achtergrond tonen bij items",
"blur_nsfw": "NSFW vervagen",
"blur_nsfw_hint": "Vervaagt NSFW-thumbnails.",
"blur_nsfl": "NSFL vervagen",
"blur_nsfl_hint": "Vervaagt NSFL-thumbnails.",
"blur_sfw": "SFW vervagen",
"blur_sfw_hint": "Vervaagt SFW-thumbnails.",
"blur_untagged": "Ongetagde vervagen",
"blur_untagged_hint": "Vervaagt ongetagde thumbnails.",
"blur_detail": "Details weigeren direct te tonen (vervagen)",
"blur_detail_hint": "Vereist klikken om vervaagde media op de detailpagina te onthullen.",
"render_emojis": "Emoji's weergeven in antwoorden",
"render_emojis_hint": "Toon :emoji: afbeeldingen binnen >geciteerde regels",
"embed_yt": "YouTube-links insluiten in opmerkingen",
@@ -156,7 +187,7 @@
"hide_koepfe_hint": "De Köpfe uitschakelen",
"comment_display_mode": "Reactie-weergavemodus",
"comment_display_tree": "Antwoordboom (Standaard)",
"comment_display_linear": "Lineair / Vlak (4chan-stijl)",
"comment_display_linear": "Lineair",
"comment_display_mode_hint": "Kies hoe je reacties wilt laten weergeven.",
"forced_mode_notice": "Deze instelling wordt beheerd door een beheerder.",
"language": "Taal",
@@ -262,7 +293,9 @@
"toggle_rating": "itembeoordeling omschakelen",
"play_pause": "afspelen/pauzeren",
"next_prev": "volgende/vorige",
"volume": "volume",
"scroll_nav": "next/prev",
"frame_skip": "frame-stap (gepauzeerd) / 5s overslaan",
"show_help": "help tonen"
},
"notifications": {
@@ -299,7 +332,10 @@
"scroll_for_more": "Scroll voor meer..."
},
"error": {
"label": "Fout"
"label": "Fout",
"post_not_visible": "Sorry, deze post is momenteel niet zichtbaar.",
"filter_hint": "Je huidige filter is ingesteld op {mode}.",
"filter_hint_link": "Om deze inhoud te bekijken, pas je filter aan."
},
"drop": {
"drop_anywhere": "Overal slepen om te uploaden"
@@ -311,7 +347,20 @@
"attach_file": "Bestand bijvoegen",
"uploading_file": "Uploaden...",
"remove_file": "Bestand verwijderen",
"file_too_large": "Bestand te groot"
"file_too_large": "Bestand te groot",
"poll_btn_title": "Peiling aanmaken",
"poll_question_placeholder": "Peilingvraag...",
"poll_option_placeholder": "Optie...",
"poll_add_option": "Optie toevoegen",
"poll_remove": "Peiling verwijderen",
"poll_vote": "Stemmen",
"poll_voted": "Je hebt gestemd",
"poll_votes": "stemmen",
"poll_vote_single": "stem",
"poll_delete": "Peiling verwijderen",
"poll_expired": "Peiling gesloten",
"poll_anonymous": "Anoniem",
"poll_public": "Openbare stemmen"
},
"upload_btn": {
"select_file": "Selecteer een bestand",
@@ -406,6 +455,10 @@
},
"sidebar": {
"loading_activity": "Activiteit laden...",
"no_activity": "Geen recente activiteit.",
"failed_to_load": "Laden mislukt.",
"loading_more": "Laden…",
"end_of_activity": "─ einde van activiteit ─",
"view": "Bekijken",
"read_more": "lees meer",
"see_less": "zie minder",
@@ -446,6 +499,7 @@
"stat_comments": "Totaal aantal reacties",
"stat_favs": "Totaal aantal favorieten",
"stat_disk_usage": "Totale Bestandsgrootte",
"stat_users": "Totaal Gebruikers",
"most_favorited": "Meest Gefavoriet",
"favs": "favorieten",
"top_xd": "Top xD-scores"
@@ -518,6 +572,24 @@
"found": "Gevonden in metadata:",
"no_results": "Geen extra metadata-velden gevonden in dit bestand."
},
"info_modal": {
"title": "Post- & Bestandsinformatie",
"button_title": "Post- & Bestandsinformatie",
"id": "Post-ID",
"source": "Bron",
"uploader": "Uploader",
"uploaded_at": "Geüpload op",
"file_size": "Bestandsgrootte",
"mime_type": "MIME-type",
"rating": "Beoordeling",
"oc": "Originele Content (OC)",
"no": "Nee",
"direct_url": "Directe URL",
"view_file": "Bestand bekijken",
"metadata": "Metadata",
"sha256": "SHA-256 Hash",
"dimensions": "Afmetingen"
},
"meme": {
"add_text_layer": "Tekstlaag Toevoegen",
"tags_label": "Tags (gescheiden door komma's)",
@@ -528,7 +600,12 @@
"text_layer": "Tekstlaag",
"enter_text": "Voer tekst in...",
"size_label": "Grootte",
"create_meme": "Meme Maken:"
"create_meme": "Meme Maken:",
"custom_template_title": "Eigen sjabloon gebruiken",
"custom_template_tag": "Lokaal bestand",
"select_image": "Selecteer eigen afbeelding",
"choose_file_btn": "Kies afbeelding",
"choose_image_first": "Selecteer eerst een afbeelding!"
},
"timeago": {
"just_now": "zojuist",
@@ -691,5 +768,30 @@
"left_hand_desc": "Je weet wel waarom.",
"replying_to": "Antwoord aan {user}",
"reply": "Antwoorden"
},
"invites": {
"section_title": "Uitnodigingen",
"section_desc": "Nodig nieuwe gebruikers uit. Je moet aan alle onderstaande criteria voldoen om uitnodigingstokens te genereren.",
"eligible": "✓ Je bent bevoegd om uitnodigingen te genereren.",
"not_eligible": "✗ Je voldoet nog niet aan alle criteria.",
"slots_used": "{used} / {total} uitnodigingsslots gebruikt",
"criteria_uploads": "Uploads",
"criteria_age": "Accountleeftijd",
"criteria_comments": "Opmerkingen",
"criteria_tags": "Toegewezen tags",
"criteria_days": " dagen",
"generate_btn": "Uitnodiging genereren",
"generating": "Genereren…",
"loading": "Laden…",
"no_invites": "Nog geen uitnodigingstokens gegenereerd.",
"status_unused": "Ongebruikt",
"status_used_by": "Gebruikt door {user}",
"copy_btn": "Kopiëren",
"copied": "Gekopieërd!",
"delete_btn": "Verwijderen",
"delete_confirm": "Dit uitnodigingstoken verwijderen?",
"slot_refreshes_on": "slot vernieuwd op {date}",
"slot_refreshed": "slot vernieuwd",
"admin_desc": "Je bent admin, ga je gang."
}
}

View File

@@ -70,7 +70,17 @@
"btn_add_urls": "Elfe hinzufügen",
"tags_required_shitpost": "Alle Fetzen brauchen Etiketten",
"url_queued_background": "Elfen-Hintergrundverarbeitung gestartet.",
"add_more": "Meer hinzufügen"
"add_more": "Meer hinzufügen",
"url_tracker_title": "Elfen-Aufladierungen",
"url_tracker_queued": "Warteschlange",
"url_tracker_downloading": "Wird hinunterladiert",
"url_tracker_analyzing": "Wird analysiert",
"url_tracker_saving": "Wird gespeichert",
"url_tracker_processing": "Wird verarbeitet",
"url_tracker_extracting": "Wird extrahiert",
"url_tracker_complete": "Fertig!",
"url_tracker_failed": "Aufladierung fehlgeschlagen",
"url_tracker_view": "Ansehen →"
},
"auth": {
"registering": "Registrierung wird in die Wege geleitet...",
@@ -89,7 +99,7 @@
"password_min_hint": "Muss mindestens 20 Zeichen lang sein.",
"confirm_password": "Kennwort bestätigen",
"email_placeholder": "E-Post",
"invite_token": "Einladungskennzeichen",
"invite_token": "Einladungskots",
"tos_private": "Ich bin mindestens 18 Jahre alt und stimme der Befolgung des Regelwerks zu",
"tos_public": "Ich habe die Nutzungsbedingungen gelesen und akzeptiere diese",
"tos_terms": "Nutzungsbedingungen",
@@ -120,6 +130,7 @@
"switching": "Umschaltung wird vorgenommen...",
"generating": "Generierung wird angestoßen...",
"title": "Einstellungen",
"profile": "Profil",
"avatar": "Profilbild",
"current_avatar": "Aktuelles Profilbild",
"upload_custom_avatar": "Benutzerdefiniertes Profilbild aufladieren",
@@ -128,26 +139,44 @@
"no_file_selected": "Keine Datei ausgewählt",
"upload_btn": "Aufladieren",
"remove_custom": "Benutzerdefiniertes entfernen",
"current_banner": "Aktuelles Banner",
"banner_hint": "Max 5MB. Erlaubt: gif, jpg, png, webp",
"no_banner_set": "Kein Banner gesetzt",
"custom_description": "Benutzerdefinierte Beschreibung",
"description_placeholder": "Fügen Sie Ihrem Profil eine Beschreibung hinzu",
"save_description": "Beschreibung speichern",
"clear": "Leeren",
"preferences": "Präferenzen",
"ui_section": "Benutzeroberfläche",
"content_preferences_section": "Inhaltseinstellungen",
"appearance_section": "Erscheinungsbild",
"show_motd": "Nachricht des Tages (NdT) anzeigen",
"modern_layout": "Modernes Layout",
"modern_layout_hint": "3-Spalten-Layout",
"alternative_infobox": "Alternativer Autor-Infoblock",
"alternative_infobox_hint": "Zeigt einen erweiterten Autor-Block mit Avatar und Bio auf Beitragsseiten",
"alternative_steuerung": "Icon-Navigationsstil",
"alternative_steuerung_hint": "Ersetzt die Text-Navigation (← zurück | Zufall | weiter →) durch kompakte Chevron-Icons",
"f_for_fullscreen": "F is for Fullscreen",
"f_for_fullscreen_hint": "Das Drücken der F-Taste leitet die Vollbildlichkeit des Abspielers ein, statt den Pfosten zu favorisieren.",
"disable_autoplay": "Automatische Wiedergabe deaktivieren",
"disable_autoplay_hint": "Vermeiden Sie das automatische Abspielen von Videos und Tondateien",
"hide_item_ratings": "Item-Bewertungen ausblenden",
"hide_item_ratings_hint": "Zeige keine SFW/NSFW-Bewertungsindikatoren bei Elementen auf der Hauptseite",
"disable_swiping": "Wischen deaktivieren",
"disable_swiping_hint": "Deaktivieren der Wisch-Navigation auf Mobilgeräten",
"image_expand_on_click": "Bildli beim Klickle inline uffblähe",
"image_expand_on_click_hint": "Anstatt dat Scroll-Zoom-Moped aufzumache, wird n Bild beim Klickle uff volle Größ im Bereich uffgepumpt.",
"enable_bg_blur": "Hintergrundunschärfe aktivieren",
"enable_bg_blur_hint": "Gefalteten Hintergrund auf Elementen anzeigen",
"blur_nsfw": "NSFW verwischen",
"blur_nsfw_hint": "Verwischt NSFW-Vorschaubilder.",
"blur_nsfl": "NSFL verwischen",
"blur_nsfl_hint": "Verwischt NSFL-Vorschaubilder.",
"blur_sfw": "SFW verwischen",
"blur_sfw_hint": "Verwischt SFW-Vorschaubilder.",
"blur_untagged": "Unmarkierte verwischen",
"blur_untagged_hint": "Verwischt unmarkierte Vorschaubilder.",
"render_emojis": "Emojis in Zitatantworten darstellen",
"render_emojis_hint": ":emoji:-Bilder innerhalb von >zitierten Zeilen anzeigen",
"embed_yt": "Röhrenelfen in Kommentaren einbetten",
@@ -156,7 +185,7 @@
"hide_koepfe_hint": "Die Köpfe deaktivieren",
"comment_display_mode": "Kommentar-Anzeigemodus",
"comment_display_tree": "Antwort-Baum (Standard)",
"comment_display_linear": "Linear / Flach (Vierkanal-Stil)",
"comment_display_linear": "Linear",
"comment_display_mode_hint": "Wähle aus, wie Kommentare angezeigt werden sollen.",
"forced_mode_notice": "Diese Einstellung wird für Sie verwaltet.",
"language": "Sprache",
@@ -262,7 +291,9 @@
"toggle_rating": "Elementbewertung umschalten",
"play_pause": "Abspielen/Pause",
"next_prev": "nächster/vorheriger",
"volume": "Lautstärke",
"scroll_nav": "nächster/vorheriger",
"frame_skip": "Einzelbildrücken (pausiert) / 5s Hüpfen",
"show_help": "Hilfe anzeigen"
},
"notifications": {
@@ -299,7 +330,10 @@
"scroll_for_more": "Scrollen für mehr..."
},
"error": {
"label": "Fehler"
"label": "Fehler",
"post_not_visible": "Bedauerlicher Weise ist dieser Pfosten derzeit nicht sichtbar.",
"filter_hint": "Ihr aktueller Filter ist auf {mode} eingestellt.",
"filter_hint_link": "Um diesen Inhalt zu betrachten, stellen Sie Ihren Filter entsprechend um."
},
"drop": {
"drop_anywhere": "Überall ablegen zum Aufladieren"
@@ -311,7 +345,20 @@
"attach_file": "Datei anflanschen",
"uploading_file": "Wird aufladiert...",
"remove_file": "Datei entfernen",
"file_too_large": "Datei zu voluminös"
"file_too_large": "Datei zu voluminös",
"poll_btn_title": "Umfrage erstellen",
"poll_question_placeholder": "Frage",
"poll_option_placeholder": "Option",
"poll_add_option": "Option hinzufügen",
"poll_remove": "Umfrage entfernen",
"poll_vote": "Abstimmen",
"poll_voted": "Abgestimmt",
"poll_votes": "Stimmen",
"poll_vote_single": "Stimme",
"poll_delete": "Umfrage löschen",
"poll_expired": "Umfrage geschlossen",
"poll_anonymous": "Anonym",
"poll_public": "Öffentliche Stimmen"
},
"upload_btn": {
"select_file": "Datei auswählen",
@@ -409,6 +456,10 @@
},
"sidebar": {
"loading_activity": "Aktivität wird geladen...",
"no_activity": "Noch keine Aktivität",
"failed_to_load": "Ladung gescheitert.",
"loading_more": "Ladung wird aufbereitet…",
"end_of_activity": "─ Ende des Aktivitätsfadens ─",
"view": "Ansehen",
"read_more": "mehr sehen",
"see_less": "weniger sehen",
@@ -449,6 +500,7 @@
"stat_comments": "Gesamtanzahl Kommentare",
"stat_favs": "Gesamtanzahl Favoriten",
"stat_disk_usage": "Dateigröße Gesamt",
"stat_users": "Gesamt Benutzer",
"most_favorited": "Am häufigsten favorisiert",
"favs": "Favoriten",
"top_xd": "Beste xD-Punktestände"
@@ -521,6 +573,24 @@
"found": "In den Metadaten gefunden:",
"no_results": "Keine weiteren Metadatenfelder in dieser Datei gefunden."
},
"info_modal": {
"title": "Pfosten- & Datei-Informationen",
"button_title": "Pfosten- & Datei-Informationen",
"id": "Pfosten-ID",
"source": "Quelle",
"uploader": "Hochgeladen von",
"uploaded_at": "Hochgeladen am",
"file_size": "Dateigröße",
"mime_type": "MIME-Typ",
"rating": "Bewertung",
"oc": "Originaler Inhalt (OC)",
"no": "Nein",
"direct_url": "Direktelfe",
"view_file": "Datei betrachten",
"metadata": "Metadaten",
"sha256": "SHA-256-Streuwert",
"dimensions": "Abmessungen"
},
"meme": {
"add_text_layer": "Textebene hinzufügen",
"tags_label": "Etiketten (kommagetrennt)",
@@ -531,7 +601,12 @@
"text_layer": "Textebene",
"enter_text": "Text eingeben...",
"size_label": "Größe",
"create_meme": "Memel erstellen:"
"create_meme": "Memel erstellen:",
"custom_template_title": "Eigene Vorlage nutzen",
"custom_template_tag": "Lokale Datei",
"select_image": "Eigenes Bild auswählen",
"choose_file_btn": "Bild aussuchen",
"choose_image_first": "Zuerst Vorlage auswählen"
},
"timeago": {
"just_now": "gerade eben",
@@ -696,5 +771,30 @@
"left_hand_desc": "Sie wissen schon wieso.",
"replying_to": "Antwort an {user}",
"reply": "Antworten"
},
"invites": {
"section_title": "Einladungswesen",
"section_desc": "Laden Sie neue Nutzer ein, beizutreten. Sie müssen alle nachstehenden Kriterien erfüllen, um Einladungskots zu erzeugen.",
"eligible": "✓ Sie sind berechtigt, Einladungen zu erzeugen.",
"not_eligible": "✗ Sie erfüllen noch nicht alle Kriterien.",
"slots_used": "{used} / {total} Einladungsplätze in Benutzung",
"criteria_uploads": "Aufladierungen",
"criteria_age": "Kontoalter",
"criteria_comments": "Kommentare",
"criteria_tags": "Vergebene Etiketten",
"criteria_days": " Tage",
"generate_btn": "Einladung erzeugen",
"generating": "Erzeugung wird durchgeführt…",
"loading": "Ladung wird aufbereitet…",
"no_invites": "Noch keine Einladungskots erzeugt.",
"status_unused": "Ungebraucht",
"status_used_by": "Gebraucht von {user}",
"copy_btn": "Kopieren",
"copied": "Kopiert!",
"delete_btn": "Löschen",
"delete_confirm": "Diesen Einladungskot löschen?",
"slot_refreshes_on": "Platz erneuert sich am {date}",
"slot_refreshed": "Platz erneuert",
"admin_desc": "Du bist Admin, mach weiter."
}
}

View File

@@ -6,6 +6,28 @@ import cfg from "./config.mjs";
import path from "path";
import os from "os";
function isFlatFrame(buffer) {
if (!buffer || buffer.length !== 1056) return true;
let min = 255;
let max = 0;
let sum = 0;
for (let i = 0; i < buffer.length; i++) {
const val = buffer[i];
if (val < min) min = val;
if (val > max) max = val;
sum += val;
}
const mean = sum / buffer.length;
if (mean < 15 || mean > 240) return true;
let sqDiffSum = 0;
for (let i = 0; i < buffer.length; i++) {
sqDiffSum += Math.pow(buffer[i] - mean, 2);
}
const variance = sqDiffSum / buffer.length;
return variance < 10 || (max - min) < 15;
}
export default new class queue {
constructor() {
@@ -85,31 +107,52 @@ export default new class queue {
async generatePHash(source) {
try {
// Temporal dHash implementation:
// 1. Get duration.
// 2. Extract 3 frames: 10%, 50%, 90%.
// 3. Generate dHash for each.
// 4. Return combined hash "hash1_hash2_hash3".
// 1. Check if source is image/video and get duration.
// 2. For videos: Extract 3 frames (10%, 50%, 90% of duration).
// For static images: Extract 1 frame.
// 3. Generate dHash for each valid non-flat frame.
// 4. Return combined hash "hash1_hash2_hash3" or single "hash".
// Skip ffprobe for PDFs (which would fail with "Invalid data")
if (source.toLowerCase().endsWith('.pdf')) {
return null;
}
const durationStr = (await this.spawn('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', source])).stdout.trim();
const duration = parseFloat(durationStr);
if (isNaN(duration) || duration <= 0) return null;
let isVideo = true;
let timestamps = [];
try {
const durationStr = (await this.spawn('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', source])).stdout.trim();
const duration = parseFloat(durationStr);
if (isNaN(duration) || duration <= 0) {
isVideo = false;
} else {
timestamps = [duration * 0.1, duration * 0.5, duration * 0.9];
}
} catch (err) {
isVideo = false;
}
if (!isVideo) {
timestamps = [0]; // Process static image as single frame
}
const timestamps = [duration * 0.1, duration * 0.5, duration * 0.9];
const hashes = [];
for (const ts of timestamps) {
let buffer;
try {
const { stdout } = await this.spawn('ffmpeg', ['-ss', ts.toString(), '-v', 'error', '-i', source, '-vf', 'thumbnail,scale=33:32,format=gray', '-frames:v', '1', '-f', 'rawvideo', 'pipe:1'], { encoding: 'buffer', quiet: true });
const vf = isVideo ? 'thumbnail,scale=33:32,format=gray' : 'scale=33:32,format=gray';
const args = [];
if (isVideo) {
args.push('-ss', ts.toString());
}
args.push('-v', 'error', '-i', source, '-vf', vf, '-frames:v', '1', '-f', 'rawvideo', 'pipe:1');
const { stdout } = await this.spawn('ffmpeg', args, { encoding: 'buffer', quiet: true });
buffer = stdout;
} catch (err) {
console.warn(`[PHASH] Failed to extract frame at ${ts}s for ${source}: ${err.message}`);
// Buffer remains undefined, triggering fallback below
}
if (!buffer || buffer.length !== 1056) {
@@ -117,6 +160,12 @@ export default new class queue {
continue;
}
// Filter out flat/black frames (e.g. solid color backgrounds, fade-to-black)
if (isFlatFrame(buffer)) {
console.log(`[PHASH] Ignored flat/black frame at ${ts}s for ${source}`);
continue;
}
let hash = '';
let currentByte = 0;
let bitCount = 0;
@@ -151,72 +200,122 @@ export default new class queue {
async checkrepostphash(newHash) {
if (!newHash) return false;
const newHashes = newHash.split('_');
const newHashes = newHash.split('_').filter(s => s && !s.startsWith('00000000'));
if (newHashes.length === 0) return false;
// Fetch all phashes, filtering out "all zero" failed hashes
const items = await db`
SELECT id, phash FROM items
WHERE phash IS NOT NULL
AND phash != ''
AND phash NOT LIKE '00000000%'
const h1 = newHashes[0] || '';
const h2 = newHashes[1] || '';
const h3 = newHashes[2] || '';
const results = await db`
SELECT id FROM items
WHERE is_deleted = false
AND phash IS NOT NULL AND phash != '' AND phash != 'ERROR' AND phash != 'MISSING' AND phash NOT LIKE '00000000%'
AND (
(
CASE WHEN split_part(phash, '_', 1) != '' AND ${h1} != '' THEN
bit_count(('x' || split_part(phash, '_', 1))::bit(1024) # ('x' || ${h1})::bit(1024)) <= 15
ELSE false END::int
+
CASE WHEN split_part(phash, '_', 2) != '' AND ${h2} != '' THEN
bit_count(('x' || split_part(phash, '_', 2))::bit(1024) # ('x' || ${h2})::bit(1024)) <= 15
ELSE false END::int
+
CASE WHEN split_part(phash, '_', 3) != '' AND ${h3} != '' THEN
bit_count(('x' || split_part(phash, '_', 3))::bit(1024) # ('x' || ${h3})::bit(1024)) <= 15
ELSE false END::int
) >= (
CASE
WHEN split_part(phash, '_', 3) != '' AND ${h3} != '' THEN 2
WHEN split_part(phash, '_', 2) != '' AND ${h2} != '' THEN 2
ELSE 1
END
)
)
LIMIT 1
`;
// Configurable threshold: max Hamming distance per 256-bit dHash frame.
// A value of 15 means < 6% bit difference — tight enough to only match true duplicates.
const THRESHOLD = 15;
return results.length > 0 ? results[0].id : false;
};
const getHammingDistance = (h1, h2) => {
if (!h1 || !h2 || h1.length !== h2.length) return 9999;
let distance = 0;
for (let i = 0; i < h1.length; i += 2) {
const v1 = parseInt(h1.substr(i, 2), 16);
const v2 = parseInt(h2.substr(i, 2), 16);
let xor = v1 ^ v2;
while (xor) {
distance += xor & 1;
xor >>= 1;
}
}
return distance;
};
async findallrepostphash(newHash, excludeId = null) {
if (!newHash) return [];
const newHashes = newHash.split('_').filter(s => s && !s.startsWith('00000000'));
if (newHashes.length === 0) return [];
// We want at least 2 out of 3 frames to match
const REQUIRED_MATCHES = 2;
const h1 = newHashes[0] || '';
const h2 = newHashes[1] || '';
const h3 = newHashes[2] || '';
for (const item of items) {
// Handle legacy single hashes vs new multi-hashes
const dbHashes = item.phash.split('_');
const results = await db`
SELECT id, username, stamp FROM items
WHERE is_deleted = false
AND phash IS NOT NULL AND phash != '' AND phash != 'ERROR' AND phash != 'MISSING' AND phash NOT LIKE '00000000%'
${excludeId ? db`AND id != ${excludeId}` : db``}
AND (
CASE WHEN split_part(phash, '_', 1) != '' AND ${h1} != '' THEN
bit_count(('x' || split_part(phash, '_', 1))::bit(1024) # ('x' || ${h1})::bit(1024)) <= 15
ELSE false END::int
+
CASE WHEN split_part(phash, '_', 2) != '' AND ${h2} != '' THEN
bit_count(('x' || split_part(phash, '_', 2))::bit(1024) # ('x' || ${h2})::bit(1024)) <= 15
ELSE false END::int
+
CASE WHEN split_part(phash, '_', 3) != '' AND ${h3} != '' THEN
bit_count(('x' || split_part(phash, '_', 3))::bit(1024) # ('x' || ${h3})::bit(1024)) <= 15
ELSE false END::int
>= 1
)
ORDER BY id ASC
`;
let matches = 0;
// Compare corresponding frames: 0vs0, 1vs1, 2vs2
const framesToCompare = Math.min(newHashes.length, dbHashes.length);
return results.map(r => ({ id: r.id, username: r.username, stamp: r.stamp }));
};
for (let i = 0; i < framesToCompare; i++) {
const dist = getHammingDistance(newHashes[i], dbHashes[i]);
if (dist <= THRESHOLD) {
matches++;
}
}
async checkcommentrepostphash(newHash) {
if (!newHash) return false;
const newHashes = newHash.split('_').filter(s => s && !s.startsWith('00000000'));
if (newHashes.length === 0) return false;
// If we have 3 frames, require 2 out of 3 matches.
// If we are comparing against a legacy 1-frame hash, require that single frame to match.
if (framesToCompare >= 3 && matches >= REQUIRED_MATCHES) {
return item.id;
} else if (framesToCompare === 1 && matches === 1) {
return item.id;
} else if (framesToCompare === 2 && matches >= 2) {
return item.id;
}
}
const h1 = newHashes[0] || '';
const h2 = newHashes[1] || '';
const h3 = newHashes[2] || '';
return false;
const results = await db`
SELECT id, dest FROM comment_files
WHERE phash IS NOT NULL AND phash != '' AND phash NOT LIKE '00000000%'
AND (
(
CASE WHEN split_part(phash, '_', 1) != '' AND ${h1} != '' THEN
bit_count(('x' || split_part(phash, '_', 1))::bit(1024) # ('x' || ${h1})::bit(1024)) <= 15
ELSE false END::int
+
CASE WHEN split_part(phash, '_', 2) != '' AND ${h2} != '' THEN
bit_count(('x' || split_part(phash, '_', 2))::bit(1024) # ('x' || ${h2})::bit(1024)) <= 15
ELSE false END::int
+
CASE WHEN split_part(phash, '_', 3) != '' AND ${h3} != '' THEN
bit_count(('x' || split_part(phash, '_', 3))::bit(1024) # ('x' || ${h3})::bit(1024)) <= 15
ELSE false END::int
) >= (
CASE
WHEN split_part(phash, '_', 3) != '' AND ${h3} != '' THEN 2
WHEN split_part(phash, '_', 2) != '' AND ${h2} != '' THEN 2
ELSE 1
END
)
)
LIMIT 1
`;
return results.length > 0 ? results[0] : false;
};
async genuuid() {
return (await db`
select gen_random_uuid() as uuid
`)[0].uuid.substring(0, 8);
const raw = (await db`
select replace(gen_random_uuid()::text, '-', '') || replace(gen_random_uuid()::text, '-', '') as uuid
`)[0].uuid;
return raw.substring(0, 48);
};
async checkrepostlink(link) {
@@ -273,6 +372,10 @@ export default new class queue {
}
} catch (e) {}
const outPath = path.join(tDir, itemid + '.webp');
try {
if (mime === 'video/youtube') {
const videoId = filename.startsWith('yt:') ? filename.split(':')[1] : null;
if (videoId) {
@@ -306,15 +409,51 @@ export default new class queue {
const ffThumbSize = Math.max(thumbSize, 512);
const seeks = ['20%', '40%', '60%', '80%'];
for (const seek of seeks) {
await this.spawn('ffmpegthumbnailer', ['-i', sourcePath, '-s', String(ffThumbSize), '-t', seek, '-o', tmpFile]);
try {
await this.spawn('ffmpegthumbnailer', ['-i', sourcePath, '-s', String(ffThumbSize), '-t', seek, '-o', tmpFile]);
} catch (err) {
console.warn(`[QUEUE] ffmpegthumbnailer failed at ${seek} for ${itemid}, trying ffmpeg fallback: ${err.message}`);
let seekSeconds = 0;
try {
const durationStr = (await this.spawn('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', sourcePath])).stdout.trim();
const duration = parseFloat(durationStr);
if (!isNaN(duration) && duration > 0) {
const pct = parseFloat(seek) / 100;
seekSeconds = duration * pct;
}
} catch (probeErr) {
seekSeconds = seek === '20%' ? 2 : seek === '40%' ? 5 : seek === '60%' ? 8 : 10;
}
// Fallback to ffmpeg, overriding the color transfer characteristic to standard bt709 (1) in case of unsupported trc properties (e.g. log316)
await this.spawn('ffmpeg', [
'-y',
'-ss', String(seekSeconds),
'-color_trc', '1',
'-i', sourcePath,
'-frames:v', '1',
'-update', '1',
'-vf', `scale=${ffThumbSize}:${ffThumbSize}:force_original_aspect_ratio=increase,crop=${ffThumbSize}:${ffThumbSize}`,
tmpFile
]);
}
try {
const { stdout } = await this.spawn('magick', [tmpFile, '-colorspace', 'Gray', '-format', '%[fx:mean]', 'info:']);
if (parseFloat(stdout.trim()) > 0.05) break;
} catch (e) { break; }
}
}
else if (mime.startsWith('image/') && mime != 'image/gif')
await this.spawn('magick', [sourcePath + '[0]', tmpFile]);
else if (mime.startsWith('image/') && mime != 'image/gif') {
if (mime === 'image/avif') {
try {
await this.spawn('ffmpeg', ['-i', sourcePath, '-frames:v', '1', '-update', '1', tmpFile]);
} catch (err) {
// If ffmpeg fails, fallback to magick
await this.spawn('magick', [sourcePath + '[0]', '-auto-orient', tmpFile]);
}
} else {
await this.spawn('magick', [sourcePath + '[0]', '-auto-orient', tmpFile]);
}
}
else if (mime.startsWith('audio/')) {
let coverExtracted = false;
this._lastCoverExtracted = false; // Reset state for this call
@@ -421,11 +560,83 @@ export default new class queue {
});
}
}
else if (mime.startsWith('application/') && cfg.mimes[mime] && !['swf', 'pdf'].includes(cfg.mimes[mime])) {
// Any application/* MIME registered in config that isn't swf or pdf is treated as an archive.
// Both the detection and the label come straight from cfg.mimes — no hardcoded list needed.
let customThumb = cfg.websrv && cfg.websrv.archive_thumb;
if (customThumb && customThumb.startsWith('/')) {
customThumb = path.join(path.resolve(), 'public', customThumb);
}
let usedCustom = false;
if (customThumb) {
try {
const stat = await fs.promises.stat(customThumb).catch(() => null);
if (stat && stat.size > 0) {
await this.spawn('magick', [customThumb, tmpFile]);
usedCustom = true;
}
} catch (_) {}
}
if (!usedCustom) {
const archiveLabel = (cfg.mimes[mime] || 'arc').toUpperCase();
await this.spawn('magick', [
'-size', thumbSpec, 'xc:#1a2e1a',
'-gravity', 'center',
'-fill', '#66bb6a',
'-pointsize', '48',
'-annotate', '0', archiveLabel,
tmpFile
]).catch(() => {});
}
}
await this.spawn('magick', [tmpFile, '-resize', `${thumbSpec}^`, '-gravity', 'center', '-crop', `${thumbSpec}+0+0`, '+repage', path.join(tDir, itemid + '.webp')]);
const isTransparentMime = mime === 'image/png' || mime === 'image/webp' || mime === 'image/avif' || mime === 'image/gif';
if (isTransparentMime) {
// Build a grey/white checkerboard via explicit xc: squares (no pattern replacement tricks):
// row1 = [white | grey], row2 = row1 flipped → stack into a 2x2 tile → tile to thumbSpec
const sq = 16;
const tmpRow1 = path.join(os.tmpdir(), `${itemid}_r1.png`);
const tmpRow2 = path.join(os.tmpdir(), `${itemid}_r2.png`);
const tmpTile = path.join(os.tmpdir(), `${itemid}_tile.png`);
const tmpBg = path.join(os.tmpdir(), `${itemid}_bg.png`);
const tmpResized = path.join(os.tmpdir(), `${itemid}_rs.png`);
try {
await this.spawn('magick', ['-size', `${sq}x${sq}`, 'xc:white', '-size', `${sq}x${sq}`, 'xc:#cccccc', '+append', tmpRow1]);
await this.spawn('magick', [tmpRow1, '-flop', tmpRow2]);
await this.spawn('magick', [tmpRow1, tmpRow2, '-append', tmpTile]);
await this.spawn('magick', ['-size', thumbSpec, `tile:${tmpTile}`, '-define', 'png:color-type=2', tmpBg]);
// Resize/crop source image preserving alpha channel; force sRGB so palette images retain color
await this.spawn('magick', [tmpFile, '-auto-orient', '-colorspace', 'sRGB', '-resize', `${thumbSpec}^`, '-gravity', 'center', '-crop', `${thumbSpec}+0+0`, '+repage', tmpResized]);
// Composite: Over operator — image (with alpha) on top of opaque checkerboard bg
await this.spawn('magick', [tmpBg, tmpResized, '-composite', outPath]);
} finally {
for (const f of [tmpRow1, tmpRow2, tmpTile, tmpBg, tmpResized]) {
await fs.promises.unlink(f).catch(() => {});
}
}
} else {
await this.spawn('magick', [tmpFile, '-auto-orient', '-resize', `${thumbSpec}^`, '-gravity', 'center', '-crop', `${thumbSpec}+0+0`, '+repage', outPath]);
}
await fs.promises.unlink(tmpFile).catch(_ => { });
await fs.promises.unlink(tmpJpg).catch(_ => { });
return true;
} catch (err) {
console.error(`[QUEUE] genThumbnail failed for item ${itemid} (${mime}):`, err.message || err);
// Cleanup temp files
await fs.promises.unlink(tmpFile).catch(() => {});
await fs.promises.unlink(tmpJpg).catch(() => {});
// Fallback: copy 404.gif as the thumbnail
const fallback404 = path.join(cfg.paths.s, 'img', '404.gif');
try {
await this.spawn('magick', [fallback404, '-resize', `${thumbSpec}^`, '-gravity', 'center', '-crop', `${thumbSpec}+0+0`, '+repage', outPath]);
console.warn(`[QUEUE] Used 404.gif fallback thumbnail for item ${itemid}`);
} catch (fallbackErr) {
console.error(`[QUEUE] Even fallback thumbnail failed for item ${itemid}:`, fallbackErr.message || fallbackErr);
}
return false;
}
};
@@ -434,7 +645,7 @@ export default new class queue {
const src = path.join(tDir, `${itemid}.webp`);
const dst = path.join(tDir, `${itemid}_blur.webp`);
try {
await this.spawn('magick', [src, '-blur', '0x20', dst]);
await this.spawn('magick', [src, '-blur', '0x48', dst]);
return true;
} catch (err) {
console.error(`[QUEUE] Failed to generate blurred thumbnail for ${itemid}:`, err);

View File

@@ -2,14 +2,56 @@ import db from "../sql.mjs";
import lib from "../lib.mjs";
import cfg from "../config.mjs";
import { updateHallsCache } from "../halls_cache.mjs";
import queue from "../queue.mjs";
import fs from "fs";
import url from "url";
const globalfilter = cfg.nsfp?.length ? cfg.nsfp.map(n => `tag_id = ${n}`).join(" or ") : null;
const getGlobalfilter = () => cfg.nsfp?.length ? cfg.nsfp.map(n => `tag_id = ${n}`).join(" or ") : null;
// All MIME types that map to the 'swf' extension in config (e.g. application/x-shockwave-flash, application/vnd.adobe.flash.movie)
const flashMimes = Object.entries(cfg.mimes || {}).filter(([, ext]) => ext === 'swf').map(([mime]) => mime);
// ── Count cache ─────────────────────────────────────────────────────────────
// The COUNT(DISTINCT items.id) in getf0cks is expensive (full filtered scan).
// Cache it per unique filter combination for 90 seconds so that navigating
// between pages 1→192 with the same filters skips the COUNT entirely.
const COUNT_CACHE_TTL_MS = 90_000;
const countCache = new Map(); // key → { total, expiresAt }
function buildCountCacheKey({ modequery, tag, user, hall, mime, fav, session, excludedTags, newerThan, minXd, userHallObj, tagger }) {
return JSON.stringify([
modequery,
tag ?? '',
user ?? '',
hall ?? '',
mime ?? '',
fav ? 1 : 0,
session ? 1 : 0, // guests get globalfilter applied; members don't
excludedTags.slice().sort().join(','),
newerThan ?? '',
minXd,
userHallObj?.id ?? '',
tagger ?? ''
]);
}
function getCachedCount(key) {
const entry = countCache.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) { countCache.delete(key); return null; }
return entry.total;
}
function setCachedCount(key, total) {
countCache.set(key, { total, expiresAt: Date.now() + COUNT_CACHE_TTL_MS });
// Prevent unbounded growth — evict all expired entries when cache grows large
if (countCache.size > 500) {
const now = Date.now();
for (const [k, v] of countCache) { if (now > v.expiresAt) countCache.delete(k); }
}
}
// ────────────────────────────────────────────────────────────────────────────
const processMentions = async (comments) => {
if (!comments || comments.length === 0) return comments;
@@ -79,25 +121,31 @@ const computeXdScore = (comments) => {
for (const c of comments) {
if (!c.content || c.is_deleted) continue;
for (const m of c.content.matchAll(xdRegex)) {
score += m[1].length; // 1pt per D: xD=1, xDD=2, xDDD=3, ...
score += m[1].length;
}
}
return score;
};
const xdScoreMeta = (score) => {
if (score <= 0) return { tier: 0, label: '' };
if (score < 5) return { tier: 1, label: 'xD' };
if (score < 15) return { tier: 2, label: 'xDD' };
if (score < 30) return { tier: 3, label: 'xDDD' };
if (score < 60) return { tier: 4, label: 'xDDDD' };
return { tier: 5, label: 'xDDDDD+' };
if (score < 1) return { tier: 0, label: '' };
if (score < 200) return { tier: 1, label: 'xD' };
if (score < 1000) return { tier: 2, label: 'xDD' };
if (score < 100000) return { tier: 3, label: 'xDDD' };
if (score < 20000000) return { tier: 4, label: 'xDDDD' };
return { tier: 5, label: 'xDDDDD+' };
};
export default {
getf0cks: async ({ user: rawUser, tag: rawTag, hall: rawHall, mime: rawMime, page, mode, fav, session, limit, strict, newer, exclude, user_id, random, userHall: rawUserHall, userHallOwner: rawUserHallOwner, minXdScore } = {}) => {
getf0cks: async ({ user: rawUser, tag: rawTag, hall: rawHall, mime: rawMime, page, mode, ratings, fav, session, limit, strict, newer, exclude, user_id, random, userHall: rawUserHall, userHallOwner: rawUserHallOwner, minXdScore, tagger: rawTagger } = {}) => {
const user = rawUser ? lib.escapeLike(decodeURI(rawUser)) : null;
const tag = lib.parseTag(rawTag ?? null);
// --- title: prefix — search items.title instead of the tags table ---
const _decodedTag = rawTag ? decodeURIComponent(rawTag) : '';
const isTitleSearch = _decodedTag.startsWith('title:');
const titleQuery = isTitleSearch ? _decodedTag.substring(6).trim() : null;
const tag = isTitleSearch ? null : lib.parseTag(rawTag ?? null);
let hall = rawHall ?? null;
let hallObj = null;
if (hall) {
@@ -142,12 +190,34 @@ export default {
const strictParams = ((strict || (tag && tag.includes(','))) && tag) ? tag.split(',').map(t => lib.slugify(t)).filter(t => t) : [];
const isStrict = strictParams.length > 0;
const tmp = { user, tag, hall: hallObj || hall, mime, page: actPage, mode: mode, view_mode: fav ? 'favs' : 'uploads', strict: strict, userHall: userHallObj || userHallSlug, userHallOwner };
const baseMode = lib.getMode(mode ?? 0);
const tagger = rawTagger ? lib.escapeLike(rawTagger) : null;
const tmp = { user, tag: isTitleSearch ? _decodedTag : tag, hall: hallObj || hall, mime, page: actPage, mode: mode, view_mode: fav ? 'favs' : 'uploads', strict: strict, userHall: userHallObj || userHallSlug, userHallOwner, tagger };
// Multi-rating support: if `ratings` array provided, build an OR-based SQL fragment
const multiRatingSQL = (Array.isArray(ratings) && ratings.length > 0) ? lib.getMultiRatingMode(ratings) : null;
const baseMode = multiRatingSQL ?? lib.getMode(mode ?? 0);
const modequery = baseMode;
let tagFilter = db``;
if (tag) {
let titleFilter = db``;
if (isTitleSearch && titleQuery) {
// Title search: match items.title ILIKE '%query%'
titleFilter = db`and items.title ILIKE ${'%' + titleQuery + '%'} and items.title IS NOT NULL`;
} else if (tagger && tag) {
// Tagger+tag filter: items where the specific user applied this specific tag
const terms = tag.split(',').map(t => t.trim()).filter(Boolean);
if (terms.length > 0) {
const conditions = terms.map(term => {
return db`and items.id in (
select ta.item_id from tags_assign ta
join tags t on t.id = ta.tag_id
join "user" u on u.id = ta.user_id
where t.normalized like '%' || slugify(${term}) || '%'
and u.user ilike ${tagger}
)`;
});
tagFilter = db`${conditions}`;
}
} else if (tag) {
const terms = tag.split(',').map(t => t.trim()).filter(Boolean);
if (terms.length > 0) {
if (isStrict) {
@@ -180,25 +250,32 @@ export default {
userHallFilter = db`and items.id in (select uha.item_id from user_halls_assign uha where uha.hall_id = ${userHallObj.id})`;
}
const totalRows = await db`
select count(distinct items.id) as total
from items
${fav ? db`inner join favorites on favorites.item_id = items.id inner join "user" fav_u on fav_u.id = favorites.user_id` : db``}
where
${db.unsafe(modequery)}
and items.active = true
${tagFilter}
${fav ? db`and fav_u.user ilike ${user}` : db``}
${!fav && user ? db`and items.username ilike ${user}` : db``}
${mimeSQL}
${hallFilter}
${userHallFilter}
${!session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
${newerThan ? db`and items.id > ${newerThan}` : db``}
${xdFilter}
`;
const total = Number(totalRows[0].total);
const cacheKey = buildCountCacheKey({ modequery, tag, user, hall, mime, fav, session, excludedTags, newerThan, minXd, userHallObj, tagger });
let total = getCachedCount(cacheKey);
if (total === null) {
const totalRows = await db`
select count(distinct items.id) as total
from items
${fav ? db`inner join favorites on favorites.item_id = items.id inner join "user" fav_u on fav_u.id = favorites.user_id` : db``}
where
${db.unsafe(modequery)}
and items.active = true
${tagFilter}
${titleFilter}
${fav ? db`and fav_u.user ilike ${user}` : db``}
${!fav && user ? db`and items.username ilike ${user}` : db``}
${mimeSQL}
${hallFilter}
${userHallFilter}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
${newerThan ? db`and items.id > ${newerThan}` : db``}
${xdFilter}
`;
total = Number(totalRows[0].total);
if (total > 0) setCachedCount(cacheKey, total);
}
if (!total || total === 0) {
return {
@@ -211,7 +288,49 @@ export default {
const act_page = Math.min(page || 1, pages);
const offset = Math.max(0, (act_page - 1) * eps);
const rows = await db`
// ── Deferred-join pagination ──────────────────────────────────────────────
// Step 1: Get only item IDs with all filters + OFFSET applied on the bare
// items table. No expensive JOINs here, so Postgres can use the
// (is_pinned DESC, id DESC) index efficiently even at page 192.
// The fav case still needs the favorites join in step 1 for the WHERE clause.
const pageIdRows = await db`
select items.id, items.is_pinned
from items
${fav ? db`
inner join favorites on favorites.item_id = items.id
inner join "user" fav_u on fav_u.id = favorites.user_id
` : db``}
where
${db.unsafe(modequery)}
and items.active = true
${tagFilter}
${titleFilter}
${fav ? db`and fav_u.user ilike ${user}` : db``}
${!fav && user ? db`and items.username ilike ${user}` : db``}
${mimeSQL}
${hallFilter}
${userHallFilter}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
${newerThan ? db`and items.id > ${newerThan}` : db``}
${xdFilter}
${fav ? db`group by items.id, items.is_pinned` : db``}
order by ${random ? db`random()` : db`items.is_pinned desc, items.id desc`}
offset ${newerThan ? 0 : offset}
limit ${eps}
`;
if (pageIdRows.length === 0) {
// Off the end of the dataset (e.g. stale cached total sent user to a page that no longer exists)
return { success: false, message: "404 - no uploads found" };
}
const pageIds = pageIdRows.map(r => r.id);
// Preserve the page order returned by step 1 after the join scrambles it
const pageOrder = Object.fromEntries(pageIds.map((id, i) => [id, i]));
// Step 2: Enrich only those IDs — expensive JOINs on at most `eps` rows.
const rows = (await db`
select
items.id,
items.mime,
@@ -234,36 +353,23 @@ export default {
from items
left join "user" author_u on author_u."user" = items.username or author_u.login = items.username
left join user_options uo on uo.user_id = author_u.id
left join tags_assign on tags_assign.item_id = items.id
left join tags on tags.id = tags_assign.tag_id
left join favorites on favorites.item_id = items.id
left join "user" fav_u on fav_u.id = favorites.user_id
left join tags_assign ta on ta.item_id = items.id and (ta.tag_id = 1 or ta.tag_id = 2 ${cfg.enable_nsfl ? db`or ta.tag_id = ${cfg.nsfl_tag_id || 3}` : db``})
left join tags badge_t on badge_t.id = ta.tag_id
${user_id ? db`left join user_video_views uvv on uvv.video_id = items.id and uvv.user_id = ${user_id}` : db``}
where
${db.unsafe(modequery)}
and items.active = true
${tagFilter}
${fav ? db`and fav_u.user ilike ${user}` : db``}
${!fav && user ? db`and items.username ilike ${user}` : db``}
${mimeSQL}
${hallFilter}
${userHallFilter}
${!session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
${newerThan ? db`and items.id > ${newerThan}` : db``}
${xdFilter}
where items.id = any(${pageIds})
group by items.id
order by ${random ? db`random()` : db`items.is_pinned desc, items.id desc`}
offset ${newerThan ? 0 : offset}
limit ${eps}
`;
`).sort((a, b) => pageOrder[a.id] - pageOrder[b.id]);
// ─────────────────────────────────────────────────────────────────────────
// Dynamic thumb sizing: only on the unfiltered main feed.
// Profile pages, tag searches, halls, favorites, mime filters all use tier 1 (1×1).
for (const row of rows) {
const meta = xdScoreMeta(row.xd_score);
row.xd_tier = meta.tier;
row.xd_label = meta.label;
}
// Dynamic thumb sizing: applies to the main feed including mime/rating filters.
// Only per-user profiles, tag searches, halls, and favorites disable it.
const isMainFeed = cfg.websrv.enable_dynamic_thumbs
&& !rawUser && !rawTag && !rawHall && !rawUserHall && !rawMime && !fav;
&& !rawUser && !rawTag && !rawHall && !rawUserHall && !fav;
if (isMainFeed) {
for (const row of rows) {
@@ -283,12 +389,21 @@ export default {
for (let i = Math.max(1, act_page - range); i <= Math.min(act_page + range, pages); i++)
cheat.push(i);
const link = lib.genLink({ user, tag, hall: hallObj ? hallObj.slug : hall, mime, type: fav ? 'favs' : 'uploads', path: 'p/', strict: strict });
const link = lib.genLink({ user, tag, hall: hallObj ? hallObj.slug : hall, mime, type: fav ? 'favs' : 'uploads', path: 'p/', strict: strict, tagger });
// Override link for title searches — pagination must use the /tag/title:... prefix
if (isTitleSearch && titleQuery) {
link.main = `/tag/title:${encodeURIComponent(titleQuery)}/`;
link.mainDisplay = `/tag/title:${titleQuery}/`;
link.path = 'p/';
link.suffix = '';
}
// Override link for user hall context
if (userHallObj && userHallOwner) {
const ownerName = userHallObj.owner_name || userHallOwner;
link.main = `/user/${encodeURIComponent(ownerName)}/hall/${encodeURIComponent(userHallObj.slug)}/`;
link.mainDisplay = `/user/${ownerName}/hall/${userHallObj.slug}/`;
link.path = 'p/';
link.suffix = '';
}
@@ -313,9 +428,14 @@ export default {
view_mode: fav ? 'favs' : 'uploads'
};
},
getf0ck: async ({ user: rawUser, tag: rawTag, hall: rawHall, mime: rawMime, itemid: rawItemid, mode, session, strict, exclude, user_id, fav, random, userHall: rawUserHall, userHallOwner: rawUserHallOwner, lang } = {}) => {
getf0ck: async ({ user: rawUser, tag: rawTag, hall: rawHall, mime: rawMime, itemid: rawItemid, mode, ratings, session, strict, exclude, user_id, fav, random, userHall: rawUserHall, userHallOwner: rawUserHallOwner, lang } = {}) => {
const user = rawUser ? lib.escapeLike(decodeURI(rawUser)) : null;
const tag = lib.parseTag(rawTag ?? null);
// --- title: prefix — search items.title instead of the tags table ---
const _decodedTag = rawTag ? decodeURIComponent(rawTag) : '';
const isTitleSearch = _decodedTag.startsWith('title:');
const titleQuery = isTitleSearch ? _decodedTag.substring(6).trim() : null;
const tag = isTitleSearch ? null : lib.parseTag(rawTag ?? null);
let hall = rawHall ?? null;
if (hall) {
const hallData = await db`SELECT name, slug, description FROM halls WHERE slug = ${hall} LIMIT 1`;
@@ -352,10 +472,11 @@ export default {
const strictParams = ((strict || (tag && tag.includes(','))) && tag) ? tag.split(',').map(t => lib.slugify(t)).filter(t => t) : [];
const isStrict = strictParams.length > 0;
const tmp = { user, tag, hall, mime, itemid, strict: strict, userHall: userHallObj || userHallSlug, userHallOwner };
const tmp = { user, tag: isTitleSearch ? _decodedTag : tag, hall, mime, itemid, strict: strict, userHall: userHallObj || userHallSlug, userHallOwner };
const effMode = Number(mode ?? 0);
const modequery = lib.getMode(effMode);
const multiRatingSQL = (Array.isArray(ratings) && ratings.length > 0) ? lib.getMultiRatingMode(ratings) : null;
const modequery = multiRatingSQL ?? lib.getMode(effMode);
if (itemid === null) {
return {
@@ -365,7 +486,10 @@ export default {
}
let tagFilter = db``;
if (tag) {
let titleFilter = db``;
if (isTitleSearch && titleQuery) {
titleFilter = db`and items.title ILIKE ${'%' + titleQuery + '%'} and items.title IS NOT NULL`;
} else if (tag) {
const terms = tag.split(',').map(t => t.trim()).filter(Boolean);
if (terms.length > 0) {
if (isStrict) {
@@ -402,12 +526,13 @@ export default {
${db.unsafe(modequery)}
and items.active = true
${tagFilter}
${titleFilter}
${hallFilter}
${userHallFilter}
${fav ? db`and "user"."user" ilike ${user}` : db``}
${!fav && user ? db`and items.username ilike ${user}` : db``}
${mimeSQL}
${!session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
`;
};
@@ -426,6 +551,9 @@ export default {
uo.display_name as author_display_name,
uo.avatar as author_avatar,
uo.avatar_file as author_avatar_file,
uo.banner_file as author_banner_file,
uo.banner_position as author_banner_position,
uo.banner_size as author_banner_size,
uo.description as author_description,
author_u.id as author_id,
items.is_pinned,
@@ -440,7 +568,7 @@ export default {
where
items.id = ${itemid} and
items.active = true
${!session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
limit 1
`;
@@ -458,18 +586,23 @@ export default {
if (!actitem) {
// Item not found or filtered out - check if it exists but was filtered (for OG meta tags)
if (!session && globalfilter) {
if (!session && getGlobalfilter()) {
const unfilteredItem = await db`
select id from items where id = ${itemid} and active = true limit 1
`;
if (unfilteredItem[0]) {
// Item exists but was filtered - return minimal data for OG tags with blurred thumbnail
const hallSlug = hall && typeof hall === 'object' ? hall.slug : hall;
return {
success: false,
message: "Sorry, this post is currently not visible.",
item: {
id: itemid,
og_thumbnail: `${cfg.websrv.paths.thumbnails}/${itemid}_blur.webp`
og_thumbnail: `${cfg.websrv.paths.thumbnails}/${itemid}_blur.webp`,
og_url: hallSlug
? `https://${cfg.main.url.domain}/h/${encodeURIComponent(hallSlug)}/${itemid}`
: `https://${cfg.main.url.domain}/${itemid}`,
og_description: `Content not visible in current mode`
}
};
}
@@ -556,10 +689,18 @@ export default {
? await db`select uh.name, uh.slug from user_halls uh join user_halls_assign uha on uha.hall_id = uh.id where uha.item_id = ${itemid} and uh.user_id = ${user_id}`
: [];
const link = lib.genLink({ user, tag, hall: (hall && typeof hall === 'object') ? hall.slug : hall, mime, type: fav ? 'favs' : 'uploads', path: '', strict: false });
// Override link for title searches — pagination must use the /tag/title:... prefix
if (isTitleSearch && titleQuery) {
link.main = `/tag/title:${encodeURIComponent(titleQuery)}/`;
link.mainDisplay = `/tag/title:${titleQuery}/`;
link.path = '';
link.suffix = '';
}
// Override link for user hall context
if (userHallObj && userHallOwner) {
const ownerName = userHallObj.owner_name || userHallOwner;
link.main = `/user/${encodeURIComponent(ownerName)}/hall/${encodeURIComponent(userHallObj.slug)}/`;
link.mainDisplay = `/user/${ownerName}/hall/${userHallObj.slug}/`;
link.path = '';
link.suffix = '';
}
@@ -571,6 +712,50 @@ export default {
where "favorites".item_id = ${itemid}
`;
// Detect reposts: items uploaded with bypass_duplicate_check have checksum = `{hash}_bypass_{ts}`
// Find all items (including this one) that share the same base checksum.
let repostItems = [];
if (actitem.checksum && actitem.checksum.includes('_bypass_')) {
const baseChecksum = actitem.checksum.split('_bypass_')[0];
const repostRows = await db`
SELECT id, username, stamp FROM items
WHERE active = true
AND id != ${itemid}
AND (checksum = ${baseChecksum} OR checksum LIKE ${baseChecksum + '_bypass_%'})
ORDER BY id ASC
`;
repostItems = repostRows.map(r => ({ id: r.id, username: r.username, stamp: r.stamp, match_type: 'checksum' }));
} else if (actitem.checksum) {
// Even without bypass, check if other bypass-entries exist with this same hash
const baseChecksum = actitem.checksum;
const repostRows = await db`
SELECT id, username, stamp FROM items
WHERE active = true
AND id != ${itemid}
AND checksum LIKE ${baseChecksum + '_bypass_%'}
ORDER BY id ASC
`;
repostItems = repostRows.map(r => ({ id: r.id, username: r.username, stamp: r.stamp, match_type: 'checksum' }));
}
// Also find visually-similar items via phash, merging with checksum results
if (actitem.phash && actitem.phash !== 'ERROR' && actitem.phash !== 'MISSING') {
try {
const phashMatches = await queue.findallrepostphash(actitem.phash, itemid);
const existingIds = new Set(repostItems.map(r => r.id));
for (const pm of phashMatches) {
if (!existingIds.has(pm.id)) {
repostItems.push({ id: pm.id, username: pm.username, stamp: pm.stamp, match_type: 'phash' });
existingIds.add(pm.id);
}
}
repostItems.sort((a, b) => a.id - b.id);
} catch (e) {
console.error('[GETF0CK] phash repost lookup failed:', e.message);
}
}
// Efficient coverart fallback
const coverartUrl = actitem.has_coverart
? `${cfg.websrv.paths.coverarts}/${actitem.id}.webp`
@@ -596,12 +781,17 @@ export default {
else if (userMode === 2 && isTagged) modeBlocked = true; // Untagged mode, item has tags
if (modeBlocked) {
const hallSlug = hall && typeof hall === 'object' ? hall.slug : hall;
return {
success: false,
message: "Sorry, this post is currently not visible.",
item: {
id: itemid,
og_thumbnail: `${cfg.websrv.paths.thumbnails}/${itemid}${isNsfw ? '_blur' : ''}.webp`
og_thumbnail: `${cfg.websrv.paths.thumbnails}/${itemid}${isNsfw ? '_blur' : ''}.webp`,
og_url: hallSlug
? `https://${cfg.main.url.domain}/h/${encodeURIComponent(hallSlug)}/${itemid}`
: `https://${cfg.main.url.domain}/${itemid}`,
og_description: `Content not visible in current mode`
}
};
}
@@ -624,7 +814,11 @@ export default {
author_display_name: actitem.author_display_name || null,
author_avatar: actitem.author_avatar,
author_avatar_file: actitem.author_avatar_file,
author_banner_file: actitem.author_banner_file,
author_banner_position: actitem.author_banner_position,
author_banner_size: actitem.author_banner_size,
author_description: actitem.author_description,
title: actitem.title || null,
src: {
long: actitem.src,
@@ -632,10 +826,30 @@ export default {
},
thumbnail: `${cfg.websrv.paths.thumbnails}/${actitem.id}.webp`,
og_thumbnail: `${cfg.websrv.paths.thumbnails}/${actitem.id}${(isNsfw || isNsfl) ? '_blur' : ''}.webp`,
// og_url: canonical URL for OG/bots — hall context preserved, plain /<id> as fallback
og_url: (() => {
const hallSlug = hall && typeof hall === 'object' ? hall.slug : hall;
if (hallSlug) return `https://${cfg.main.url.domain}/h/${encodeURIComponent(hallSlug)}/${actitem.id}`;
return `https://${cfg.main.url.domain}/${actitem.id}`;
})(),
// og_description: include rating + uploader for bots (Matrix, Discord, etc.)
og_description: (() => {
const ratingLabel = isNsfl ? 'NSFL' : (isNsfw ? 'NSFW' : (isSfw ? 'SFW' : 'Untagged'));
const titlePart = actitem.title ? ` · "${actitem.title}"` : '';
return `${ratingLabel}${titlePart} · uploaded by ${actitem.username}`;
})(),
coverart: coverartUrl,
dest: actitem.mime === 'video/youtube' ? actitem.dest : `${cfg.websrv.paths.images}/${actitem.dest}`,
dest: (() => {
if (actitem.mime !== 'video/youtube') return `${cfg.websrv.paths.images}/${actitem.dest}`;
if (actitem.dest && actitem.dest.startsWith('yt:')) return actitem.dest;
// dest was corrupted by UUID backfill — recover from src
const ytSrcRegex = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\/?\/?\?(?:\S*?&?v=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/i;
const m = actitem.src && actitem.src.match(ytSrcRegex);
return m ? `yt:${m[1]}` : actitem.dest;
})(),
mime: actitem.mime,
size: lib.formatSize(actitem.size),
checksum: actitem.checksum,
timestamp: {
timeago: lib.timeAgo(new Date(actitem.stamp * 1e3).toISOString(), lang),
timefull: new Date(actitem.stamp * 1e3).toISOString()
@@ -649,7 +863,12 @@ export default {
is_sfw: isSfw,
is_pinned: actitem.is_pinned || false,
is_comments_locked: actitem.is_comments_locked || false,
is_oc: actitem.is_oc || false
is_oc: actitem.is_oc || false,
is_repost: actitem.checksum ? actitem.checksum.includes('_bypass_') : false,
reposts: repostItems,
width: actitem.width || null,
height: actitem.height || null,
original_filename: actitem.original_filename || null
},
title: `${actitem.id} - ${cfg.websrv.domain}`,
pagination: {
@@ -665,10 +884,16 @@ export default {
tmp
};
return data;
}, getRandom: async ({ user: rawUser, tag: rawTag, hall: rawHall, mime: rawMime, mode, fav, session, strict, exclude, userHall: rawUserHall, userHallOwner: rawUserHallOwner } = {}) => {
}, getRandom: async ({ user: rawUser, tag: rawTag, hall: rawHall, mime: rawMime, mode, ratings, fav, session, strict, exclude, userHall: rawUserHall, userHallOwner: rawUserHallOwner } = {}) => {
const user = rawUser ? lib.escapeLike(decodeURI(rawUser)) : null;
const hall = rawHall || null;
const tag = lib.parseTag(rawTag ?? null);
// --- title: prefix — search items.title instead of the tags table ---
const _decodedTag = rawTag ? decodeURIComponent(rawTag) : '';
const isTitleSearch = _decodedTag.startsWith('title:');
const titleQuery = isTitleSearch ? _decodedTag.substring(6).trim() : null;
const tag = isTitleSearch ? null : lib.parseTag(rawTag ?? null);
const mime = (rawMime ?? "");
const userHallSlug = rawUserHall || null;
const userHallOwner = rawUserHallOwner || null;
@@ -699,12 +924,29 @@ export default {
const strictParams = ((strict || (tag && tag.includes(','))) && tag) ? tag.split(',').map(t => lib.slugify(t)).filter(t => t) : [];
const isStrict = strictParams.length > 0;
const baseMode = lib.getMode(mode ?? 0);
const multiRatingSQL = (Array.isArray(ratings) && ratings.length > 0) ? lib.getMultiRatingMode(ratings) : null;
const baseMode = multiRatingSQL ?? lib.getMode(mode ?? 0);
const modequery = baseMode;
let item;
if (fav && user) {
if (isTitleSearch && titleQuery) {
// Title search random: filter by items.title, no tag join needed
item = await db`
SELECT items.id
FROM items
WHERE
${db.unsafe(modequery)}
AND items.active = true
AND items.title ILIKE ${'%' + titleQuery + '%'}
AND items.title IS NOT NULL
${mimeSQL}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
ORDER BY random()
LIMIT 1
`;
} else if (fav && user) {
// Special case: random from user's favorites
item = await db`
select
@@ -719,7 +961,7 @@ export default {
and "user".user ilike ${user}
and items.active = true
${mimeSQL}
${!session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
group by items.id
order by random()
limit 1
@@ -761,7 +1003,7 @@ export default {
${user ? db`and items.username ilike ${user}` : db``}
${hall ? db`and items.id in (select item_id from halls_assign ha join halls h on h.id = ha.hall_id where h.slug = ${hall})` : db``}
${mimeSQL}
${!session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
group by items.id, tags.tag
order by random()
@@ -780,7 +1022,7 @@ export default {
and h.slug = ${hall}
and items.active = true
${mimeSQL}
${!session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
order by random()
limit 1
@@ -801,10 +1043,13 @@ export default {
limit 1
`;
} else {
// Uniform random logic for global requests (no user/tag)
const baseMode = lib.getMode(mode ?? 0);
const modequery = baseMode;
const tagId = (mode === 0 || mode === 1 || mode === 4) ? (mode === 4 ? (cfg.nsfl_tag_id || 3) : (mode === 1 ? 2 : 1)) : null;
// Uniform random logic for global requests (no user/tag/hall)
// When multi-rating SQL is active, use it directly. Otherwise use the tag-join optimisation.
const globalModeQuery = multiRatingSQL ?? lib.getMode(mode ?? 0);
// tagId optimisation only applies for single native modes (not multi-rating)
const tagId = !multiRatingSQL && (mode === 0 || mode === 1 || mode === 4)
? (mode === 4 ? (cfg.nsfl_tag_id || 3) : (mode === 1 ? 2 : 1))
: null;
// If audio is included, we avoid the strict tagId optimization to ensure audio is visible
const useTagIdOpt = tagId && !mimeParts.includes('audio');
const nsfpIds = cfg.nsfp || [];
@@ -821,7 +1066,7 @@ export default {
${mimeSQL}
${checkFilter ? db`AND filter_ta.tag_id IS NULL` : db``}
${excludedTags.length > 0 ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND tag_id = ANY(${excludedTags}::int[]))` : db``}
${!useTagIdOpt ? db`AND ${db.unsafe(modequery)}` : db``}
${!useTagIdOpt ? db`AND ${db.unsafe(globalModeQuery)}` : db``}
ORDER BY random()
LIMIT 1
`;
@@ -884,6 +1129,73 @@ export default {
// Table might not exist yet, gracefully degrade
for (const c of comments) c.files = [];
}
// Fetch poll data for comments that have one
try {
const pollRows = await db`
SELECT
cp.id as poll_id,
cp.comment_id,
cp.question,
cp.expires_at,
COALESCE(cp.is_anonymous, true) as is_anonymous,
json_agg(
json_build_object(
'id', cpo.id,
'text', cpo.text,
'sort_order', cpo.sort_order,
'vote_count', COALESCE(vote_counts.cnt, 0)
) ORDER BY cpo.sort_order ASC, cpo.id ASC
) AS options,
COALESCE(SUM(vote_counts.cnt), 0)::int AS total_votes
FROM comment_polls cp
JOIN comment_poll_options cpo ON cpo.poll_id = cp.id
LEFT JOIN (
SELECT option_id, COUNT(*) AS cnt
FROM comment_poll_votes
GROUP BY option_id
) vote_counts ON vote_counts.option_id = cpo.id
WHERE cp.comment_id = ANY(${commentIds}::int[])
GROUP BY cp.id, cp.comment_id, cp.question, cp.expires_at, cp.is_anonymous
`;
// For non-anonymous polls, fetch voter names
const nonAnonIds = pollRows.filter(p => !p.is_anonymous).map(p => p.poll_id);
let votersByOption = new Map();
if (nonAnonIds.length > 0) {
const voterRows = await db`
SELECT cpv.option_id, u."user" as username, uo.avatar, uo.avatar_file
FROM comment_poll_votes cpv
JOIN public."user" u ON u.id = cpv.user_id
LEFT JOIN public.user_options uo ON uo.user_id = cpv.user_id
WHERE cpv.poll_id = ANY(${nonAnonIds}::int[])
`;
for (const v of voterRows) {
if (!votersByOption.has(v.option_id)) votersByOption.set(v.option_id, []);
votersByOption.get(v.option_id).push({ username: v.username, avatar: v.avatar, avatar_file: v.avatar_file });
}
}
const pollMap = new Map();
for (const p of pollRows) {
const options = p.is_anonymous
? p.options
: p.options.map(o => ({ ...o, voters: votersByOption.get(o.id) || [] }));
pollMap.set(p.comment_id, {
id: p.poll_id,
question: p.question,
expires_at: p.expires_at,
is_anonymous: p.is_anonymous,
options,
total_votes: parseInt(p.total_votes) || 0,
user_vote_option_id: null
});
}
for (const c of comments) {
c.poll = pollMap.get(c.id) || null;
}
} catch (e) {
console.error('[POLLS] getComments poll fetch error:', e.message, e.code);
for (const c of comments) c.poll = null;
}
}
console.log(`[${new Date().toISOString()}] [GETCOMMENTS] Fetched ${comments.length} comments for item ${itemId} in ${Date.now() - tStart}ms`);
@@ -972,14 +1284,12 @@ export default {
? db`AND NOT EXISTS (SELECT 1 FROM tags_assign ta_ex WHERE ta_ex.item_id = i.id AND ta_ex.tag_id = ANY(${excludedTags}::int[]))`
: db``;
// Build mode condition using alias 'i' (getMode uses raw 'items' table name, incompatible with subquery alias)
const modeNum = Number(mode) || 0;
const modeFilter = modeNum === 1 ? db`AND i.id IN (SELECT item_id FROM tags_assign WHERE tag_id = 2)`
: modeNum === 2 ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = i.id)`
: modeNum === 3 ? db``
: db`AND i.id IN (SELECT item_id FROM tags_assign WHERE tag_id = 1)`; // default: sfw
// Filter halls by their rating column to match the current mode
// Filter halls by their rating column to match the current mode.
// The hall's own rating is the source of truth for mode gating — the old
// item-level modeFilter (tag_id check) caused NSFW halls to show 0 posts
// when items didn't carry the exact NSFW tag_id.
// mode 0=sfw -> rating='sfw', mode 1=nsfw -> rating='nsfw', mode 4=nsfl -> rating='nsfl'
// mode 3=all and mode 2=untagged show all halls
const hallRating = modeNum === 0 ? 'sfw' : modeNum === 1 ? 'nsfw' : modeNum === 4 ? 'nsfl' : null;
@@ -1005,7 +1315,6 @@ export default {
FROM halls_assign ha
JOIN items i ON i.id = ha.item_id
WHERE i.active = true
${modeFilter}
${userExcludeFilter}
GROUP BY ha.hall_id
) counts ON counts.hall_id = h.id
@@ -1267,5 +1576,7 @@ export default {
},
computeXdScore,
xdScoreMeta
xdScoreMeta,
// Bust the count cache (call after a new upload is accepted so page totals stay accurate)
clearCountCache: () => countCache.clear()
};

View File

@@ -45,7 +45,7 @@ export default (router, tpl) => {
return res.reply({ code: 429, body: msg });
}
if (!username || !password || password.length < 20) {
if (!username || !password) {
return fail("Invalid username or password.");
}
@@ -507,7 +507,8 @@ export default (router, tpl) => {
update "user"
set banned = false,
ban_reason = null,
ban_expires = null
ban_expires = null,
last_seen = ${~~(Date.now() / 1e3)}
where id = ${+user_id}
`;
@@ -803,8 +804,11 @@ export default (router, tpl) => {
// User Management Routes
router.get(/^\/admin\/users\/?$/, lib.auth, async (req, res) => {
const q = req.url.qs?.q || '';
const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
const rawQ = req.url.qs?.q || '';
// Exact match mode: strip surrounding double quotes and match exactly
const exactMatch = rawQ.startsWith('"') && rawQ.endsWith('"') && rawQ.length > 2;
const q = exactMatch ? rawQ.slice(1, -1) : rawQ;
const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
const limit = 50;
const offset = (page - 1) * limit;
@@ -816,7 +820,10 @@ const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
(SELECT token FROM invite_tokens WHERE used_by = u.id ORDER BY created_at DESC LIMIT 1) as reg_method
FROM "user" u
LEFT JOIN user_options uo ON uo.user_id = u.id
${q ? db`WHERE u.login ILIKE ${'%' + lib.escapeLike(q) + '%'} OR u.user ILIKE ${'%' + lib.escapeLike(q) + '%'} OR u.email ILIKE ${'%' + lib.escapeLike(q) + '%'}` : db``}
${q ? (exactMatch
? db`WHERE lower(u.login) = lower(${q}) OR lower(u.user) = lower(${q}) OR lower(u.email) = lower(${q})`
: db`WHERE u.login ILIKE ${'%' + lib.escapeLike(q) + '%'} OR u.user ILIKE ${'%' + lib.escapeLike(q) + '%'} OR u.email ILIKE ${'%' + lib.escapeLike(q) + '%'}`
) : db``}
),
ghost_users AS (
SELECT
@@ -825,7 +832,10 @@ const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
NULL::text as avatar_file, NULL::varchar as display_name, 0 as force_comment_display_mode, 0 as comment_display_mode, 'Legacy' as reg_method
FROM items i
WHERE NOT EXISTS (SELECT 1 FROM "user" u WHERE u.login = i.username OR u.user = i.username)
${q ? db`AND (i.username ILIKE ${'%' + lib.escapeLike(q) + '%'})` : db``}
${q ? (exactMatch
? db`AND lower(i.username) = lower(${q})`
: db`AND (i.username ILIKE ${'%' + lib.escapeLike(q) + '%'})`
) : db``}
GROUP BY i.username
),
all_users AS (
@@ -867,13 +877,19 @@ const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
const totalCountActual = await db`
SELECT COUNT(*) as c FROM "user" u
${q ? db`WHERE u.login ILIKE ${'%' + lib.escapeLike(q) + '%'} OR u.user ILIKE ${'%' + lib.escapeLike(q) + '%'} OR u.email ILIKE ${'%' + lib.escapeLike(q) + '%'}` : db``}
${q ? (exactMatch
? db`WHERE lower(u.login) = lower(${q}) OR lower(u.user) = lower(${q}) OR lower(u.email) = lower(${q})`
: db`WHERE u.login ILIKE ${'%' + lib.escapeLike(q) + '%'} OR u.user ILIKE ${'%' + lib.escapeLike(q) + '%'} OR u.email ILIKE ${'%' + lib.escapeLike(q) + '%'}`
) : db``}
`;
const totalCountGhost = await db`
SELECT COUNT(DISTINCT i.username) as c
FROM items i
WHERE NOT EXISTS (SELECT 1 FROM "user" u WHERE u.login = i.username OR u.user = i.username)
${q ? db`AND (i.username ILIKE ${'%' + lib.escapeLike(q) + '%'})` : db``}
${q ? (exactMatch
? db`AND lower(i.username) = lower(${q})`
: db`AND (i.username ILIKE ${'%' + lib.escapeLike(q) + '%'})`
) : db``}
`;
const total = parseInt(totalCountActual[0].c) + parseInt(totalCountGhost[0].c);
@@ -952,11 +968,57 @@ const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
}
});
router.post(/^\/api\/v2\/admin\/users\/set-role\/?$/, lib.auth, async (req, res) => {
try {
const { user_id, role } = req.post;
if (!user_id) throw new Error('Missing user_id');
if (!['user', 'mod', 'admin'].includes(role)) throw new Error('Invalid role. Must be user, mod, or admin.');
// Fetch target
const target = await db`SELECT id, login FROM "user" WHERE id = ${+user_id} LIMIT 1`;
if (!target.length) throw new Error('User not found.');
if (target[0].login === 'deleted_user') throw new Error('The deleted_user account is protected.');
// Prevent self-demotion
if (+user_id === req.session.id && role !== 'admin') {
throw new Error('You cannot change your own role away from admin.');
}
const isAdmin = role === 'admin';
const isMod = role === 'mod';
await db`
UPDATE "user"
SET admin = ${isAdmin}, is_moderator = ${isMod}
WHERE id = ${+user_id}
`;
// Invalidate sessions so permissions refresh on next login
await db`DELETE FROM user_sessions WHERE user_id = ${+user_id}`;
await audit.log(req.session.id, 'admin_set_role', 'user', +user_id, {
target_login: target[0].login,
role
});
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({
success: true,
role,
msg: `Role for "${target[0].login}" set to ${role}.`
}));
} catch (err) {
console.error('[ADMIN] Set role failed:', err);
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg: err.message }));
}
});
router.post(/^\/api\/v2\/admin\/users\/lock-layout\/?$/, lib.auth, async (req, res) => {
try {
const { user_id, mode, lock } = req.post;
if (!user_id) throw new Error('Missing user_id');
const isLocked = lock === true || lock === 'true' || lock === 1;
const targetMode = parseInt(mode, 10);
@@ -1257,6 +1319,136 @@ const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
});
router.post(/^\/api\/v2\/admin\/users\/rename\/?$/, lib.auth, async (req, res) => {
try {
const { user_id, new_username } = req.post;
if (!user_id) throw new Error('Missing user_id');
if (!new_username || !new_username.trim()) throw new Error('Missing new_username');
const newName = new_username.trim();
// Validate format (same rules as registration)
if (!/^[a-zA-Z0-9._-]+$/.test(newName)) {
throw new Error('Invalid username. Only A-Z, 0-9, _, -, and . are allowed.');
}
if (newName.length < 2 || newName.length > 32) {
throw new Error('Username must be between 2 and 32 characters.');
}
// Get current user info
const target = await db`SELECT id, login, "user" FROM "user" WHERE id = ${+user_id} LIMIT 1`;
if (!target.length) throw new Error('User not found');
if (target[0].login === 'deleted_user') throw new Error('The deleted_user account is protected and cannot be renamed.');
const oldLogin = target[0].login;
const oldUser = target[0].user;
const newLogin = newName.toLowerCase();
if (newLogin === oldLogin && newName === oldUser) throw new Error('New username is the same as the current one.');
// Check for conflicts
const conflict = await db`SELECT id FROM "user" WHERE (lower(login) = ${newLogin} OR lower("user") = lower(${newName})) AND id != ${+user_id} LIMIT 1`;
if (conflict.length) throw new Error(`Username "${newName}" is already taken.`);
await db.begin(async sql => {
// 1. Update the user record
await sql`UPDATE "user" SET login = ${newLogin}, "user" = ${newName} WHERE id = ${+user_id}`;
// 2. Update items.username (matches both old login and old display name)
await sql`UPDATE items SET username = ${newLogin} WHERE username ILIKE ${oldLogin} OR username ILIKE ${oldUser}`;
// 3. Clear old login_attempts so the new name starts clean
await sql`DELETE FROM login_attempts WHERE username = ${oldLogin}`;
});
// Invalidate all sessions so the user must re-log with the new name
await db`DELETE FROM user_sessions WHERE user_id = ${+user_id}`;
// Log it in audit
await audit.log(req.session.id, 'admin_rename_user', 'user', +user_id, {
old_login: oldLogin,
new_login: newLogin,
old_user: oldUser,
new_user: newName
});
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({
success: true,
new_login: newLogin,
new_user: newName,
msg: `User renamed from "${oldLogin}" to "${newLogin}". All uploads updated. Sessions invalidated.`
}));
} catch (err) {
console.error('[ADMIN] Rename failed:', err);
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg: err.message }));
}
});
router.post(/^\/api\/v2\/admin\/users\/create\/?$/, lib.auth, async (req, res) => {
try {
let { username, email, password, role } = req.post;
if (!username || !username.trim()) throw new Error('Username is required.');
username = username.trim();
if (!/^[a-zA-Z0-9._-]+$/.test(username)) {
throw new Error('Username contains invalid characters. Only A-Z, 0-9, _, -, and . are allowed.');
}
if (username.length < 2 || username.length > 32) {
throw new Error('Username must be between 2 and 32 characters.');
}
if (!password || password.length < 20) {
throw new Error('Password must be at least 20 characters long.');
}
// Check for existing user
const existing = await db`
SELECT id FROM "user"
WHERE lower(login) = lower(${username}) OR lower("user") = lower(${username})
${email ? db`OR (email IS NOT NULL AND lower(email) = lower(${email}))` : db``}
LIMIT 1
`;
if (existing.length) throw new Error('Username or email is already taken.');
const isAdmin = role === 'admin';
const isMod = role === 'mod';
const hash = await lib.hash(password);
const ts = ~~(Date.now() / 1e3);
const { getDefaultLayout } = await import('../settings.mjs');
const newUser = await db`
INSERT INTO "user" (login, password, "user", created_at, admin, is_moderator, email, activated, activation_token)
VALUES (
${username.toLowerCase()}, ${hash}, ${username},
to_timestamp(${ts}), ${isAdmin}, ${isMod},
${email || null}, true, NULL
)
RETURNING id, login
`;
const userId = newUser[0].id;
await db`
INSERT INTO user_options (user_id, mode, theme, fullscreen, avatar, avatar_file, use_new_layout, disable_autoplay, disable_swiping, use_alternative_infobox)
VALUES (${userId}, 3, 'amoled', 0, NULL, 'default.png', ${getDefaultLayout() === 'modern'}, ${cfg.websrv.enable_autoplay === false}, ${cfg.websrv.enable_swiping === false}, ${cfg.websrv.user_alternative_infobox !== false})
`;
await audit.log(req.session.id, 'admin_create_user', 'user', userId, {
new_login: username.toLowerCase(),
role: role || 'user'
});
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({
success: true,
user_id: userId,
username: username.toLowerCase(),
msg: `User "${username.toLowerCase()}" created successfully.`
}));
} catch (err) {
console.error('[ADMIN] Create user failed:', err);
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg: err.message }));
}
});
// About page text editor
router.get(/^\/admin\/about\/?$/, lib.auth, async (req, res) => {
const settings = await db`SELECT value FROM site_settings WHERE key = 'about_text' LIMIT 1`;
@@ -1422,6 +1614,9 @@ const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
// Chat Manager
router.get(/^\/admin\/chat\/?$/, lib.auth, async (req, res) => {
if (!cfg.websrv.enable_global_chat) {
return res.redirect("/admin");
}
res.reply({
body: tpl.render('admin/chat', {
session: req.session,
@@ -1431,5 +1626,45 @@ const page = Math.max(1, parseInt(req.url.qs?.page) || 1);
});
});
// Koepfe Manager
router.get(/^\/admin\/koepfe\/?$/, lib.auth, async (req, res) => {
res.reply({
body: tpl.render('admin/koepfe', { session: req.session, tmp: null }, req)
});
});
router.get(/^\/api\/v2\/admin\/koepfe\/?$/, lib.auth, async (req, res) => {
try {
const fs = (await import('fs')).promises;
const path = await import('path');
const kDir = cfg.paths.koepfe;
const files = await fs.readdir(kDir).catch(() => []);
const koepfeFiles = files.filter(f => /\.(png|jpe?g|gif|webp|avif)$/i.test(f)).map(f => ({
filename: f,
url: '/s/koepfe/' + f
}));
if (res.json) return res.json({ koepfe: koepfeFiles });
return res.writeHead(200, {'Content-Type': 'application/json'}).end(JSON.stringify({ koepfe: koepfeFiles }));
} catch (e) {
if (res.json) return res.json({ success: false, msg: e.message });
return res.writeHead(500, {'Content-Type': 'application/json'}).end(JSON.stringify({ success: false, msg: e.message }));
}
});
router.post(/^\/api\/v2\/admin\/koepfe\/delete\/?$/, lib.auth, async (req, res) => {
try {
const { filename } = req.post || req.body || {};
if (!filename || filename.includes('..') || filename.includes('/')) throw new Error('Invalid filename');
const fs = (await import('fs')).promises;
const path = await import('path');
await fs.unlink(path.join(cfg.paths.koepfe, filename));
if (res.json) return res.json({ success: true });
return res.writeHead(200, {'Content-Type': 'application/json'}).end(JSON.stringify({ success: true }));
} catch (e) {
if (res.json) return res.json({ success: false, msg: e.message });
return res.writeHead(500, {'Content-Type': 'application/json'}).end(JSON.stringify({ success: false, msg: e.message }));
}
});
return router;
}

View File

@@ -1,6 +1,7 @@
import f0cklib from "../routeinc/f0cklib.mjs";
import url from "url";
import cfg from "../config.mjs";
import { createI18n } from "../i18n.mjs";
export default (router, tpl) => {
router.get(/\/ajax\/item\/(?<itemid>\d+)/, async (req, res) => {
@@ -31,11 +32,14 @@ export default (router, tpl) => {
if (cfg.main.development) console.log(`[${new Date().toISOString()}] [AJAX] Starting item load for ${req.params.itemid}`);
const isRandom = query.random === '1' || req.cookies.random_mode === '1';
const ratingsRaw = req.cookies.ratings;
const ratingsArr = ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null;
const itemid = req.params.itemid || req.url.pathname.match(/\/ajax\/item\/(\d+)/)?.[1];
const data = await f0cklib.getf0ck({
itemid: itemid,
mode: query.mode !== undefined ? +query.mode : req.mode,
ratings: ratingsArr,
session: !!req.session,
url: contextUrl,
user: query.user,
@@ -54,9 +58,17 @@ export default (router, tpl) => {
const tAjaxFetch = Date.now();
if (!data.success) {
const reqMode = (query.mode !== undefined ? +query.mode : req.mode) ?? 0;
const modeLabels = { 0: 'SFW', 1: 'NSFW', 2: 'Untagged', 4: 'NSFL' };
const errorModeLabel = (req.session && reqMode !== 3) ? (modeLabels[reqMode] || null) : null;
const { t: tErr } = createI18n(req.session?.language || req.lang || 'en');
const errorHtml = tpl.render('error-partial', {
message: data.message || '404 - Not f0cked',
tmp: null
message: tErr('error.post_not_visible'),
tmp: null,
session: req.session ? { ...req.session } : false,
error_mode_label: errorModeLabel,
error_filter_hint: errorModeLabel ? tErr('error.filter_hint', { mode: `<strong>${errorModeLabel}</strong>` }) : null,
error_filter_hint_link: tErr('error.filter_hint_link')
}, req);
return res.reply({
headers: { 'Content-Type': 'application/json' },
@@ -126,7 +138,7 @@ export default (router, tpl) => {
const item = data.item;
data.is_mod_or_admin = !!(session && (session.admin || session.is_moderator));
data.can_manage_item = !!(session && (session.admin || session.is_moderator || session.user === item.username));
data.can_extract_meta = !!(item.mime && item.mime.indexOf('flash') === -1 && item.mime.indexOf('youtube') === -1);
data.can_extract_meta = !!(item.mime && item.mime.indexOf('flash') === -1 && !(item.mime.startsWith('application/') && cfg.mimes[item.mime] && !['swf', 'pdf'].includes(cfg.mimes[item.mime])));
data.user_has_favorited = !!(session && Array.isArray(item.favorites) && item.favorites.some(f => f.user === session.user));
data.halls_slugs = Array.isArray(item.halls) ? item.halls.map(h => h.slug).join(',') : '';
data.user_halls_slugs = Array.isArray(item.user_halls) ? item.user_halls.map(h => h.slug).join(',') : '';
@@ -135,9 +147,11 @@ export default (router, tpl) => {
data.item_rating_label = item.is_nsfl ? 'NSFL' : (item.is_nsfw ? 'NSFW' : (item.is_sfw ? 'SFW' : '?'));
data.item_username_lower = (item.username || '').toLowerCase();
data.is_flash_item = !!(item.mime && (item.mime.indexOf('flash') !== -1 || item.mime.indexOf('shockwave') !== -1));
data.is_archive_item = !!(item.mime && item.mime.startsWith('application/') && cfg.mimes[item.mime] && !['swf', 'pdf'].includes(cfg.mimes[item.mime]));
data.current_hall_slug = (data.tmp && data.tmp.hall && typeof data.tmp.hall === 'object') ? data.tmp.hall.slug : (data.tmp && data.tmp.hall ? data.tmp.hall : '');
data.current_user_hall_slug = (data.tmp && data.tmp.userHall && typeof data.tmp.userHall === 'object') ? data.tmp.userHall.slug : (data.tmp && data.tmp.userHall ? data.tmp.userHall : '');
data.current_user_hall_owner = (data.tmp && data.tmp.userHallOwner) ? data.tmp.userHallOwner : '';
data.item_has_dimensions = !!(item.width && item.height);
}
// Render both the item content and the pagination
@@ -191,14 +205,19 @@ export default (router, tpl) => {
const page = parseInt(query.page) || 1;
const isRandom = query.random === '1' || req.cookies.random_mode === '1';
const ratingsRaw = req.cookies.ratings;
const ratingsArr = ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null;
const data = await f0cklib.getf0cks({
page: page,
tag: query.tag || null,
hall: query.hall || null,
user: query.user || null,
userHall: query.userHall || null,
userHallOwner: query.userHallOwner || null,
mime: query.mime || (req.cookies.mime || null),
mode: query.mode !== undefined ? +query.mode : req.mode,
ratings: ratingsArr,
session: !!req.session,
exclude: req.session ? (req.session.excluded_tags || []) : [],
user_id: req.session?.id,
@@ -207,7 +226,8 @@ export default (router, tpl) => {
strict: query.strict === '1' || query.strict === 'true' || req.session?.strict_mode,
explicitStrict: query.strict === '1' || query.strict === 'true',
newer: query.newer || null,
minXdScore: req.session?.min_xd_score || 0
minXdScore: req.session?.min_xd_score || 0,
tagger: query.tagger || null
});
if (!data.success) {
@@ -252,7 +272,7 @@ export default (router, tpl) => {
return res.reply({
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
'Cache-Control': 'no-cache, must-revalidate, proxy-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
},

View File

@@ -10,7 +10,7 @@ import audit from '../../audit.mjs';
import { parseMultipart, collectBody } from '../../multipart.mjs';
const allowedMimes = ["audio", "image", "video", "%"];
const globalfilter = cfg.nsfp?.length ? cfg.nsfp.map(n => `tag_id = ${n}`).join(' or ') : null;
const getGlobalfilter = () => cfg.nsfp?.length ? cfg.nsfp.map(n => `tag_id = ${n}`).join(' or ') : null;
const metaCache = new Map();
const MAX_META_CACHE = 2000;
@@ -299,9 +299,49 @@ export default router => {
}
});
// Allow authenticated clients to push metadata they fetched client-side (e.g. YouTube oEmbed
// fetched directly from the browser, bypassing Tor/proxy consent walls).
group.post(/\/meta\/cache$/, lib.loggedin, async (req, res) => {
if (!cfg.websrv.web_meta_extraction) {
return res.json({ success: false, msg: 'Metadata extraction is disabled' }, 403);
}
try {
const body = await collectBody(req);
const payload = JSON.parse(body.toString());
const { url, meta } = payload || {};
if (!url || !meta || !meta.title) {
return res.json({ success: false, msg: 'url and meta.title required' }, 400);
}
// Only accept YouTube URLs to prevent arbitrary cache poisoning
if (!/(youtube\.com|youtu\.be)/i.test(url)) {
return res.json({ success: false, msg: 'Only YouTube URLs accepted' }, 400);
}
// Sanitise — only store known-safe fields
const safeMeta = {
title: String(meta.title).substring(0, 500),
site_name: 'youtube.com',
author: meta.author ? String(meta.author).substring(0, 200) : 'Unknown'
};
metaCache.set(url, safeMeta);
if (metaCache.size > MAX_META_CACHE) {
const first = metaCache.keys().next().value;
metaCache.delete(first);
}
try {
await db`INSERT INTO meta_cache (url, data) VALUES (${url}, ${safeMeta})
ON CONFLICT (url) DO UPDATE SET data = EXCLUDED.data, created_at = CURRENT_TIMESTAMP`;
} catch (err) {
console.error('[META-CACHE] DB save failed:', err);
}
return res.json({ success: true });
} catch (err) {
return res.json({ success: false, msg: 'Invalid request body' }, 400);
}
});
// F-002 Security: Require authentication to prevent SSRF via arbitrary URL fetching.
// Guests use cached entries from DB (populated by authenticated user requests).
group.get(/\/meta\/fetch$/, lib.loggedin, async (req, res) => {
// Guests may read from the cache (in-memory or DB); only authenticated users trigger real outbound fetches.
group.get(/\/meta\/fetch$/, async (req, res) => {
if (!cfg.websrv.web_meta_extraction) {
return res.json({ success: false, msg: 'Metadata extraction is disabled' }, 403);
}
@@ -325,6 +365,11 @@ export default router => {
console.error('[META-CACHE] DB lookup failed:', err);
}
// Cache miss — require auth to perform real outbound fetch (SSRF prevention)
if (!req.session) {
return res.json({ success: false, msg: 'Not cached' }, 401);
}
const setCache = async (u, m) => {
if (!m || !m.title) return;
metaCache.set(u, m);
@@ -352,34 +397,71 @@ export default router => {
? cfg.main.socks.replace(/^socks5:\/\//, 'socks5h://')
: null;
// 1. YouTube: go straight to oEmbed — faster and more reliable than yt-dlp for these
// 1. YouTube: try oEmbed first (fast), then fall through to yt-dlp on failure
if (isYouTube) {
try {
const oembedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(url)}&format=json`;
// Do NOT use --fail: non-2xx responses (e.g. age-restricted/private videos) still
// return valid JSON we can attempt to parse. Use ignoreExitCode so we always get output.
const { stdout: oembedOut } = await queue.spawn('curl', [
'-s', '--max-time', '10', '--fail',
'--user-agent', 'Mozilla/5.0 (compatible; oEmbed)',
'-s', '--max-time', '15',
'--user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
...(socksH ? ['--proxy', socksH] : []),
oembedUrl
]);
], { ignoreExitCode: true });
if (oembedOut && oembedOut.trim()) {
const data = JSON.parse(oembedOut);
if (data.title) {
const meta = {
title: data.title,
site_name: 'youtube.com',
author: data.author_name || 'Unknown'
};
await setCache(url, meta);
return res.json({
success: true,
meta
});
const trimmed = oembedOut.trim();
// YouTube often returns HTML (consent/cookie walls, CAPTCHAs, geo-blocks)
// instead of JSON when accessed through a proxy — skip those gracefully.
if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
console.warn(`[META-FETCH] YouTube oEmbed returned non-JSON (likely HTML wall), falling back to yt-dlp`);
} else {
const data = JSON.parse(trimmed);
if (data.title) {
const meta = {
title: data.title,
site_name: 'youtube.com',
author: data.author_name || 'Unknown'
};
await setCache(url, meta);
return res.json({ success: true, meta });
}
}
}
} catch (oembedErr) {
console.error(`[META-FETCH] YouTube oEmbed failed:`, oembedErr.message || oembedErr);
console.warn(`[META-FETCH] YouTube oEmbed failed, will try yt-dlp:`, oembedErr.message || oembedErr);
}
// oEmbed failed — fall back to yt-dlp for YouTube (handles age-restricted, private, etc.)
for (let attempt = 1; attempt <= 2; attempt++) {
try {
const { stdout: ytOut } = await queue.spawn('yt-dlp', [
...proxyArgs,
'--quiet',
'--no-warnings',
'--js-runtimes', 'node',
'--print', '%(title)s',
'--print', '%(uploader)s',
'--skip-download',
url
]);
const ytLines = ytOut.trim().split('\n');
const ytTitle = ytLines[0] ? ytLines[0].trim() : '';
if (ytTitle) {
const meta = {
title: ytTitle,
site_name: 'youtube.com',
author: ytLines[1] ? ytLines[1].trim() : 'Unknown'
};
await setCache(url, meta);
return res.json({ success: true, meta });
}
} catch (ytErr) {
if (attempt < 2) { await sleep(1000); continue; }
console.error(`[META-FETCH] YouTube yt-dlp fallback failed:`, ytErr.message || ytErr);
}
}
return res.json({ success: false, msg: 'Failed to extract YouTube metadata' }, 500);
}
@@ -496,7 +578,9 @@ export default router => {
const userHallOwner = req.url.qs.userHallOwner || null;
const isFav = req.url.qs.fav === 'true';
const isStrict = req.url.qs.strict === '1';
const mode = req.session?.mode ?? 0;
const mode = req.mode ?? 0; // Use req.mode (set by middleware) for consistency with all other routes
const ratingsRaw = req.cookies.ratings;
const ratingsArr = ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null;
const data = await f0cklib.getRandom({
user,
@@ -507,6 +591,7 @@ export default router => {
mime,
fav: isFav,
mode,
ratings: ratingsArr && ratingsArr.length > 0 ? ratingsArr : null,
strict: isStrict,
session: !!req.session,
exclude: req.session?.excluded_tags || []
@@ -519,41 +604,61 @@ export default router => {
});
}
// API expects { success: true, items: { id: ... } } (based on f0ck.js usage)
// The old query returned full item row. f0cklib.getRandom returns { itemid: ... } or { itemid: ... } (actually it returns { itemid: ... } on success)
const rows = await db`
SELECT *
FROM "items"
WHERE id = ${data.itemid} AND active = true
LIMIT 1
`;
const item = rows[0];
// We need to fetch the item details if the frontend expects them?
// Looking at f0ck.js:
// if (data.success && data.items && data.items.id) { loadItemAjax(`/${data.items.id}`, true); }
// So it only really needs the ID.
if (!item) {
return res.json({
success: false,
items: []
});
}
const isYouTube = item.mime === 'video/youtube';
const ytSrcRegex = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\/?\/?\?(?:\S*?&?v=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/i;
let ytDest = item.dest;
if (isYouTube && (!ytDest || !ytDest.startsWith('yt:'))) {
const m = item.src && item.src.match(ytSrcRegex);
if (m) ytDest = `yt:${m[1]}`;
}
const relativeDest = isYouTube ? ytDest : `${cfg.websrv.paths.images}/${item.dest}`;
const directUrl = isYouTube ? ytDest : `${cfg.main.url.full}${cfg.websrv.paths.images}/${item.dest}`;
const { username, src, xd_score, ...safeItem } = item;
return res.json({
success: true,
items: { id: data.itemid }
items: {
...safeItem,
id: item.id,
dest: relativeDest,
url: directUrl,
direct_url: directUrl
}
});
});
group.get(/\/orakel\/user$/, async (req, res) => {
try {
const now = ~~(Date.now() / 1000);
const thirtyDaysAgo = now - 2592000; // 30 days in seconds
const sevenDaysAgo = now - 604800; // 7 days in seconds
// Tiered selection from user.last_seen (updated fire-and-forget on every authenticated request):
// Tier 0 — active in last 15 minutes
// Tier 1 — active in last 24 hours
// Tier 2 — active in last 30 days (includes lurkers — anyone who visited the site)
// Flat random pick from all users seen in the last 7 days.
// No tiered bias — gives a proper pool of recently-active users
// rather than always favouring whoever is online right now.
// Banned users are always excluded.
let activeUsers = await db`
SELECT "user"."user", "user".id, uo.display_name
FROM "user"
LEFT JOIN user_options uo ON uo.user_id = "user".id
WHERE "user".last_seen > ${thirtyDaysAgo}
WHERE "user".last_seen > ${sevenDaysAgo}
AND "user".banned = false
ORDER BY (CASE
WHEN "user".last_seen > ${now - 900} THEN 0
WHEN "user".last_seen > ${now - 86400} THEN 1
ELSE 2
END), RANDOM()
ORDER BY RANDOM()
LIMIT 1
`;
@@ -748,6 +853,28 @@ export default router => {
}
});
group.get(/\/items\/suggest$/, async (req, res) => {
const searchString = req.url.qs.q;
if (!searchString || searchString.length < 1) {
return res.json({ success: false, suggestions: [] });
}
try {
const items = await db`
SELECT id, title
FROM items
WHERE title IS NOT NULL
AND active = true
AND title ILIKE ${'%' + searchString + '%'}
ORDER BY id DESC
LIMIT 8
`;
return res.json({ success: true, suggestions: items });
} catch (err) {
return res.json({ success: false, error: 'Item title suggestion error', suggestions: [] });
}
});
// tags lol
group.put(/\/tags\/rename\/(?<tagname>.*)/, lib.modAuth, async (req, res) => {
@@ -798,6 +925,33 @@ export default router => {
});
// PATCH /api/v2/items/:id/title — set or clear the title for an item
// Allowed by: item owner, moderators, admins
group.patch(/\/items\/(?<id>\d+)\/title$/, lib.loggedin, async (req, res) => {
const id = +req.params.id;
if (!id) return res.json({ success: false, msg: 'Invalid item id' }, 400);
// Fetch item to check ownership
const rows = await db`SELECT id, username FROM items WHERE id = ${id} AND active = true LIMIT 1`;
if (!rows.length) return res.json({ success: false, msg: 'Item not found' }, 404);
const item = rows[0];
const isOwner = req.session.user === item.username;
const isMod = !!(req.session.is_moderator || req.session.admin);
if (!isOwner && !isMod) return res.json({ success: false, msg: 'Forbidden' }, 403);
// Accept title from JSON or URL-encoded body
let rawTitle = req.post?.title ?? req.body?.title ?? null;
if (rawTitle !== null) rawTitle = String(rawTitle).trim();
// Empty string → null (clears the title)
const title = (rawTitle === '' || rawTitle === null) ? null : rawTitle.substring(0, 500);
await db`UPDATE items SET title = ${title} WHERE id = ${id}`;
return res.json({ success: true, title });
});
group.post(/\/admin\/deletepost$/, lib.modAuth, async (req, res) => {
if (req.post.postid === undefined || req.post.postid === null) {
return res.json({
@@ -1045,12 +1199,22 @@ export default router => {
const currentRatingId = existingRating.length > 0 ? existingRating[0].tag_id : null;
let newRatingId;
if (currentRatingId === 1) {
newRatingId = 2; // SFW -> NSFW
} else if (currentRatingId === 2) {
newRatingId = cfg.enable_nsfl ? nsfl_id : 1; // NSFW -> NSFL (if enabled) or SFW
const reqRating = req.body?.rating || req.post?.rating || req.url?.qs?.rating;
if (reqRating === 'sfw') {
newRatingId = 1;
} else if (reqRating === 'nsfw') {
newRatingId = 2;
} else if (reqRating === 'nsfl') {
newRatingId = nsfl_id;
} else {
newRatingId = 1; // NSFL or none -> SFW
// fallback to cycling
if (currentRatingId === 1) {
newRatingId = 2; // SFW -> NSFW
} else if (currentRatingId === 2) {
newRatingId = cfg.enable_nsfl ? nsfl_id : 1; // NSFW -> NSFL (if enabled) or SFW
} else {
newRatingId = 1; // NSFL or none -> SFW
}
}
await db.begin(async sql => {
@@ -1063,12 +1227,10 @@ export default router => {
VALUES (${itemid}, ${newRatingId}, ${req.session.id})
`;
// If switching to NSFW/NSFL, ensure blurred thumbnail exists
if (newRatingId === 2 || newRatingId === nsfl_id) {
await queue.genBlurredThumbnail(itemid).catch(err => {
console.error(`[RATING_TOGGLE] Blurred thumbnail generation failed for ${itemid}:`, err);
});
}
// Ensure blurred thumbnail exists
await queue.genBlurredThumbnail(itemid).catch(err => {
console.error(`[RATING_TOGGLE] Blurred thumbnail generation failed for ${itemid}:`, err);
});
});
const newRating = newRatingId === 1 ? 'sfw' : (newRatingId === 2 ? 'nsfw' : 'nsfl');

View File

@@ -3,6 +3,7 @@ import lib from '../../lib.mjs';
import cfg from '../../config.mjs';
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
// Note: Avatar upload/delete is handled by middleware in index.mjs via avatar_handler.mjs
// These routes remain for other settings API endpoints
@@ -330,6 +331,14 @@ export default router => {
`;
// Sync session immediately
if (req.session) req.session.username_color = color;
const payloadStr = JSON.stringify({
user_id: req.session.id,
user: req.session.user,
username_color: color
});
await db`select pg_notify('profile_update', ${payloadStr})`;
return res.json({ success: true, color }, 200);
} catch (e) {
console.error('Update Username Color error:', e);
@@ -419,6 +428,14 @@ export default router => {
`;
// Sync session immediately
if (req.session) req.session.display_name = cleanDisplayName;
const payloadStr = JSON.stringify({
user_id: req.session.id,
user: req.session.user,
display_name: cleanDisplayName
});
await db`select pg_notify('profile_update', ${payloadStr})`;
return res.json({ success: true, display_name: cleanDisplayName, msg: 'Display name updated successfully' }, 200);
} catch (e) {
console.error('Update Display Name error:', e);
@@ -437,7 +454,7 @@ export default router => {
return res.json({ success: false, msg: 'Invalid description format' }, 400);
}
const cleanDescription = description ? description.trim().substring(0, 255) : null;
const cleanDescription = description ? description.trim().substring(0, 2000) : null;
try {
await db`
@@ -447,6 +464,14 @@ export default router => {
`;
// Sync session immediately
if (req.session) req.session.description = cleanDescription;
const payloadStr = JSON.stringify({
user_id: req.session.id,
user: req.session.user,
description: cleanDescription
});
await db`select pg_notify('profile_update', ${payloadStr})`;
return res.json({ success: true, description: cleanDescription }, 200);
} catch (e) {
console.error('Update Description error:', e);
@@ -461,7 +486,7 @@ export default router => {
// F-023 Security: Validate font against actual files on disk
// The font value is rendered into CSS url() in header.html, so it must be a real filename
if (font) {
const fontsDir = path.join(path.resolve(), 'public/s/fonts');
const fontsDir = cfg.paths.fonts;
try {
const available = (await fs.readdir(fontsDir)).filter(f => /\.(ttf|otf|woff2?)$/i.test(f));
if (!available.includes(font)) {
@@ -644,6 +669,24 @@ export default router => {
}
});
// Update alternative steuerung preference (per-user toggle for icon-only nav)
group.put(/\/alternative_steuerung/, lib.loggedin, async (req, res) => {
const use_alternative_steuerung = req.post.use_alternative_steuerung === true || req.post.use_alternative_steuerung === 'true';
try {
await db`
update user_options
set use_alternative_steuerung = ${use_alternative_steuerung}
where user_id = ${+req.session.id}
`;
if (req.session) req.session.use_alternative_steuerung = use_alternative_steuerung;
return res.json({ success: true, use_alternative_steuerung }, 200);
} catch (e) {
console.error('Update alternative_steuerung error:', e);
return res.json({ success: false, msg: 'Error updating preference' }, 500);
}
});
// Update per-user language preference
group.put(/\/language/, lib.loggedin, async (req, res) => {
if (cfg.websrv.allow_language_change === false) {
@@ -726,6 +769,342 @@ export default router => {
}
});
// --- Upload API Key Management ---
// GET /api/v2/settings/api-key
// Returns whether the user has an API key, when it was created, and the last 8 chars (masked preview).
group.get(/\/api-key$/, lib.loggedin, async (req, res) => {
if (cfg.websrv.enable_user_api_keys === false) {
return res.json({ success: false, msg: 'API keys are disabled' }, 403);
}
try {
const row = (await db`
SELECT api_key, created_at
FROM user_api_keys
WHERE user_id = ${+req.session.id}
LIMIT 1
`)[0];
if (!row) {
return res.json({ success: true, has_key: false }, 200);
}
return res.json({
success: true,
has_key: true,
preview: `****${row.api_key.slice(-8)}`,
created_at: row.created_at
}, 200);
} catch (e) {
console.error('[API KEY] GET error:', e);
return res.json({ success: false, msg: 'Error fetching API key' }, 500);
}
});
// POST /api/v2/settings/api-key/regenerate
// Generates a new key (or replaces an existing one). Returns the full key — only shown once.
group.post(/\/api-key\/regenerate$/, lib.loggedin, async (req, res) => {
if (cfg.websrv.enable_user_api_keys === false) {
return res.json({ success: false, msg: 'API keys are disabled' }, 403);
}
try {
const newKey = crypto.randomBytes(32).toString('hex');
await db`
INSERT INTO user_api_keys (user_id, api_key, created_at)
VALUES (${+req.session.id}, ${newKey}, now())
ON CONFLICT (user_id) DO UPDATE
SET api_key = EXCLUDED.api_key,
created_at = now()
`;
return res.json({
success: true,
api_key: newKey,
msg: 'API key generated. Copy it now — it will not be shown again in full.'
}, 200);
} catch (e) {
console.error('[API KEY] Regenerate error:', e);
return res.json({ success: false, msg: 'Error generating API key' }, 500);
}
});
// DELETE /api/v2/settings/api-key
// Revokes (deletes) the user's API key.
group.delete(/\/api-key$/, lib.loggedin, async (req, res) => {
if (cfg.websrv.enable_user_api_keys === false) {
return res.json({ success: false, msg: 'API keys are disabled' }, 403);
}
try {
const result = await db`
DELETE FROM user_api_keys
WHERE user_id = ${+req.session.id}
RETURNING user_id
`;
if (result.length === 0) {
return res.json({ success: false, msg: 'No API key to revoke' }, 404);
}
return res.json({ success: true, msg: 'API key revoked' }, 200);
} catch (e) {
console.error('[API KEY] Delete error:', e);
return res.json({ success: false, msg: 'Error revoking API key' }, 500);
}
});
// GET /api/v2/settings/api-key/sharex-config
// Downloads a pre-filled ShareX custom uploader (.sxcu) for the requesting user.
group.get(/\/api-key\/sharex-config$/, lib.loggedin, async (req, res) => {
if (cfg.websrv.enable_user_api_keys === false) {
return res.status(403).reply({ body: 'API keys are disabled' });
}
try {
const row = (await db`
SELECT api_key FROM user_api_keys
WHERE user_id = ${+req.session.id}
LIMIT 1
`)[0];
if (!row) {
return res.status(404).reply({ body: 'No API key — generate one first in Settings.' });
}
// Determine a safe default rating for the ShareX config.
// In shitpost mode the server accepts uploads without a rating, but
// we still send 'sfw' so the item gets a rating tag by default.
const defaultRating = 'sfw';
const sxcu = {
Version: '15.0.0',
Name: cfg.main.url.domain,
DestinationType: 'ImageUploader, FileUploader',
RequestMethod: 'POST',
RequestURL: `${cfg.main.url.full}/api/v2/upload`,
Headers: {
'X-Api-Key': row.api_key
},
Body: 'MultipartFormData',
FileFormName: 'file',
// The server requires a rating field. Without it every upload is rejected.
// Users can change this value in ShareX's custom uploader settings.
Parameters: {
rating: defaultRating
},
// {json:file_url} maps to the direct file URL in the success response JSON
URL: '{json:file_url}',
ThumbnailURL: '{json:file_url}',
ErrorMessage: '{response}'
};
const filename = `${cfg.main.url.domain}.sxcu`;
const body = JSON.stringify(sxcu, null, 2);
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
'Content-Length': Buffer.byteLength(body)
}).end(body);
} catch (e) {
console.error('[API KEY] ShareX config error:', e);
return res.status(500).reply({ body: 'Error generating config' });
}
});
// --- User Invite System ---
// Eligibility: ≥150 uploads, ≥30 days old, ≥66 comments, ≥200 tags
// Slots: configurable (default 2), refresh 30 days after a token is used.
const getInviteCriteria = () => {
const ic = cfg.websrv.invite_criteria || {};
return {
uploads: Number.isFinite(+ic.uploads) ? +ic.uploads : 150,
age_days: Number.isFinite(+ic.age_days) ? +ic.age_days : 30,
comments: Number.isFinite(+ic.comments) ? +ic.comments : 66,
tags: Number.isFinite(+ic.tags) ? +ic.tags : 200,
};
};
const getInviteSlots = () => {
const n = parseInt(cfg.websrv.user_invite_slots);
return Number.isFinite(n) && n > 0 ? n : 2;
};
// GET /api/v2/settings/invites
// Returns eligibility, criteria breakdown, tokens created by this user, and slot usage.
group.get(/\/invites$/, lib.loggedin, async (req, res) => {
if (cfg.websrv.enable_user_invites === false) {
return res.json({ success: false, msg: 'Invite system is disabled' }, 403);
}
try {
const userId = +req.session.id;
const username = req.session.user;
const totalSlots = getInviteSlots();
const refreshDays = 30;
const isAdmin = !!req.session.admin;
// Always fetch this user's token history
const tokens = await db`
SELECT
it.id,
it.token,
it.is_used,
it.used_at,
it.created_at,
u.user AS used_by_name
FROM invite_tokens it
LEFT JOIN "user" u ON u.id = it.used_by
WHERE it.created_by = ${userId}
ORDER BY it.created_at DESC
`;
let eligible, criteria, slotsConsumed, slotsAvailable;
if (isAdmin) {
// Admins bypass all criteria and slot limits
eligible = true;
criteria = null;
slotsConsumed = 0;
slotsAvailable = Infinity;
} else {
// Gather eligibility stats in one query
const [stats] = await db`
SELECT
(SELECT COUNT(*) FROM items WHERE username = ${username} AND active = true AND is_deleted = false)::int AS upload_count,
EXTRACT(EPOCH FROM (NOW() - u.created_at)) / 86400 AS age_days,
(SELECT COUNT(*) FROM comments WHERE user_id = ${userId} AND is_deleted = false)::int AS comment_count,
(SELECT COUNT(*) FROM tags_assign WHERE user_id = ${userId})::int AS tag_count
FROM "user" u
WHERE u.id = ${userId}
`;
const INVITE_CRITERIA = getInviteCriteria();
criteria = {
uploads: { current: stats.upload_count, required: INVITE_CRITERIA.uploads, met: stats.upload_count >= INVITE_CRITERIA.uploads },
age_days: { current: Math.floor(stats.age_days), required: INVITE_CRITERIA.age_days, met: stats.age_days >= INVITE_CRITERIA.age_days },
comments: { current: stats.comment_count, required: INVITE_CRITERIA.comments, met: stats.comment_count >= INVITE_CRITERIA.comments },
tags: { current: stats.tag_count, required: INVITE_CRITERIA.tags, met: stats.tag_count >= INVITE_CRITERIA.tags },
};
eligible = Object.values(criteria).every(c => c.met);
// Slots consumed = tokens used within the last 30 days
const cutoff = new Date(Date.now() - refreshDays * 24 * 60 * 60 * 1000);
slotsConsumed = tokens.filter(t => t.is_used && t.used_at && new Date(t.used_at) > cutoff).length;
slotsAvailable = Math.max(0, totalSlots - slotsConsumed);
}
return res.json({
success: true,
is_admin: isAdmin,
eligible,
criteria,
tokens,
slots_total: isAdmin ? null : totalSlots,
slots_consumed: isAdmin ? null : slotsConsumed,
slots_available: isAdmin ? null : slotsAvailable,
refresh_days: refreshDays,
}, 200);
} catch (e) {
console.error('[INVITES] GET error:', e);
return res.json({ success: false, msg: 'Error fetching invite data' }, 500);
}
});
// POST /api/v2/settings/invites/create
// Generates a new invite token if eligible and slots remain.
group.post(/\/invites\/create$/, lib.loggedin, async (req, res) => {
if (cfg.websrv.enable_user_invites === false) {
return res.json({ success: false, msg: 'Invite system is disabled' }, 403);
}
try {
const userId = +req.session.id;
const username = req.session.user;
const totalSlots = getInviteSlots();
const refreshDays = 30;
const isAdmin = !!req.session.admin;
if (!isAdmin) {
// Eligibility check
const [stats] = await db`
SELECT
(SELECT COUNT(*) FROM items WHERE username = ${username} AND active = true AND is_deleted = false)::int AS upload_count,
EXTRACT(EPOCH FROM (NOW() - u.created_at)) / 86400 AS age_days,
(SELECT COUNT(*) FROM comments WHERE user_id = ${userId} AND is_deleted = false)::int AS comment_count,
(SELECT COUNT(*) FROM tags_assign WHERE user_id = ${userId})::int AS tag_count
FROM "user" u WHERE u.id = ${userId}
`;
const INVITE_CRITERIA = getInviteCriteria();
const eligible =
stats.upload_count >= INVITE_CRITERIA.uploads &&
stats.age_days >= INVITE_CRITERIA.age_days &&
stats.comment_count >= INVITE_CRITERIA.comments &&
stats.tag_count >= INVITE_CRITERIA.tags;
if (!eligible) {
return res.json({ success: false, msg: 'You do not meet the eligibility criteria' }, 403);
}
// Check available slots (used within last 30 days)
const cutoff = new Date(Date.now() - refreshDays * 24 * 60 * 60 * 1000);
const [{ slots_consumed }] = await db`
SELECT COUNT(*)::int AS slots_consumed
FROM invite_tokens
WHERE created_by = ${userId}
AND is_used = true
AND used_at > ${cutoff}
`;
if (slots_consumed >= totalSlots) {
return res.json({ success: false, msg: 'No invite slots available. Slots refresh 30 days after use.' }, 403);
}
}
// Generate token
const token = crypto.randomBytes(16).toString('hex').toUpperCase();
await db`
INSERT INTO invite_tokens (token, created_at, created_by)
VALUES (${token}, ${~~(Date.now() / 1e3)}, ${userId})
`;
console.log(`[INVITES] User ${username} (${userId}) generated invite token ${token}`);
return res.json({ success: true, token }, 200);
} catch (e) {
console.error('[INVITES] Create error:', e);
return res.json({ success: false, msg: 'Error creating invite token' }, 500);
}
});
// POST /api/v2/settings/invites/delete
// Deletes an unused invite token owned by the calling user.
group.post(/\/invites\/delete$/, lib.loggedin, async (req, res) => {
if (cfg.websrv.enable_user_invites === false) {
return res.json({ success: false, msg: 'Invite system is disabled' }, 403);
}
try {
const { id } = req.post;
if (!id) return res.json({ success: false, msg: 'Missing token ID' }, 400);
const result = await db`
DELETE FROM invite_tokens
WHERE id = ${+id}
AND created_by = ${+req.session.id}
AND is_used = false
RETURNING id
`;
if (result.length === 0) {
return res.json({ success: false, msg: 'Token not found or already used' }, 404);
}
return res.json({ success: true }, 200);
} catch (e) {
console.error('[INVITES] Delete error:', e);
return res.json({ success: false, msg: 'Error deleting invite token' }, 500);
}
});
return group;
});

View File

@@ -25,7 +25,8 @@ export default router => {
group.post(/$/, lib.loggedin, async (req, res) => {
// assign and/or create tag
if (!req.params.postid || !req.post.tagname) {
const rawTagname = req.post?.tagname || req.body?.tagname;
if (!req.params.postid || !rawTagname) {
return res.json({
success: false,
msg: 'missing postid or tag'
@@ -33,7 +34,7 @@ export default router => {
}
const postid = +req.params.postid;
const tagname = req.post.tagname?.trim();
const tagname = rawTagname.trim();
const protectedTags = ['sfw', 'nsfw', 'nsfl'];
if (protectedTags.includes(tagname.toLowerCase())) {
@@ -43,7 +44,7 @@ export default router => {
});
}
if (tagname.length > 70) {
if (tagname.length > 85) {
return res.json({
success: false,
msg: 'tag is too long!'
@@ -105,8 +106,19 @@ export default router => {
const cycle = [1, 2, nsflId];
const currentTags = await lib.getTags(postid);
const ratingTagId = currentTags.find(t => [1, 2, nsflId].includes(t.id))?.id ?? 0;
const cycleIdx = cycle.indexOf(ratingTagId); // -1 if untagged → (1+1)%3 = 0 → SFW
const nextTagId = cycle[(cycleIdx + 1) % cycle.length];
let nextTagId;
const reqRating = req.body?.rating || req.post?.rating || req.url?.qs?.rating;
if (reqRating === 'sfw') {
nextTagId = 1;
} else if (reqRating === 'nsfw') {
nextTagId = 2;
} else if (reqRating === 'nsfl') {
nextTagId = nsflId;
} else {
const cycleIdx = cycle.indexOf(ratingTagId); // -1 if untagged → (1+1)%3 = 0 → SFW
nextTagId = cycle[(cycleIdx + 1) % cycle.length];
}
try {
// Remove any existing rating tag
@@ -115,6 +127,14 @@ export default router => {
await db`INSERT INTO tags_assign ${db({ tag_id: nextTagId, item_id: postid, user_id: +req.session.id })}`;
}
// Automatically generate/verify blurred thumbnail on cycle
const blurPath = path.join(cfg.paths.t, `${postid}_blur.webp`);
try {
await fs.promises.access(blurPath);
} catch {
await queue.genBlurredThumbnail(postid, false);
}
const labels = { 1: { label: 'SFW', cls: 'sfw' }, 2: { label: 'NSFW', cls: 'nsfw' }, [nsflId]: { label: 'NSFL', cls: 'nsfl' } };
const { label, cls } = labels[nextTagId];
@@ -170,16 +190,13 @@ export default router => {
await audit.log(req.session.id, 'toggle_tag', 'item', postid, auditDetails);
// Generate blurred thumbnail if toggling TO NSFW
if (hasSFW && !hasNSFW) {
// Was SFW, now NSFW - check if blur exists and generate if not
const blurPath = path.join(cfg.paths.t, `${postid}_blur.webp`);
try {
await fs.promises.access(blurPath);
} catch {
// Doesn't exist - generate it
await queue.genBlurredThumbnail(postid, false);
}
// Ensure blurred thumbnail exists on toggle
const blurPath = path.join(cfg.paths.t, `${postid}_blur.webp`);
try {
await fs.promises.access(blurPath);
} catch {
// Doesn't exist - generate it
await queue.genBlurredThumbnail(postid, false);
}
const freshTags = await lib.getTags(postid);

View File

@@ -1,10 +1,96 @@
import { promises as fs } from "fs";
import { spawn as _spawnRaw } from 'child_process';
import db from '../../sql.mjs';
import lib from '../../lib.mjs';
import cfg from '../../config.mjs';
import { applyWordFilter } from '../../wordfilter.mjs';
import queue from '../../queue.mjs';
import path from "path";
// ──────────────────────────────────────────────────────────────────────
// In-memory job progress map (keyed by jobId string)
// Entries: { stage, percent, speed, eta, done, error }
// Auto-cleaned 10 min after completion.
// ──────────────────────────────────────────────────────────────────────
const progressMap = new Map();
const setProgress = (jobId, patch) => {
const existing = progressMap.get(jobId) || { stage: 'queued', percent: 0, speed: null, eta: null, done: false, error: null };
progressMap.set(jobId, { ...existing, ...patch });
};
const cleanupJob = (jobId) => {
setTimeout(() => progressMap.delete(jobId), 10 * 60 * 1000);
};
/**
* Like queue.spawn() but streams stderr lines to a callback for live progress,
* while still resolving with { stdout, stderr } when the process exits.
* Splits on both \n and \r so yt-dlp's carriage-return progress works.
*/
const spawnWithProgress = (cmd, args, onLine) => {
return new Promise((resolve, reject) => {
const child = _spawnRaw(cmd, args);
const stdoutChunks = [];
const stderrChunks = [];
let stderrBuf = '';
if (child.stdout) child.stdout.on('data', d => stdoutChunks.push(d));
if (child.stderr) {
child.stderr.on('data', chunk => {
stderrChunks.push(chunk);
stderrBuf += chunk.toString();
// Split on \r or \n (yt-dlp uses \r to overwrite progress in-place)
const parts = stderrBuf.split(/[\r\n]/);
// Keep the last (potentially incomplete) segment in the buffer
stderrBuf = parts.pop() ?? '';
for (const line of parts) {
// Strip ANSI escape codes
const clean = line.replace(/\x1b\[[0-9;]*m/g, '').trim();
if (clean && onLine) onLine(clean);
}
});
}
child.on('close', code => {
// Process any remaining buffered content
if (stderrBuf.trim() && onLine) {
const clean = stderrBuf.replace(/\x1b\[[0-9;]*m/g, '').trim();
if (clean) onLine(clean);
}
const stdout = Buffer.concat(stdoutChunks).toString();
const stderr = Buffer.concat(stderrChunks).toString();
if (code !== 0) {
const err = new Error(`Command '${cmd} ${args.join(' ')}' failed with code ${code}`);
err.stderr = stderr;
err.stdout = stdout;
return reject(err);
}
resolve({ stdout, stderr });
});
child.on('error', err => {
err.stderr = Buffer.concat(stderrChunks).toString();
err.stdout = Buffer.concat(stdoutChunks).toString();
reject(err);
});
});
};
/** Parse a yt-dlp stderr line and return a progress patch object or null. */
const parseYtdlpLine = (line) => {
// [download] 47.3% of ~ 58.23MiB at 3.22MiB/s ETA 00:13
const dlMatch = line.match(/\[download\]\s+([\d.]+)%.*?at\s+([\d.]+\s*\S+\/s)(?:.*?ETA\s+(\S+))?/);
if (dlMatch) {
return { stage: 'downloading', percent: parseFloat(dlMatch[1]), speed: dlMatch[2] || null, eta: dlMatch[3] || null };
}
// [download] Destination: ...
if (line.includes('[download] Destination:')) return { stage: 'downloading' };
if (line.includes('[Merger]') || line.includes('[ffmpeg]')) return { stage: 'processing', percent: 99 };
if (line.includes('[ExtractAudio]')) return { stage: 'extracting', percent: 99 };
return null;
};
// Native multipart form data parser
const parseMultipart = (buffer, boundary) => {
const parts = {};
@@ -79,15 +165,25 @@ const collectBody = (req) => {
export default router => {
router.group(/^\/api\/v2/, group => {
// ── GET /api/v2/upload-url/progress/:jobId ──────────────────────────────
group.get(/\/upload-url\/progress\/(?<jobId>[a-zA-Z0-9_-]+)$/, lib.loggedin, (req, res) => {
const jobId = req.params?.jobId || (req.url?.pathname || req.url || '').split('/').pop();
const state = progressMap.get(jobId);
res.setHeader?.('Cache-Control', 'no-store');
if (!state) return res.json({ success: false, msg: 'Job not found' }, 404);
return res.json({ success: true, ...state });
});
const saveComment = async (itemid, userid, content) => {
if (!content || !content.trim()) return;
try {
const filteredContent = await applyWordFilter(content);
await db`
INSERT INTO comments ${db({
item_id: itemid,
user_id: userid,
parent_id: null,
content: content.trim()
content: filteredContent.trim()
}, 'item_id', 'user_id', 'parent_id', 'content')}
`;
} catch (err) {
@@ -133,8 +229,6 @@ export default router => {
domain = parts.slice(-2).join('.');
}
if (domain) tags.push(domain);
// YouTube-specific tag
if (/(?:youtube\.com|youtu\.be)$/i.test(domain) || /(?:youtube\.com|youtu\.be)$/i.test(host)) {
tags.push('youtube');
@@ -202,7 +296,13 @@ export default router => {
return res.json({ success: false, msg: 'URL uploads are disabled' }, 403);
}
const { url: inputUrl, rating, tags: tagsRaw, comment, is_oc, is_shitpost } = req.post || {};
const { url: inputUrl, rating, tags: tagsRaw, comment, is_oc, is_shitpost, title: rawTitle } = req.post || {};
const title = (rawTitle && typeof rawTitle === 'string' && rawTitle.trim()) ? rawTitle.trim().substring(0, 500) : null;
const maxLen = cfg.main.comment_max_length;
if (comment && maxLen !== null && maxLen !== undefined && comment.length > maxLen) {
return res.json({ success: false, msg: `Comment too long (max ${maxLen} characters)` }, 400);
}
if (!inputUrl || !inputUrl.trim()) {
return res.json({ success: false, msg: 'URL is required' }, 400);
@@ -219,8 +319,8 @@ export default router => {
}
const tags = tagsRaw ? tagsRaw.split(',').map(t => t.trim()).filter(t => t.length > 0 && !['sfw', 'nsfw', 'nsfl'].includes(t.toLowerCase())) : [];
const minTags = getMinTags();
// In shitpost mode tags are optional
if (!is_shitpost && tags.length < minTags) {
// In shitpost mode tags are optional; skip entirely when minTags is 0
if (!is_shitpost && minTags > 0 && tags.length < minTags) {
return res.json({ success: false, msg: `At least ${minTags} tag${minTags !== 1 ? 's' : ''} required` }, 400);
}
@@ -236,7 +336,16 @@ export default router => {
}
}
const url = inputUrl.trim();
let url = inputUrl.trim();
try {
const parsed = new URL(url);
if (parsed.searchParams.has('igsh')) {
parsed.searchParams.delete('igsh');
url = parsed.toString();
}
} catch (e) {
// Ignore malformed URL, keep original string
}
const ytRegex = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\/?\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/i;
const ytMatch = url.match(ytRegex);
@@ -273,8 +382,9 @@ export default router => {
usernetwork: 'web',
stamp: ~~(Date.now() / 1000),
active: !isApprovalRequired,
is_oc: !!is_oc
}, 'src', 'dest', 'mime', 'size', 'checksum', 'phash', 'username', 'userchannel', 'usernetwork', 'stamp', 'active', 'is_oc')}
is_oc: !!is_oc,
title: title
}, 'src', 'dest', 'mime', 'size', 'checksum', 'phash', 'username', 'userchannel', 'usernetwork', 'stamp', 'active', 'is_oc', 'title')}
RETURNING id
`;
@@ -296,9 +406,7 @@ export default router => {
if (effectiveRating) {
const ratingTagId = effectiveRating === 'sfw' ? 1 : (effectiveRating === 'nsfw' ? 2 : (cfg.nsfl_tag_id || 3));
await db`insert into tags_assign ${db({ item_id: itemid, tag_id: ratingTagId, user_id: req.session.id })} on conflict do nothing`;
if (effectiveRating === 'nsfw' || effectiveRating === 'nsfl') {
await queue.genBlurredThumbnail(itemid, isApprovalRequired).catch(() => {});
}
await queue.genBlurredThumbnail(itemid, isApprovalRequired).catch(() => {});
}
// Assign user tags + auto-tags
@@ -338,9 +446,14 @@ export default router => {
};
// Return immediately to avoid proxy timeouts
// Generate a client-side trackable job ID
const jobId = await queue.genuuid();
setProgress(jobId, { stage: 'queued', percent: 0, speed: null, eta: null, done: false, error: null });
res.json({
success: true,
pending: true,
jobId,
msg: 'URL processing started in background. You will receive a notification when it is finished.'
});
@@ -385,7 +498,7 @@ export default router => {
try {
const proxyArgs = (cfg.main.socks && cfg.main.socks !== 'undefined') ? ['--proxy', cfg.main.socks] : [];
const ytdlpArgs = ['--js-runtimes', 'node', '--geo-bypass', '--extractor-args', 'youtube:player-client=ios,web'];
const ytdlpArgs = ['--js-runtimes', 'node', '--geo-bypass', '--extractor-args', 'youtube:player-client=ios,web', '--newline', '--no-colors'];
let maxfilesize = cfg.main.maxfilesize;
if (session.admin) maxfilesize = Math.floor(maxfilesize * cfg.main.adminmultiplier);
@@ -396,9 +509,10 @@ export default router => {
let source;
console.log(`[UPLOAD-URL-ASYNC] Starting Stage 1 (constrained) download for ${url} (user: ${session.user})`);
setProgress(jobId, { stage: 'downloading', percent: 0 });
try {
source = (await queue.spawn('yt-dlp', [
source = (await spawnWithProgress('yt-dlp', [
...proxyArgs, ...ytdlpArgs,
'-f', 'bv*[height<=1080]+ba/b[height<=1080] / wv*+ba/w',
url,
@@ -407,22 +521,30 @@ export default router => {
'-o', path.join(cfg.paths.tmp, `${uuid}.%(ext)s`),
'--print', 'after_move:filepath',
'--merge-output-format', 'mp4'
])).stdout.trim().split('\n').map(l => l.trim()).filter(l => l.length > 0).pop();
], (line) => {
const patch = parseYtdlpLine(line);
if (patch) setProgress(jobId, patch);
})).stdout.trim().split('\n').map(l => l.trim()).filter(l => l.length > 0).pop();
} catch (err) {
console.warn(`[UPLOAD-URL-ASYNC] Stage 1 failed: ${err.message}`);
if (isInstagram) throw new Error(sanitizeError(err));
setProgress(jobId, { stage: 'downloading', percent: 0, speed: null, eta: null });
try {
source = (await queue.spawn('yt-dlp', [
source = (await spawnWithProgress('yt-dlp', [
...proxyArgs, ...ytdlpArgs,
url,
'--max-filesize', `${maxfilesize / 1024}k`,
'-o', path.join(cfg.paths.tmp, `${uuid}.%(ext)s`),
'--print', 'after_move:filepath'
])).stdout.trim().split('\n').map(l => l.trim()).filter(l => l.length > 0).pop();
], (line) => {
const patch = parseYtdlpLine(line);
if (patch) setProgress(jobId, patch);
})).stdout.trim().split('\n').map(l => l.trim()).filter(l => l.length > 0).pop();
} catch (err2) {
console.warn(`[UPLOAD-URL-ASYNC] Stage 2 failed: ${err2.message}`);
console.log(`[UPLOAD-URL-ASYNC] Starting Stage 3 (curl) fallback for ${url}`);
setProgress(jobId, { stage: 'downloading', percent: 0, speed: null, eta: null });
const fallbackTmp = path.join(cfg.paths.tmp, `${uuid}.tmp`);
let referer = url;
try {
@@ -467,6 +589,8 @@ export default router => {
if (!source || source.match(/larger than/)) throw new Error('File too large or download failed');
setProgress(jobId, { stage: 'analyzing', percent: 100, speed: null, eta: null });
const { stat } = await import('fs/promises');
const size = (await stat(source)).size;
if (size > maxfilesize) {
@@ -508,7 +632,9 @@ export default router => {
const repostSum = await queue.checkrepostsum(checksum);
if (repostSum) {
await fs.unlink(source).catch(() => {});
await db`INSERT INTO notifications (user_id, type, reference_id, item_id, data) VALUES (${session.id}, 'upload_error', 0, ${repostSum}, ${db.json({ url, msg: 'Duplicate detected (Checksum)' })})`;
setProgress(jobId, { stage: 'error', done: true, error: 'This file already exists', itemId: repostSum });
cleanupJob(jobId);
await db`INSERT INTO notifications (user_id, type, reference_id, item_id, data) VALUES (${session.id}, 'upload_error', 0, ${repostSum}, ${db.json({ jobId, url, msg: 'This file already exists' })})`;
return;
}
}
@@ -520,7 +646,9 @@ export default router => {
const phashMatch = await queue.checkrepostphash(phash);
if (phashMatch) {
await fs.unlink(source).catch(() => {});
await db`INSERT INTO notifications (user_id, type, reference_id, item_id, data) VALUES (${session.id}, 'upload_error', 0, ${phashMatch}, ${db.json({ url, msg: 'Visual duplicate detected (PHash)' })})`;
setProgress(jobId, { stage: 'error', done: true, error: 'This file is a visual duplicate', itemId: phashMatch });
cleanupJob(jobId);
await db`INSERT INTO notifications (user_id, type, reference_id, item_id, data) VALUES (${session.id}, 'upload_error', 0, ${phashMatch}, ${db.json({ jobId, url, msg: 'This file is a visual duplicate' })})`;
return;
}
}
@@ -541,6 +669,7 @@ export default router => {
} catch (e) { }
}
}
setProgress(jobId, { stage: 'saving', percent: 100 });
if (!linkedToExistingUrl) await fs.copyFile(source, path.join(destDir, filename));
await fs.unlink(source).catch(() => { });
@@ -559,8 +688,9 @@ export default router => {
usernetwork: 'web',
stamp: ~~(Date.now() / 1000),
active: !isApprovalRequired,
is_oc: !!is_oc
}, 'src', 'dest', 'mime', 'size', 'checksum', 'phash', 'username', 'userchannel', 'usernetwork', 'stamp', 'active', 'is_oc')}
is_oc: !!is_oc,
title: title
}, 'src', 'dest', 'mime', 'size', 'checksum', 'phash', 'username', 'userchannel', 'usernetwork', 'stamp', 'active', 'is_oc', 'title')}
RETURNING id
`;
@@ -570,7 +700,7 @@ export default router => {
try {
await queue.genThumbnail(filename, mime, itemid, url, isApprovalRequired);
if (effectiveRating === 'nsfw' || effectiveRating === 'nsfl') await queue.genBlurredThumbnail(itemid, isApprovalRequired);
await queue.genBlurredThumbnail(itemid, isApprovalRequired);
} catch (err) {
const tDir = isApprovalRequired ? path.join(cfg.paths.pending, 't') : cfg.paths.t;
await queue.spawn('magick', ['-size', '128x128', 'xc:#1a1a1a', path.join(tDir, `${itemid}.webp`)]).catch(() => {});
@@ -632,12 +762,16 @@ export default router => {
}
// Completion notification
await db`INSERT INTO notifications (user_id, type, reference_id, item_id) VALUES (${session.id}, 'upload_success', 0, ${itemid})`;
setProgress(jobId, { stage: 'done', percent: 100, done: true, error: null, itemId: itemid });
cleanupJob(jobId);
await db`INSERT INTO notifications (user_id, type, reference_id, item_id, data) VALUES (${session.id}, 'upload_success', 0, ${itemid}, ${db.json({ jobId })})`;
} catch (err) {
console.error('[UPLOAD-URL-ASYNC] Final Error:', err);
// Error notification
await db`INSERT INTO notifications (user_id, type, reference_id, item_id, data) VALUES (${session.id}, 'upload_error', 0, ${null}, ${db.json({ url, msg: sanitizeError(err) })})`;
setProgress(jobId, { stage: 'error', done: true, error: sanitizeError(err) });
cleanupJob(jobId);
await db`INSERT INTO notifications (user_id, type, reference_id, item_id, data) VALUES (${session.id}, 'upload_error', 0, ${null}, ${db.json({ jobId, url, msg: sanitizeError(err) })})`;
}
})();
}

View File

@@ -4,6 +4,7 @@ import cfg from "../config.mjs";
import lib from "../lib.mjs";
import audit from "../audit.mjs";
import { promises as fs } from "fs";
import { applyWordFilter } from "../wordfilter.mjs";
import path from "path";
export default (router, tpl) => {
@@ -42,6 +43,24 @@ export default (router, tpl) => {
if (sub.length > 0) is_subscribed = true;
}
// Fill in per-user poll votes
if (req.session && cfg.websrv.enable_comment_polls) {
const pollComments = comments.filter(c => c.poll);
if (pollComments.length > 0) {
const pollIds = pollComments.map(c => c.poll.id);
try {
const votes = await db`
SELECT poll_id, option_id FROM comment_poll_votes
WHERE poll_id = ANY(${pollIds}::int[]) AND user_id = ${req.session.id}
`;
const voteMap = new Map(votes.map(v => [v.poll_id, v.option_id]));
for (const c of pollComments) {
if (c.poll) c.poll.user_vote_option_id = voteMap.get(c.poll.id) || null;
}
} catch (e) { /* graceful */ }
}
}
// Transform for frontend if needed, or send as is
return res.reply({
headers: { 'Content-Type': 'application/json; charset=utf-8' },
@@ -145,7 +164,14 @@ export default (router, tpl) => {
mode = parseInt(req.url.qs.mode);
}
/* </mode-override> */
const modequery = lib.getMode(mode).replace(/items\.id/g, 'i.id');
// Multi-rating cookie support (same logic as other routes)
const ratingsRaw = req.cookies.ratings;
const ratingsArr = ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null;
const multiRatingSQL = (ratingsArr && ratingsArr.length > 0) ? lib.getMultiRatingMode(ratingsArr) : null;
// Build mode SQL — replace items.id alias with i.id used in the activity query
const modequery = (multiRatingSQL ?? lib.getMode(mode)).replace(/items\.id/g, 'i.id');
const comments = await db`
SELECT c.*, i.mime, i.id as item_id
@@ -179,13 +205,122 @@ export default (router, tpl) => {
// Let's modify comments content in-place (or new array) before mapping
const mentionsProcessed = await f0cklib.processMentions(comments);
const processedComments = mentionsProcessed.map(c => {
let processedComments = mentionsProcessed.map(c => {
return {
...c,
content: c.content
};
});
// Fetch file attachments for all fetched comments
if (processedComments.length > 0) {
const commentIds = processedComments.map(c => c.id);
try {
const files = await db`
SELECT id, comment_id, dest, mime, size, original_filename
FROM comment_files
WHERE comment_id = ANY(${commentIds}::int[])
ORDER BY id ASC
`;
const filesMap = new Map();
for (const f of files) {
if (!filesMap.has(f.comment_id)) filesMap.set(f.comment_id, []);
filesMap.get(f.comment_id).push(f);
}
for (const c of processedComments) {
c.files = filesMap.get(c.id) || [];
}
} catch (e) {
for (const c of processedComments) c.files = [];
}
// Fetch poll data for comments
if (cfg.websrv.enable_comment_polls) {
try {
const commentIds = processedComments.map(c => c.id);
const pollRows = await db`
SELECT
cp.id as poll_id,
cp.comment_id,
cp.question,
cp.expires_at,
COALESCE(cp.is_anonymous, true) as is_anonymous,
json_agg(
json_build_object(
'id', cpo.id,
'text', cpo.text,
'sort_order', cpo.sort_order,
'vote_count', COALESCE(vote_counts.cnt, 0)
) ORDER BY cpo.sort_order ASC, cpo.id ASC
) AS options,
COALESCE(SUM(vote_counts.cnt), 0)::int AS total_votes
FROM comment_polls cp
JOIN comment_poll_options cpo ON cpo.poll_id = cp.id
LEFT JOIN (
SELECT option_id, COUNT(*) AS cnt
FROM comment_poll_votes
GROUP BY option_id
) vote_counts ON vote_counts.option_id = cpo.id
WHERE cp.comment_id = ANY(${commentIds}::int[])
GROUP BY cp.id, cp.comment_id, cp.question, cp.expires_at, cp.is_anonymous
`;
// For non-anonymous polls, fetch voter names
const nonAnonIds = pollRows.filter(p => !p.is_anonymous).map(p => p.poll_id);
let votersByOption = new Map();
if (nonAnonIds.length > 0) {
const voterRows = await db`
SELECT cpv.option_id, u."user" as username, uo.avatar, uo.avatar_file
FROM comment_poll_votes cpv
JOIN public."user" u ON u.id = cpv.user_id
LEFT JOIN public.user_options uo ON uo.user_id = cpv.user_id
WHERE cpv.poll_id = ANY(${nonAnonIds}::int[])
`;
for (const v of voterRows) {
if (!votersByOption.has(v.option_id)) votersByOption.set(v.option_id, []);
votersByOption.get(v.option_id).push({ username: v.username, avatar: v.avatar, avatar_file: v.avatar_file });
}
}
const pollMap = new Map();
for (const p of pollRows) {
const options = p.is_anonymous
? p.options
: p.options.map(o => ({ ...o, voters: votersByOption.get(o.id) || [] }));
pollMap.set(p.comment_id, {
id: p.poll_id,
question: p.question,
expires_at: p.expires_at,
is_anonymous: p.is_anonymous,
options,
total_votes: parseInt(p.total_votes) || 0,
user_vote_option_id: null
});
}
// Fill in per-user poll votes if logged in
if (req.session && pollRows.length > 0) {
const pollIds = pollRows.map(p => p.poll_id);
try {
const votes = await db`
SELECT poll_id, option_id FROM comment_poll_votes
WHERE poll_id = ANY(${pollIds}::int[]) AND user_id = ${req.session.id}
`;
const voteMap = new Map(votes.map(v => [v.poll_id, v.option_id]));
for (const [comment_id, poll] of pollMap.entries()) {
poll.user_vote_option_id = voteMap.get(poll.id) || null;
}
} catch (e) { /* graceful */ }
}
for (const c of processedComments) {
c.poll = pollMap.get(c.id) || null;
}
} catch (e) {
console.error('[USER_COMMENTS] Poll fetch error:', e.message);
for (const c of processedComments) c.poll = null;
}
} else {
for (const c of processedComments) c.poll = null;
}
}
if (isJson) {
return res.reply({
headers: { 'Content-Type': 'application/json; charset=utf-8' },
@@ -252,14 +387,20 @@ export default (router, tpl) => {
const body = req.post || {};
const item_id = parseInt(body.item_id, 10);
const parent_id = body.parent_id ? parseInt(body.parent_id, 10) : null;
const content = body.content;
let content = body.content || '';
content = await applyWordFilter(content);
const video_time = (body.video_time !== undefined && body.video_time !== '' && !isNaN(parseFloat(body.video_time)))
? parseFloat(body.video_time)
: null;
if (cfg.main.development) console.log("DEBUG: Posting comment:", { item_id, parent_id, content: content?.substring(0, 20) });
if (!content || !content.trim()) {
const fileIdsRaw = body.file_ids || '';
const fileIds = fileIdsRaw ? fileIdsRaw.split(',').map(id => parseInt(id, 10)).filter(id => !isNaN(id) && id > 0) : [];
const hasPoll = body.has_poll === '1' || body.has_poll === 'true';
if ((!content || !content.trim()) && fileIds.length === 0 && !hasPoll) {
return res.reply({ body: JSON.stringify({ success: false, message: "Empty comment" }) });
}
@@ -281,7 +422,7 @@ export default (router, tpl) => {
item_id,
user_id: req.session.id,
parent_id: parent_id || null,
content: content
content: content || ''
};
if (video_time !== null) insertData.video_time = video_time;
@@ -293,6 +434,7 @@ export default (router, tpl) => {
const commentId = parseInt(newComment[0].id, 10);
// Link uploaded files to this comment (if any)
let activityFiles = [];
const fileIdsRaw = body.file_ids || '';
if (fileIdsRaw) {
const fileIds = fileIdsRaw.split(',').map(id => parseInt(id, 10)).filter(id => !isNaN(id) && id > 0);
@@ -306,6 +448,13 @@ export default (router, tpl) => {
AND user_id = ${req.session.id}
AND comment_id IS NULL
`;
// Fetch the linked files to send with live notification and post response
activityFiles = await db`
SELECT id, comment_id, dest, mime, size, original_filename
FROM comment_files
WHERE comment_id = ${commentId}
ORDER BY id ASC
`;
} catch (err) {
console.error('[COMMENTS] Failed to link files to comment:', err);
}
@@ -418,8 +567,23 @@ export default (router, tpl) => {
}
// Notify for live updates
// Fetch the trigger-updated xd_score from the DB (trigger runs synchronously before we get here)
const [xdRow] = await db`SELECT xd_score FROM items WHERE id = ${item_id}`;
// Fetch the trigger-updated xd_score and the item rating tag from the DB (trigger runs synchronously before we get here)
const itemQuery = await db`
SELECT
i.xd_score,
(SELECT ta.tag_id FROM tags_assign ta
WHERE ta.item_id = i.id AND ta.tag_id = ANY(${[1, 2, cfg.nsfl_tag_id || 3]}::int[])
ORDER BY ta.tag_id LIMIT 1) AS rating_tag_id
FROM items i WHERE i.id = ${item_id}
`;
const xdRow = itemQuery[0];
const ratingTagId = itemQuery[0]?.rating_tag_id;
let ratingLabel = '?';
let ratingClass = 'untagged';
if (ratingTagId == 1) { ratingLabel = 'SFW'; ratingClass = 'sfw'; }
else if (ratingTagId == 2) { ratingLabel = 'NSFW'; ratingClass = 'nsfw'; }
else if (ratingTagId == (cfg.nsfl_tag_id || 3)) { ratingLabel = 'NSFL'; ratingClass = 'nsfl'; }
// Truncate body to 500 chars: PostgreSQL NOTIFY has an 8000-byte hard limit.
// Large comments would silently drop the notification. The client fetches
// the full content via _silentSync; the NOTIFY only needs to trigger the update.
@@ -438,19 +602,35 @@ export default (router, tpl) => {
username_color: req.session.username_color,
display_name: req.session.display_name || null,
xd_score: xdRow?.xd_score ?? null,
video_time: newComment[0]?.video_time ?? null
video_time: newComment[0]?.video_time ?? null,
files: activityFiles
};
// 1. Thread live update
db.notify('comments', JSON.stringify(livePayload));
// 2. Sidebar activity update
// Compute is_long using the full content (not the truncated notifyBody) so the
// sidebar renders the correct clamped state immediately on first paint.
const activityIsLong = content.length > 120
|| content.split('\n').length > 2
|| activityFiles.length > 0
|| /\[(video|audio|youtube|img)\]|!\[|https?:\/\//i.test(content);
db.notify('activity', JSON.stringify({
user_id: req.session.id,
item_id: item_id,
type: 'comment',
body: notifyBody,
id: commentId
id: commentId,
item_rating_class: ratingClass,
item_rating_label: ratingLabel,
avatar: req.session.avatar,
avatar_file: req.session.avatar_file,
username: req.session.user,
username_color: req.session.username_color,
display_name: req.session.display_name || null,
files: activityFiles,
is_long: activityIsLong
}));
// Automatically subscribe user to the thread
@@ -466,7 +646,11 @@ export default (router, tpl) => {
headers: { 'Content-Type': 'application/json; charset=utf-8' },
body: JSON.stringify({
success: true,
comment: newComment[0],
comment: {
...newComment[0],
content,
files: activityFiles
},
xd_score: xdRow?.xd_score ?? null,
is_new_subscription
})
@@ -519,8 +703,14 @@ export default (router, tpl) => {
const comment = await db`SELECT content, item_id, user_id FROM comments WHERE id = ${commentId}`;
if (!comment.length) return res.reply({ code: 404, body: JSON.stringify({ success: false, message: "Not found" }) });
if (!req.session.admin && !req.session.is_moderator && comment[0].user_id !== req.session.id) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: "Forbidden" }) });
const { getAllowCommentDeletion } = await import("../settings.mjs");
const canDeleteOwn = getAllowCommentDeletion();
const isOwner = comment[0].user_id === req.session.id;
if (!req.session.admin && !req.session.is_moderator) {
if (!canDeleteOwn || !isOwner) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: "Forbidden" }) });
}
}
// Log all deletions in audit log
@@ -691,7 +881,8 @@ export default (router, tpl) => {
const commentId = req.params.id;
const body = req.post || {};
const content = body.content;
let content = body.content;
content = await applyWordFilter(content);
if (!content || !content.trim()) {
return res.reply({ body: JSON.stringify({ success: false, message: "Empty content" }) });
@@ -796,7 +987,14 @@ export default (router, tpl) => {
mode = parseInt(req.url.qs.mode);
}
/* </mode-override> */
const modequery = lib.getMode(mode).replace(/items\.id/g, 'i.id');
// Multi-rating cookie support (same logic as other routes)
const ratingsRaw = req.cookies.ratings;
const ratingsArr = ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null;
const multiRatingSQL = (ratingsArr && ratingsArr.length > 0) ? lib.getMultiRatingMode(ratingsArr) : null;
// Build mode SQL — replace items.id alias with i.id used in the activity query
const modequery = (multiRatingSQL ?? lib.getMode(mode)).replace(/items\.id/g, 'i.id');
const globalfilter = cfg.nsfp.map(n => `tag_id = ${n}`).join(' or ');
const excludedTags = req.session ? (req.session.excluded_tags || []) : [];
@@ -806,6 +1004,9 @@ export default (router, tpl) => {
i.mime,
i.id as item_id,
i.dest as item_dest,
(SELECT ta.tag_id FROM tags_assign ta
WHERE ta.item_id = i.id AND ta.tag_id = ANY(${[1, 2, cfg.nsfl_tag_id || 3]}::int[])
ORDER BY ta.tag_id LIMIT 1) AS rating_tag_id,
u.user as username,
uo.avatar,
uo.avatar_file,
@@ -826,11 +1027,95 @@ export default (router, tpl) => {
LIMIT ${limit} OFFSET ${offset}
`;
// Fetch comment file attachments
const filesMap = new Map();
if (comments.length > 0) {
const commentIds = comments.map(c => c.id);
try {
const files = await db`
SELECT id, comment_id, dest, mime, size, original_filename
FROM comment_files
WHERE comment_id = ANY(${commentIds}::int[])
ORDER BY id ASC
`;
for (const f of files) {
if (!filesMap.has(f.comment_id)) filesMap.set(f.comment_id, []);
filesMap.get(f.comment_id).push(f);
}
} catch (e) {
console.error('[ACTIVITY] Failed to fetch comment files:', e);
}
}
// Fetch poll data for these comments
const pollMap = new Map();
if (comments.length > 0 && cfg.websrv.enable_comment_polls) {
try {
const commentIds = comments.map(c => c.id);
const pollRows = await db`
SELECT
cp.id as poll_id,
cp.comment_id,
cp.question,
cp.expires_at,
COALESCE(cp.is_anonymous, true) as is_anonymous,
json_agg(
json_build_object(
'id', cpo.id,
'text', cpo.text,
'sort_order', cpo.sort_order,
'vote_count', COALESCE(vc.cnt, 0)
) ORDER BY cpo.sort_order ASC, cpo.id ASC
) AS options,
COALESCE(SUM(vc.cnt), 0)::int AS total_votes
FROM comment_polls cp
JOIN comment_poll_options cpo ON cpo.poll_id = cp.id
LEFT JOIN (SELECT option_id, COUNT(*) AS cnt FROM comment_poll_votes GROUP BY option_id) vc ON vc.option_id = cpo.id
WHERE cp.comment_id = ANY(${commentIds}::int[])
GROUP BY cp.id, cp.comment_id, cp.question, cp.expires_at, cp.is_anonymous
`;
for (const p of pollRows) {
pollMap.set(p.comment_id, {
id: p.poll_id,
question: p.question,
expires_at: p.expires_at,
is_anonymous: p.is_anonymous,
options: p.options,
total_votes: parseInt(p.total_votes) || 0,
user_vote_option_id: null
});
}
} catch (e) {
console.error('[ACTIVITY] Failed to fetch polls:', e.message);
}
}
const processedComments = comments.map(c => {
let ratingLabel = '?';
let ratingClass = 'untagged';
if (c.rating_tag_id == 1) { ratingLabel = 'SFW'; ratingClass = 'sfw'; }
else if (c.rating_tag_id == 2) { ratingLabel = 'NSFW'; ratingClass = 'nsfw'; }
else if (c.rating_tag_id == (cfg.nsfl_tag_id || 3)) { ratingLabel = 'NSFL'; ratingClass = 'nsfl'; }
const commentContent = (c.content || '').trim();
const commentFiles = filesMap.get(c.id) || [];
// Compute overflow hint: true if content is likely taller than the 80px clamp.
// ~120 chars ≈ 2-3 wrapped lines in the sidebar; any newlines > 2 or file
// attachments (images/video) will also push height above the limit.
const isLong = commentContent.length > 120
|| commentContent.split('\n').length > 2
|| commentFiles.length > 0
|| /\[(video|audio|youtube|img)\]|!\[|https?:\/\//i.test(commentContent);
return {
...c,
content: (c.content || '').trim(),
username_color: c.username_color
content: commentContent,
username_color: c.username_color,
item_rating_class: ratingClass,
item_rating_label: ratingLabel,
files: commentFiles,
poll: pollMap.get(c.id) || null,
is_long: isLong
// created_at stays as the raw ISO timestamp so the frontend f0ckTimeAgo can localize it
};
});
@@ -890,5 +1175,259 @@ export default (router, tpl) => {
}
});
// ──────────────────────────────────────────────────────────────────────────
// Poll creation — called after a comment is inserted (internal helper)
// ──────────────────────────────────────────────────────────────────────────
const createPollForComment = async (commentId, pollData) => {
if (!cfg.websrv.enable_comment_polls) return null;
const { question, options, is_anonymous } = pollData || {};
if (!question || !question.trim()) return null;
if (!Array.isArray(options) || options.length < 2) return null;
const cleanOptions = options.map(o => (typeof o === 'string' ? o : String(o)).trim()).filter(Boolean);
if (cleanOptions.length < 2 || cleanOptions.length > 10) return null;
const anonymous = is_anonymous !== false; // default true
const [poll] = await db`
INSERT INTO comment_polls (comment_id, question, is_anonymous)
VALUES (${commentId}, ${question.trim()}, ${anonymous})
RETURNING id, is_anonymous
`;
const pollId = poll.id;
for (let i = 0; i < cleanOptions.length; i++) {
await db`
INSERT INTO comment_poll_options (poll_id, text, sort_order)
VALUES (${pollId}, ${cleanOptions[i]}, ${i})
`;
}
const optRows = await db`SELECT id, text, sort_order FROM comment_poll_options WHERE poll_id = ${pollId} ORDER BY sort_order ASC`;
return {
id: pollId,
question: question.trim(),
is_anonymous: poll.is_anonymous,
options: optRows.map(o => ({ id: o.id, text: o.text, sort_order: o.sort_order, vote_count: 0, voters: [] })),
total_votes: 0,
user_vote_option_id: null
};
};
// Patch POST /api/comments to support optional poll payload
// We cannot re-define the same route, so we intercept via a pre-middleware trick.
// Instead we add a dedicated endpoint that the frontend always uses for polls.
// POST /api/polls/:commentId — attach a poll to an existing just-created comment
// (frontend calls this immediately after posting the comment)
router.post(/\/api\/polls\/attach\/(?<commentId>\d+)/, async (req, res) => {
if (!req.session) return res.reply({ code: 401, body: JSON.stringify({ success: false }) });
if (!cfg.websrv.enable_comment_polls) return res.reply({ code: 403, body: JSON.stringify({ success: false, message: 'Polls disabled' }) });
const commentId = req.params.commentId;
const body = req.post || {};
// Verify this comment belongs to the logged-in user and has no poll yet
const comment = await db`SELECT id, user_id FROM comments WHERE id = ${commentId} AND is_deleted = false LIMIT 1`;
if (!comment.length) return res.reply({ code: 404, body: JSON.stringify({ success: false, message: 'Comment not found' }) });
if (comment[0].user_id !== req.session.id && !req.session.admin && !req.session.is_moderator) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: 'Forbidden' }) });
}
const existing = await db`SELECT id FROM comment_polls WHERE comment_id = ${commentId} LIMIT 1`;
if (existing.length) return res.reply({ code: 409, body: JSON.stringify({ success: false, message: 'Poll already exists' }) });
let pollData;
try {
pollData = typeof body.poll === 'string' ? JSON.parse(body.poll) : body.poll;
} catch (e) {
return res.reply({ code: 400, body: JSON.stringify({ success: false, message: 'Invalid poll JSON' }) });
}
try {
const poll = await createPollForComment(parseInt(commentId, 10), pollData);
if (!poll) return res.reply({ code: 400, body: JSON.stringify({ success: false, message: 'Invalid poll data (need question + 2-10 options)' }) });
return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true, poll }) });
} catch (err) {
console.error('[POLLS] createPollForComment error:', err);
return res.reply({ code: 500, body: JSON.stringify({ success: false, message: 'Database error' }) });
}
});
// GET /api/polls/:pollId — fetch poll with current user's vote
router.get(/\/api\/polls\/(?<pollId>\d+)/, async (req, res) => {
if (!cfg.websrv.enable_comment_polls) return res.reply({ code: 403, body: JSON.stringify({ success: false }) });
const pollId = req.params.pollId;
try {
const pollRows = await db`
SELECT
cp.id as poll_id, cp.comment_id, cp.question, cp.expires_at, COALESCE(cp.is_anonymous, true) as is_anonymous,
json_agg(
json_build_object(
'id', cpo.id, 'text', cpo.text, 'sort_order', cpo.sort_order,
'vote_count', COALESCE(vc.cnt, 0)
) ORDER BY cpo.sort_order ASC, cpo.id ASC
) AS options,
COALESCE(SUM(vc.cnt), 0)::int AS total_votes
FROM comment_polls cp
JOIN comment_poll_options cpo ON cpo.poll_id = cp.id
LEFT JOIN (SELECT option_id, COUNT(*) AS cnt FROM comment_poll_votes GROUP BY option_id) vc ON vc.option_id = cpo.id
WHERE cp.id = ${pollId}
GROUP BY cp.id, cp.comment_id, cp.question, cp.expires_at, cp.is_anonymous
`;
if (!pollRows.length) return res.reply({ code: 404, body: JSON.stringify({ success: false }) });
const p = pollRows[0];
let userVoteOptionId = null;
if (req.session) {
const vote = await db`SELECT option_id FROM comment_poll_votes WHERE poll_id = ${pollId} AND user_id = ${req.session.id} LIMIT 1`;
if (vote.length) userVoteOptionId = vote[0].option_id;
}
// If not anonymous, attach voter usernames to each option
let options = p.options;
if (!p.is_anonymous) {
const voterRows = await db`
SELECT cpv.option_id, u."user" as username, uo.avatar, uo.avatar_file
FROM comment_poll_votes cpv
JOIN public."user" u ON u.id = cpv.user_id
LEFT JOIN public.user_options uo ON uo.user_id = cpv.user_id
WHERE cpv.poll_id = ${pollId}
`;
const voterMap = new Map();
for (const v of voterRows) {
if (!voterMap.has(v.option_id)) voterMap.set(v.option_id, []);
voterMap.get(v.option_id).push({ username: v.username, avatar: v.avatar, avatar_file: v.avatar_file });
}
options = options.map(o => ({ ...o, voters: voterMap.get(o.id) || [] }));
}
return res.reply({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
success: true,
poll: {
id: p.poll_id,
comment_id: p.comment_id,
question: p.question,
expires_at: p.expires_at,
is_anonymous: p.is_anonymous,
options,
total_votes: parseInt(p.total_votes) || 0,
user_vote_option_id: userVoteOptionId
}
})
});
} catch (err) {
console.error('[POLLS] GET error:', err);
return res.reply({ code: 500, body: JSON.stringify({ success: false }) });
}
});
// POST /api/polls/:pollId/vote — cast or change vote
router.post(/\/api\/polls\/(?<pollId>\d+)\/vote/, async (req, res) => {
if (!req.session) return res.reply({ code: 401, body: JSON.stringify({ success: false }) });
if (!cfg.websrv.enable_comment_polls) return res.reply({ code: 403, body: JSON.stringify({ success: false }) });
const pollId = req.params.pollId;
const body = req.post || {};
const optionId = parseInt(body.option_id, 10);
if (!optionId) return res.reply({ code: 400, body: JSON.stringify({ success: false, message: 'Missing option_id' }) });
try {
// Verify option belongs to poll
const opt = await db`SELECT id FROM comment_poll_options WHERE id = ${optionId} AND poll_id = ${pollId} LIMIT 1`;
if (!opt.length) return res.reply({ code: 400, body: JSON.stringify({ success: false, message: 'Invalid option' }) });
// Check expiry
const poll = await db`SELECT expires_at FROM comment_polls WHERE id = ${pollId} LIMIT 1`;
if (!poll.length) return res.reply({ code: 404, body: JSON.stringify({ success: false }) });
if (poll[0].expires_at && new Date(poll[0].expires_at) < new Date()) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: 'Poll has expired' }) });
}
// Upsert vote (change allowed) — manual check avoids needing a unique constraint
const existing = await db`
SELECT poll_id FROM comment_poll_votes
WHERE poll_id = ${pollId} AND user_id = ${req.session.id}
LIMIT 1
`;
if (existing.length) {
await db`
UPDATE comment_poll_votes
SET option_id = ${optionId}, created_at = now()
WHERE poll_id = ${pollId} AND user_id = ${req.session.id}
`;
} else {
await db`
INSERT INTO comment_poll_votes (poll_id, option_id, user_id)
VALUES (${pollId}, ${optionId}, ${req.session.id})
`;
}
// Return updated tally
const pollMeta = await db`SELECT COALESCE(is_anonymous, true) as is_anonymous FROM comment_polls WHERE id = ${pollId} LIMIT 1`;
const isAnon = pollMeta.length ? pollMeta[0].is_anonymous : true;
const rows = await db`
SELECT cpo.id, cpo.text, cpo.sort_order, COALESCE(vc.cnt, 0)::int AS vote_count
FROM comment_poll_options cpo
LEFT JOIN (SELECT option_id, COUNT(*) AS cnt FROM comment_poll_votes WHERE poll_id = ${pollId} GROUP BY option_id) vc ON vc.option_id = cpo.id
WHERE cpo.poll_id = ${pollId}
ORDER BY cpo.sort_order ASC
`;
const totalVotes = rows.reduce((s, r) => s + r.vote_count, 0);
let options = rows;
if (!isAnon) {
const voterRows = await db`
SELECT cpv.option_id, u."user" as username, uo.avatar, uo.avatar_file
FROM comment_poll_votes cpv
JOIN public."user" u ON u.id = cpv.user_id
LEFT JOIN public.user_options uo ON uo.user_id = cpv.user_id
WHERE cpv.poll_id = ${pollId}
`;
const voterMap = new Map();
for (const v of voterRows) {
if (!voterMap.has(v.option_id)) voterMap.set(v.option_id, []);
voterMap.get(v.option_id).push({ username: v.username, avatar: v.avatar, avatar_file: v.avatar_file });
}
options = rows.map(o => ({ ...o, voters: voterMap.get(o.id) || [] }));
}
return res.reply({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ success: true, is_anonymous: isAnon, options, total_votes: totalVotes, user_vote_option_id: optionId })
});
} catch (err) {
console.error('[POLLS] vote error:', err);
return res.reply({ code: 500, body: JSON.stringify({ success: false }) });
}
});
// DELETE /api/polls/:pollId — admin/mod or creator can delete
router.post(/\/api\/polls\/(?<pollId>\d+)\/delete/, async (req, res) => {
if (!req.session) return res.reply({ code: 401, body: JSON.stringify({ success: false }) });
if (!cfg.websrv.enable_comment_polls) return res.reply({ code: 403, body: JSON.stringify({ success: false }) });
const pollId = req.params.pollId;
try {
const poll = await db`
SELECT cp.id, cp.comment_id, c.user_id
FROM comment_polls cp
JOIN comments c ON c.id = cp.comment_id
WHERE cp.id = ${pollId} LIMIT 1
`;
if (!poll.length) return res.reply({ code: 404, body: JSON.stringify({ success: false }) });
const isCreator = poll[0].user_id === req.session.id;
if (!isCreator && !req.session.admin && !req.session.is_moderator) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: 'Forbidden' }) });
}
await db`DELETE FROM comment_polls WHERE id = ${pollId}`;
// Notify live update
db.notify('comments', JSON.stringify({ type: 'poll_deleted', poll_id: pollId, comment_id: poll[0].comment_id }));
return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true }) });
} catch (err) {
console.error('[POLLS] delete error:', err);
return res.reply({ code: 500, body: JSON.stringify({ success: false }) });
}
});
return router;
};

View File

@@ -6,6 +6,7 @@ import path from "path";
import { fileURLToPath } from "url";
import { execFile as _execFile } from "child_process";
import { promisify } from "util";
import crypto from "crypto";
const execFile = promisify(_execFile);
@@ -23,15 +24,312 @@ export default (router, tpl) => {
});
});
// List all emojis (Public)
// List all emojis — returns both a flat list and a grouped-by-pack structure
router.get('/api/v2/emojis', async (req, res) => {
try {
const emojis = await db`SELECT id, name, url FROM custom_emojis ORDER BY name ASC`;
// Try the full pack-aware query first; fall back if pack_id column doesn't exist yet
let emojis;
let hasPacks = true;
try {
emojis = await db`
SELECT e.id, e.name, e.url, e.pack_id,
p.name as pack_name, p.tg_name, p.tg_title, p.thumb_url as pack_thumb_url
FROM custom_emojis e
LEFT JOIN sticker_packs p ON p.id = e.pack_id
ORDER BY e.pack_id NULLS FIRST, e.id ASC
`;
} catch (colErr) {
// column pack_id or thumb_url may not exist — try without thumb_url, then flat
try {
emojis = await db`
SELECT e.id, e.name, e.url, e.pack_id,
p.name as pack_name, p.tg_name, p.tg_title, NULL as pack_thumb_url
FROM custom_emojis e
LEFT JOIN sticker_packs p ON p.id = e.pack_id
ORDER BY e.pack_id NULLS FIRST, e.id ASC
`;
} catch (_) {
// pack_id column missing entirely — serve flat list
console.warn('[EMOJIS] pack_id column missing, serving flat list');
hasPacks = false;
emojis = await db`SELECT id, name, url FROM custom_emojis ORDER BY id ASC`;
}
}
// Flat list (backwards compat)
const flat = emojis.map(e => ({ id: e.id, name: e.name, url: e.url, pack_id: e.pack_id ?? null }));
if (!hasPacks) {
return res.reply({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ success: true, emojis: flat, packs: [] })
});
}
// Grouped by pack
const packsMap = new Map();
// "No pack" group for standalone emojis
packsMap.set(null, { id: null, name: 'Custom Emojis', tg_name: null, emojis: [] });
for (const e of emojis) {
if (e.pack_id && !packsMap.has(e.pack_id)) {
packsMap.set(e.pack_id, {
id: e.pack_id,
name: e.pack_name || e.tg_title || `Pack #${e.pack_id}`,
tg_name: e.tg_name,
thumb_url: e.pack_thumb_url || null,
emojis: []
});
}
const packKey = e.pack_id ?? null;
packsMap.get(packKey).emojis.push({ id: e.id, name: e.name, url: e.url });
}
// Filter out empty groups
const packs = [...packsMap.values()].filter(p => p.emojis.length > 0);
return res.reply({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ success: true, emojis })
body: JSON.stringify({ success: true, emojis: flat, packs })
});
} catch (e) {
console.error(e);
return res.reply({ code: 500, body: JSON.stringify({ success: false, message: "Database error" }) });
}
});
// List sticker packs (Admin)
router.get('/api/v2/admin/sticker-packs', async (req, res) => {
if (!req.session || !req.session.admin) {
return res.reply({ code: 403, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: false, message: "Forbidden" }) });
}
try {
let packs;
try {
packs = await db`
SELECT sp.id, sp.name, sp.tg_name, sp.tg_title, sp.thumb_url, sp.sticker_count, sp.created_at,
count(e.id)::int as actual_count
FROM sticker_packs sp
LEFT JOIN custom_emojis e ON e.pack_id = sp.id
GROUP BY sp.id
ORDER BY sp.created_at DESC
`;
} catch (_) {
// thumb_url column may not exist yet — fall back without it
packs = await db`
SELECT sp.id, sp.name, sp.tg_name, sp.tg_title, NULL as thumb_url, sp.sticker_count, sp.created_at,
count(e.id)::int as actual_count
FROM sticker_packs sp
LEFT JOIN custom_emojis e ON e.pack_id = sp.id
GROUP BY sp.id
ORDER BY sp.created_at DESC
`;
}
return res.reply({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ success: true, packs })
});
} catch (e) {
console.error(e);
return res.reply({ code: 500, body: JSON.stringify({ success: false, message: "Database error" }) });
}
});
// Delete a sticker pack and all its emojis (Admin)
router.delete(/\/api\/v2\/admin\/sticker-packs\/(?<id>\d+)/, async (req, res) => {
if (!req.session || !req.session.admin) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: "Forbidden" }) });
}
const csrfToken = req.headers['x-csrf-token'];
if (!req.session.csrf_token || !csrfToken || csrfToken !== req.session.csrf_token) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: "Invalid CSRF token" }) });
}
const id = req.params.id;
try {
// Fetch emoji file URLs before deletion for filesystem cleanup
const emojiFiles = await db`SELECT url FROM custom_emojis WHERE pack_id = ${id}`;
await db`DELETE FROM custom_emojis WHERE pack_id = ${id}`;
await db`DELETE FROM sticker_packs WHERE id = ${id}`;
// Clean up local files
for (const e of emojiFiles) {
if (e.url && e.url.startsWith('/s/emojis/')) {
const filename = path.basename(e.url);
await fs.unlink(path.join(cfg.paths.emojis, filename)).catch(() => {});
}
}
await db`NOTIFY emojis_updated, '{}'`;
return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true }) });
} catch (e) {
console.error(e);
return res.reply({ code: 500, body: JSON.stringify({ success: false, message: "Database error" }) });
}
});
// Rename a sticker pack (Admin) — optionally backfills emoji names and comment references
router.post(/\/api\/v2\/admin\/sticker-packs\/(?<id>\d+)\/rename/, async (req, res) => {
if (!req.session || !req.session.admin) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: "Forbidden" }) });
}
const csrfToken = req.headers['x-csrf-token'];
if (!req.session.csrf_token || !csrfToken || csrfToken !== req.session.csrf_token) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: "Invalid CSRF token" }) });
}
const id = req.params.id;
let body = {};
try {
const raw = req.body || req.post || {};
body = typeof raw === 'string' ? JSON.parse(raw) : raw;
} catch (_) {}
const newName = (body.name || '').trim();
const backfill = body.backfill === true;
if (!newName) {
return res.reply({ code: 400, body: JSON.stringify({ success: false, message: 'name is required' }) });
}
try {
if (!backfill) {
// Simple rename only
await db`UPDATE sticker_packs SET name = ${newName} WHERE id = ${id}`;
await db`NOTIFY emojis_updated, '{}'`;
return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true }) });
}
// ── Backfill: rename emojis + update comment references ──────────
// Build new slug from new display name (same logic as import)
const newSlug = newName
.replace(/[^a-z0-9]/gi, '_')
.toLowerCase()
.replace(/_+/g, '_')
.replace(/^_|_$/, '');
// Load all emojis in this pack
const emojis = await db`SELECT id, name FROM custom_emojis WHERE pack_id = ${id} ORDER BY id`;
// Build rename map: old_name → new_name
const renames = [];
for (const emoji of emojis) {
const suffixMatch = emoji.name.match(/_(\d+)$/);
if (!suffixMatch) continue; // skip non-standard names
const newEmojiName = newSlug + '_' + suffixMatch[1].padStart(3, '0');
if (newEmojiName !== emoji.name) {
renames.push({ id: emoji.id, oldName: emoji.name, newName: newEmojiName });
}
}
// Apply everything in a transaction
let emojiRenamed = 0;
let commentRowsUpdated = 0;
await db.begin(async sql => {
// Rename the pack
await sql`UPDATE sticker_packs SET name = ${newName} WHERE id = ${id}`;
for (const r of renames) {
// Check name conflict (another emoji already has this name)
const [conflict] = await sql`SELECT id FROM custom_emojis WHERE name = ${r.newName} AND id != ${r.id} LIMIT 1`;
if (conflict) {
console.warn(`[RENAME] Skipping ${r.oldName}${r.newName}: name conflict`);
continue;
}
// Rename the emoji
await sql`UPDATE custom_emojis SET name = ${r.newName} WHERE id = ${r.id}`;
emojiRenamed++;
// Replace :old_name: with :new_name: in all comments
const result = await sql`
UPDATE comments
SET content = REPLACE(content, ${':' + r.oldName + ':'}, ${':' + r.newName + ':'})
WHERE content LIKE ${'%:' + r.oldName + ':%'}
`;
commentRowsUpdated += result.count ?? 0;
}
});
await db`NOTIFY emojis_updated, '{}'`;
return res.reply({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ success: true, emojiRenamed, commentRowsUpdated })
});
} catch (e) {
console.error('[RENAME PACK]', e);
return res.reply({ code: 500, body: JSON.stringify({ success: false, message: "Database error: " + e.message }) });
}
});
// Set tab thumbnail for a sticker pack (Admin)
router.post(/\/api\/v2\/admin\/sticker-packs\/(?<id>\d+)\/thumb/, async (req, res) => {
if (!req.session || !req.session.admin) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: "Forbidden" }) });
}
const csrfToken = req.headers['x-csrf-token'];
if (!req.session.csrf_token || !csrfToken || csrfToken !== req.session.csrf_token) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: "Invalid CSRF token" }) });
}
const id = req.params.id;
let body = {};
try {
const raw = req.body || req.post || {};
body = typeof raw === 'string' ? JSON.parse(raw) : raw;
} catch (_) {}
const thumbUrl = (body.thumb_url || '').trim();
// Only allow local emoji paths to prevent SSRF
if (!thumbUrl || !thumbUrl.startsWith('/s/emojis/')) {
return res.reply({ code: 400, body: JSON.stringify({ success: false, message: 'thumb_url must be a local /s/emojis/ path' }) });
}
try {
let finalThumbUrl = thumbUrl;
// For .webm stickers: extract first frame -> save as WebP so tabs always show a static image
if (thumbUrl.endsWith('.webm')) {
try {
const webmPath = path.join(cfg.paths.emojis, path.basename(thumbUrl));
const randSuffix = crypto.randomBytes(24).toString('hex');
const tmpPng = path.join(cfg.paths.emojis, randSuffix + '_tmp.png');
const webpPath = path.join(cfg.paths.emojis, randSuffix + '_thumb.webp');
// Step 1: ffmpeg extracts first frame to a temp PNG file
await execFile('ffmpeg', [
'-y', '-i', webmPath,
'-vframes', '1',
tmpPng
], { maxBuffer: 20 * 1024 * 1024 });
// Step 2: ImageMagick converts PNG -> WebP
try {
await execFile('magick', [tmpPng, '-quality', '85', webpPath], { env: magickEnv });
} finally {
await fs.unlink(tmpPng).catch(() => {});
}
const stat = await fs.stat(webpPath).catch(() => null);
if (stat && stat.size > 0) {
finalThumbUrl = '/s/emojis/' + randSuffix + '_thumb.webp';
console.log('[SET THUMB] Generated WebP thumbnail from .webm: ' + finalThumbUrl);
}
} catch (thumbErr) {
console.warn('[SET THUMB] Could not generate WebP from .webm:', thumbErr.message);
}
}
try {
await db`UPDATE sticker_packs SET thumb_url = ${finalThumbUrl} WHERE id = ${id}`;
} catch (colErr) {
// Column might not exist yet — add it and retry once
if (colErr.message && colErr.message.includes('thumb_url')) {
await db`ALTER TABLE public.sticker_packs ADD COLUMN IF NOT EXISTS thumb_url text`;
await db`UPDATE sticker_packs SET thumb_url = ${finalThumbUrl} WHERE id = ${id}`;
} else {
throw colErr;
}
}
await db`NOTIFY emojis_updated, '{}'`;
return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true, thumb_url: finalThumbUrl }) });
} catch (e) {
console.error(e);
return res.reply({ code: 500, body: JSON.stringify({ success: false, message: "Database error" }) });
}
@@ -132,5 +430,61 @@ export default (router, tpl) => {
}
});
// ── User Emoji Favorites ─────────────────────────────────────────
// Create table lazily on first use (idempotent)
const ensureFavTable = async () => {
await db`
CREATE TABLE IF NOT EXISTS user_emoji_favorites (
user_id integer NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
emoji_name text NOT NULL,
emoji_url text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, emoji_name)
)`;
};
// GET /api/v2/user/emoji-favorites — returns logged-in user's favorites
router.get('/api/v2/user/emoji-favorites', lib.loggedin, async (req, res) => {
try {
await ensureFavTable();
const rows = await db`
SELECT emoji_name AS name, emoji_url AS url
FROM user_emoji_favorites
WHERE user_id = ${req.session.id}
ORDER BY created_at ASC
`;
return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true, favorites: rows }) });
} catch (e) {
console.error('[EMOJI FAVS GET]', e);
return res.reply({ code: 500, body: JSON.stringify({ success: false }) });
}
});
// POST /api/v2/user/emoji-favorites/toggle — add or remove a single favorite
router.post('/api/v2/user/emoji-favorites/toggle', lib.loggedin, async (req, res) => {
const csrfToken = req.headers['x-csrf-token'];
if (!req.session.csrf_token || !csrfToken || csrfToken !== req.session.csrf_token) {
return res.reply({ code: 403, body: JSON.stringify({ success: false, message: 'Invalid CSRF token' }) });
}
let body = {};
try { const raw = req.body || req.post || {}; body = typeof raw === 'string' ? JSON.parse(raw) : raw; } catch (_) {}
const { name, url, action } = body;
if (!name || !url) return res.reply({ code: 400, body: JSON.stringify({ success: false, message: 'name and url required' }) });
try {
await ensureFavTable();
if (action === 'remove') {
await db`DELETE FROM user_emoji_favorites WHERE user_id = ${req.session.id} AND emoji_name = ${name}`;
} else {
await db`INSERT INTO user_emoji_favorites (user_id, emoji_name, emoji_url) VALUES (${req.session.id}, ${name}, ${url}) ON CONFLICT (user_id, emoji_name) DO NOTHING`;
}
return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true }) });
} catch (e) {
console.error('[EMOJI FAVS TOGGLE]', e);
return res.reply({ code: 500, body: JSON.stringify({ success: false }) });
}
});
// Edit emoji (Admin only) — handled by bypass middleware in index.mjs
return router;
};

View File

@@ -319,7 +319,7 @@ export default (router) => {
// POST /api/v2/scroller/rehost
// Downloads an external item and adds it to the platform
router.post(/^\/api\/v2\/scroller\/rehost\/?$/, lib.loggedin, async (req, res) => {
const { url, rating: initialRating, tags: tagsRaw, comment, is_oc } = req.post || {};
const { url, rating: initialRating, tags: tagsRaw, comment, is_oc, original_filename } = req.post || {};
if (!url) return res.reply({ code: 400, body: JSON.stringify({ success: false, msg: 'URL is required' }) });
@@ -436,8 +436,9 @@ export default (router) => {
usernetwork: 'web',
stamp: ~~(Date.now() / 1000),
active: !isApprovalRequired,
is_oc: !!is_oc
}, 'src', 'dest', 'mime', 'size', 'checksum', 'phash', 'username', 'userchannel', 'usernetwork', 'stamp', 'active', 'is_oc')}
is_oc: !!is_oc,
original_filename: original_filename || null
}, 'src', 'dest', 'mime', 'size', 'checksum', 'phash', 'username', 'userchannel', 'usernetwork', 'stamp', 'active', 'is_oc', 'original_filename')}
RETURNING id
`;
@@ -449,7 +450,7 @@ export default (router) => {
// Process thumbnail
try {
await queue.genThumbnail(filename, mime, itemid, url, isApprovalRequired);
if (rating === 'nsfw' || rating === 'nsfl') await queue.genBlurredThumbnail(itemid, isApprovalRequired);
await queue.genBlurredThumbnail(itemid, isApprovalRequired);
} catch (err) {
console.error('[REHOST] Thumbnail error:', err);
}

View File

@@ -94,8 +94,7 @@ export default (router, tpl) => {
const util = await import('util');
const execFilePromise = util.promisify(execFile);
// If only 1 or 2 items, just use what we have
await execFilePromise('magick', [...inputs, '+append', '-background', 'none', '-resize', '300x150^', '-gravity', 'center', '-extent', '300x150', cachePath]);
await execFilePromise('magick', [...inputs, '+append', '-background', 'none', '-resize', '600x300^', '-gravity', 'center', '-extent', '600x300', cachePath]);
res.writeHead(200, { 'Content-Type': 'image/webp', 'Cache-Control': 'public, max-age=3600' });
return res.end(await fs.readFile(cachePath));

View File

@@ -2,6 +2,7 @@ import cfg from "../config.mjs";
import db from "../sql.mjs";
import lib from "../lib.mjs";
import f0cklib from "../routeinc/f0cklib.mjs";
import { createI18n } from "../i18n.mjs";
const auth = async (req, res, next) => {
if (!req.session)
@@ -62,9 +63,14 @@ export default (router, tpl) => {
};
try {
const isRandom = req.cookies.random_mode === '1';
const ratingsRaw = req.cookies.ratings;
// In All mode (mode=3), ignore the ratings cookie — it would otherwise
// filter out e.g. NSFW uploads even though the user is in "All" mode.
const ratingsArr = (req.mode === 3) ? null : (ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null);
f0cks = await f0cklib.getf0cks({
user: user,
mode: req.mode,
ratings: ratingsArr,
mime: mime,
fav: false,
session: !!req.session,
@@ -83,9 +89,14 @@ export default (router, tpl) => {
if (!userData.is_ghost) {
try {
const isRandom = req.cookies.random_mode === '1';
const ratingsRaw = req.cookies.ratings;
// In All mode (mode=3), ignore the ratings cookie — a stale ratings cookie
// (e.g. only 'sfw') would cause NSFW favorites to show 0 on the profile.
const ratingsArr = (req.mode === 3) ? null : (ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null);
favs = await f0cklib.getf0cks({
user: user,
mode: req.mode,
ratings: ratingsArr,
mime: mime,
fav: true,
session: !!req.session,
@@ -137,7 +148,7 @@ export default (router, tpl) => {
userData.timestamp = {
timeago: lib.timeAgo(userData.created_at, req.lang),
timefull: userData.created_at
timefull: new Date(userData.created_at).toISOString()
};
userData.age_days = Math.floor((Date.now() - new Date(userData.created_at).getTime()) / 86400000);
@@ -212,15 +223,19 @@ export default (router, tpl) => {
req.session.strict_mode = (req.query?.strict === '1' || req.url.qs?.strict === '1');
}
// Decode tag param once — browsers send title%3A... on hard reload, title:... via AJAX
const reqTag = req.params.tag ? decodeURIComponent(req.params.tag) : req.params.tag;
const data = await (req.params.itemid ? f0cklib.getf0ck : f0cklib.getf0cks)({
user: req.params.user,
tag: req.params.tag,
tag: reqTag,
mime: req.cookies.mime !== undefined ? req.cookies.mime : (req.query?.mime || req.url.qs?.mime || req.params.mime || null),
page: req.params.page,
itemid: req.params.itemid,
hall: req.params.hall,
fav: req.params.mode == 'favs',
mode: req.mode,
ratings: (() => { const r = req.cookies.ratings; return r ? decodeURIComponent(r).split(/[|,]/).filter(x => ['sfw','nsfw','nsfl','untagged'].includes(x)) : null; })(),
session: !!req.session,
user_id: req.session?.id,
exclude: req.session ? (req.session.excluded_tags || []) : [],
@@ -229,7 +244,8 @@ export default (router, tpl) => {
explicitStrict: !!(req.query?.strict || req.url.qs?.strict),
random: req.cookies.random_mode === '1',
minXdScore: req.params.itemid ? 0 : (req.url.qs?.min_xd !== undefined ? +req.url.qs.min_xd : (req.session?.min_xd_score || 0)),
lang: req.lang
lang: req.lang,
tagger: req.url.qs?.tagger || null
});
console.log(`[DEBUG] Checking strict mode: query=${req.query?.strict}, session=${req.session?.strict_mode}, effective=${!!(req.query?.strict || req.url.qs?.strict || req.session?.strict_mode)}`);
console.log(`[${new Date().toISOString()}] [ROUTE] Data fetch complete in ${Date.now() - tRouteStart}ms`);
@@ -243,7 +259,7 @@ export default (router, tpl) => {
data.success = true;
if (!data.link) {
if (req.params.hall) data.link = { main: '/h/' + encodeURIComponent(req.params.hall) + '/', path: 'p/', suffix: '' };
else if (req.params.tag) data.link = { main: '/tag/' + encodeURIComponent(req.params.tag) + '/', path: 'p/', suffix: '' };
else if (reqTag) data.link = { main: '/tag/' + encodeURIComponent(reqTag) + '/', path: 'p/', suffix: '' };
else data.link = { main: '/', path: 'p/', suffix: '' };
}
data.tmp = data.tmp || {};
@@ -251,18 +267,26 @@ export default (router, tpl) => {
const hallRow = await db`SELECT id, name, slug, description FROM halls WHERE slug = ${req.params.hall} LIMIT 1`;
data.tmp.hall = hallRow.length ? hallRow[0] : req.params.hall;
}
if (req.params.tag && !data.tmp.tag) data.tmp.tag = req.params.tag;
if (reqTag && !data.tmp.tag) data.tmp.tag = reqTag;
} else {
// Return 200 for filtered NSFW items (has item data) so Discord parses og:image
// Return 404 only for truly missing items
const statusCode = data.item ? 200 : 404;
const reqMode = req.mode ?? 0;
const modeLabels = { 0: 'SFW', 1: 'NSFW', 2: 'Untagged', 4: 'NSFL' };
const errorModeLabel = (req.session && reqMode !== 3) ? (modeLabels[reqMode] || null) : null;
const { t: tErr } = createI18n(req.session?.language || req.lang || 'en');
return res.reply({
code: statusCode,
body: tpl.render('error', {
message: data.message,
message: tErr('error.post_not_visible'),
item: data.item, // For OG meta tags on filtered NSFW items
domain: cfg.main.url.domain,
tmp: null
tmp: null,
session: req.session ? { ...req.session } : false,
error_mode_label: errorModeLabel,
error_filter_hint: errorModeLabel ? tErr('error.filter_hint', { mode: `<strong>${errorModeLabel}</strong>` }) : null,
error_filter_hint_link: tErr('error.filter_hint_link')
}, req)
});
}
@@ -333,7 +357,8 @@ export default (router, tpl) => {
// Can the current user manage this item (owner, admin, or mod)?
data.can_manage_item = !!(session && (session.admin || session.is_moderator || session.user === item.username));
// Is the item's MIME type suitable for metadata extraction?
data.can_extract_meta = !!(item.mime && item.mime.indexOf('flash') === -1 && item.mime.indexOf('youtube') === -1);
// YouTube items use oEmbed via /meta/fetch; all non-flash MIME types are eligible.
data.can_extract_meta = !!(item.mime && item.mime.indexOf('flash') === -1 && !(item.mime.startsWith('application/') && cfg.mimes[item.mime] && !['swf', 'pdf'].includes(cfg.mimes[item.mime])));
// Has the current user favorited this item?
data.user_has_favorited = !!(session && Array.isArray(item.favorites) && item.favorites.some(f => f.user === session.user));
// Hall columns for display
@@ -344,9 +369,11 @@ export default (router, tpl) => {
data.item_rating_label = item.is_nsfl ? 'NSFL' : (item.is_nsfw ? 'NSFW' : (item.is_sfw ? 'SFW' : '?'));
data.item_username_lower = (item.username || '').toLowerCase();
data.is_flash_item = !!(item.mime && (item.mime.indexOf('flash') !== -1 || item.mime.indexOf('shockwave') !== -1));
data.is_archive_item = !!(item.mime && item.mime.startsWith('application/') && cfg.mimes[item.mime] && !['swf', 'pdf'].includes(cfg.mimes[item.mime]));
data.current_hall_slug = (data.tmp && data.tmp.hall && typeof data.tmp.hall === 'object') ? data.tmp.hall.slug : (data.tmp && data.tmp.hall ? data.tmp.hall : '');
data.current_user_hall_slug = (data.tmp && data.tmp.userHall && typeof data.tmp.userHall === 'object') ? data.tmp.userHall.slug : (data.tmp && data.tmp.userHall ? data.tmp.userHall : '');
data.current_user_hall_owner = (data.tmp && data.tmp.userHallOwner) ? data.tmp.userHallOwner : '';
data.item_has_dimensions = !!(item.width && item.height);
}
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');

View File

@@ -29,6 +29,30 @@ export default (router, tpl) => {
});
});
// Custom meme template page
router.get(/^\/meme\/custom$/, lib.userauth, async (req, res) => {
if (!cfg.websrv.meme_creator) {
res.writeHead(404).end('Not Found');
return;
}
res.reply({
body: tpl.render('meme-creator', {
template: {
id: 'custom',
name: 'Custom Template',
url: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="800" height="600" viewBox="0 0 800 600"><rect width="800" height="600" fill="%231a1a1b"/><text x="50%25" y="50%25" fill="%23888888" font-family="sans-serif" font-size="24" dominant-baseline="middle" text-anchor="middle">Click %22Choose Image%22 or Drag and Drop here</text></svg>',
category: 'Custom',
sub_category: ''
},
page_meta: {
title: 'Create Meme - Custom Template',
description: 'Create a meme using your own custom template',
url: `https://${cfg.main.url.domain}/meme/custom`
}
}, req)
});
});
// Meme creator page
router.get(/^\/meme\/(?<id>[a-z0-9-]+)$/, lib.userauth, async (req, res) => {
if (!cfg.websrv.meme_creator) {

View File

@@ -209,7 +209,8 @@ export default (router, tpl) => {
pm.ciphertext,
pm.iv,
pm.is_read,
pm.created_at
pm.created_at,
pm.edited_at
FROM private_messages pm
WHERE (
(pm.sender_id = ${req.session.id} AND pm.recipient_id = ${otherId})
@@ -312,6 +313,81 @@ export default (router, tpl) => {
}
});
// Edit own message (re-encrypt in browser, send new ciphertext + iv)
router.patch(/\/api\/dm\/message\/(?<msgId>\d+)/, async (req, res) => {
if (!getPrivateMessages()) return json(res, { success: false, msg: 'Not found' }, 404);
if (!req.session) return json(res, { success: false, msg: 'Unauthorized' }, 401);
const csrf = req.headers['x-csrf-token'];
if (!csrf || csrf !== req.session.csrf_token) return json(res, { success: false, msg: 'CSRF mismatch' }, 403);
const msgId = parseInt(req.params.msgId, 10);
const body = req.post || {};
const { ciphertext, iv } = body;
if (!ciphertext || !iv || typeof ciphertext !== 'string' || typeof iv !== 'string') {
return json(res, { success: false, msg: 'Missing ciphertext or iv' }, 400);
}
if (ciphertext.length > 65536 || iv.length > 32) {
return json(res, { success: false, msg: 'Payload too large' }, 413);
}
try {
const result = await db`
UPDATE private_messages
SET ciphertext = ${ciphertext}, iv = ${iv}, edited_at = NOW()
WHERE id = ${msgId} AND sender_id = ${req.session.id}
RETURNING id, edited_at
`;
if (!result.length) return json(res, { success: false, msg: 'Not found or not yours' }, 404);
return json(res, { success: true, id: result[0].id, edited_at: result[0].edited_at });
} catch (err) {
console.error('[DM] edit message failed:', err);
return json(res, { success: false, msg: 'DB error' }, 500);
}
});
// Delete own message (and optionally its attachment blobs)
router.delete(/\/api\/dm\/message\/(?<msgId>\d+)/, async (req, res) => {
if (!getPrivateMessages()) return json(res, { success: false, msg: 'Not found' }, 404);
if (!req.session) return json(res, { success: false, msg: 'Unauthorized' }, 401);
const csrf = req.headers['x-csrf-token'];
if (!csrf || csrf !== req.session.csrf_token) return json(res, { success: false, msg: 'CSRF mismatch' }, 403);
const msgId = parseInt(req.params.msgId, 10);
const body = req.post || {};
const rawIds = body['attachment_ids[]'] ?? body.attachment_ids;
const attachmentIds = (Array.isArray(rawIds) ? rawIds : rawIds ? [rawIds] : [])
.map(Number).filter(n => Number.isFinite(n) && n > 0);
// Verify message belongs to sender
const rows = await db`SELECT id FROM private_messages WHERE id = ${msgId} AND sender_id = ${req.session.id} LIMIT 1`;
if (!rows.length) return json(res, { success: false, msg: 'Not found or not yours' }, 404);
try {
// Clean up attachments the client identified (verify sender ownership server-side)
if (attachmentIds.length) {
const { promises: fsP } = await import('fs');
const atts = await db`
SELECT id, file_path FROM dm_attachments
WHERE id = ANY(${attachmentIds}) AND sender_id = ${req.session.id}
`;
for (const att of atts) await fsP.unlink(att.file_path).catch(() => {});
if (atts.length) {
const ids = atts.map(a => a.id);
await db`DELETE FROM dm_attachments WHERE id = ANY(${ids})`;
}
}
await db`DELETE FROM private_messages WHERE id = ${msgId} AND sender_id = ${req.session.id}`;
return json(res, { success: true });
} catch (err) {
console.error('[DM] delete message failed:', err);
return json(res, { success: false, msg: 'DB error' }, 500);
}
});
// Hide a whole conversation (Close DM)
router.post(/\/api\/dm\/conversation\/(?<userId>\d+)\/delete/, async (req, res) => {
if (!getPrivateMessages()) return json(res, { success: false, msg: 'Not found' }, 404);
@@ -330,6 +406,24 @@ export default (router, tpl) => {
}
});
// Presence check — last_seen timestamp for a given user (online = seen < 5 min ago)
router.get(/\/api\/dm\/presence\/(?<userId>\d+)/, async (req, res) => {
if (!getPrivateMessages()) return json(res, { success: false }, 404);
if (!req.session) return json(res, { success: false }, 401);
const userId = parseInt(req.params.userId, 10);
try {
const rows = await db`SELECT last_seen FROM "user" WHERE id = ${userId} AND banned = false LIMIT 1`;
if (!rows.length) return json(res, { success: false, msg: 'User not found' }, 404);
const lastSeen = rows[0].last_seen || 0; // unix seconds
const now = ~~(Date.now() / 1000);
const online = (now - lastSeen) < 300; // 5-minute window
return json(res, { success: true, online, last_seen: lastSeen });
} catch (err) {
console.error('[DM] presence failed:', err);
return json(res, { success: false }, 500);
}
});
// Total unread DM count (for navbar badge polling)
router.get('/api/dm/unread', async (req, res) => {
if (!getPrivateMessages()) return json(res, { success: true, count: 0 });

View File

@@ -16,6 +16,7 @@ function broadcastChatPresence() {
if (!seen.has(client.userId)) {
seen.add(client.userId);
users.push({
id: client.userId,
username: client.username,
display_name: client.display_name,
avatar_file: client.avatar_file,
@@ -56,7 +57,8 @@ db.listen('notifications', (payload) => {
if (client.do_not_disturb === true) continue;
if (SYSTEM_TYPES.includes(data.type) && client.receive_system_notifications === false) continue;
if (USER_TYPES.includes(data.type) && client.receive_user_notifications === false) continue;
// warnings bypass user settings
if (data.type !== 'warning' && USER_TYPES.includes(data.type) && client.receive_user_notifications === false) continue;
client.send({ type: 'notify', data });
}
}
@@ -92,6 +94,20 @@ db.listen('profile_update', (payload) => {
if (data.do_not_disturb !== undefined) client.do_not_disturb = data.do_not_disturb;
client.send({ type: 'profile_update', data });
} else {
// For other users, only send public profile fields (so their DOM can live-update)
const publicData = {
user_id: data.user_id,
user: data.user,
display_name: data.display_name,
banner_file: data.banner_file,
banner_position: data.banner_position,
banner_size: data.banner_size,
avatar_file: data.avatar_file,
username_color: data.username_color,
description: data.description
};
client.send({ type: 'profile_update', data: publicData });
}
}
} catch (e) {
@@ -342,7 +358,9 @@ db.listen('global_chat_topic', (payload) => {
export default (router, tpl) => {
const USER_TYPES = ['comment_reply', 'subscription', 'mention', 'upload_comment'];
const SYSTEM_TYPES = ['approve', 'deny', 'item_deleted', 'upload_success', 'upload_error', 'admin_pending', 'report'];
const SYSTEM_TYPES = ['approve', 'deny', 'item_deleted', 'upload_success', 'upload_error', 'admin_pending', 'report', 'warning'];
const nsflTagId = cfg.nsfl_tag_id || 3;
async function getNotificationHistory(userId, page = 1, limit = 50, tab = null) {
const offset = (page - 1) * limit;
@@ -354,7 +372,13 @@ export default (router, tpl) => {
COALESCE(uo.display_name, '') as from_display_name,
COALESCE(u.id, 0) as from_user_id,
uo.username_color,
i.dest, i.mime
i.dest, i.mime,
CASE (SELECT ta.tag_id FROM tags_assign ta WHERE ta.item_id = n.item_id AND ta.tag_id IN (1, 2, ${nsflTagId}) LIMIT 1)
WHEN 1 THEN 'sfw'
WHEN 2 THEN 'nsfw'
WHEN ${nsflTagId} THEN 'nsfl'
ELSE NULL
END as item_mode
FROM notifications n
LEFT JOIN comments c ON n.reference_id = c.id
LEFT JOIN "user" u ON c.user_id = u.id
@@ -362,7 +386,7 @@ export default (router, tpl) => {
LEFT JOIN items i ON n.item_id = i.id
WHERE n.user_id = ${userId}
AND n.type = ANY(${typeFilter})
AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report') OR i.id IS NULL OR (i.active = true AND i.is_deleted = false))
AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report', 'warning') OR i.id IS NULL OR (i.active = true AND i.is_deleted = false))
ORDER BY n.created_at DESC
LIMIT ${limit + 1}
OFFSET ${offset}
@@ -373,14 +397,20 @@ export default (router, tpl) => {
COALESCE(uo.display_name, '') as from_display_name,
COALESCE(u.id, 0) as from_user_id,
uo.username_color,
i.dest, i.mime
i.dest, i.mime,
CASE (SELECT ta.tag_id FROM tags_assign ta WHERE ta.item_id = n.item_id AND ta.tag_id IN (1, 2, ${nsflTagId}) LIMIT 1)
WHEN 1 THEN 'sfw'
WHEN 2 THEN 'nsfw'
WHEN ${nsflTagId} THEN 'nsfl'
ELSE NULL
END as item_mode
FROM notifications n
LEFT JOIN comments c ON n.reference_id = c.id
LEFT JOIN "user" u ON c.user_id = u.id
LEFT JOIN user_options uo ON u.id = uo.user_id
LEFT JOIN items i ON n.item_id = i.id
WHERE n.user_id = ${userId}
AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report') OR i.id IS NULL OR (i.active = true AND i.is_deleted = false))
AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report', 'warning') OR i.id IS NULL OR (i.active = true AND i.is_deleted = false))
ORDER BY n.created_at DESC
LIMIT ${limit + 1}
OFFSET ${offset}
@@ -418,14 +448,20 @@ export default (router, tpl) => {
COALESCE(uo.display_name, '') as from_display_name,
COALESCE(u.id, 0) as from_user_id,
uo.username_color,
i.dest, i.mime
i.dest, i.mime,
CASE (SELECT ta.tag_id FROM tags_assign ta WHERE ta.item_id = n.item_id AND ta.tag_id IN (1, 2, ${nsflTagId}) LIMIT 1)
WHEN 1 THEN 'sfw'
WHEN 2 THEN 'nsfw'
WHEN ${nsflTagId} THEN 'nsfl'
ELSE NULL
END as item_mode
FROM notifications n
LEFT JOIN comments c ON n.reference_id = c.id
LEFT JOIN "user" u ON c.user_id = u.id
LEFT JOIN user_options uo ON u.id = uo.user_id
LEFT JOIN items i ON n.item_id = i.id
WHERE n.user_id = ${req.session.id} AND n.is_read = false
AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report', 'approve')
AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report', 'approve', 'warning')
OR (
${req.session.do_not_disturb !== true} AND (
(n.type IN ('upload_success', 'upload_error') AND ${req.session.receive_system_notifications !== false})
@@ -433,7 +469,7 @@ export default (router, tpl) => {
)
)
)
AND (n.item_id IS NULL OR (i.active = true AND i.is_deleted = false) OR n.type IN ('admin_pending', 'deny', 'item_deleted', 'report'))
AND (n.item_id IS NULL OR (i.active = true AND i.is_deleted = false) OR n.type IN ('admin_pending', 'deny', 'item_deleted', 'report', 'warning'))
ORDER BY n.created_at DESC
LIMIT 1000
`;
@@ -495,7 +531,7 @@ export default (router, tpl) => {
router.post(/\/api\/notifications\/item\/(?<itemId>\d+)\/read/, async (req, res) => {
if (!req.session) return res.reply({ code: 401, body: JSON.stringify({ success: false }) });
const itemId = req.params.itemId;
const SYSTEM_TYPES = ['item_deleted', 'deny', 'admin_pending', 'report'];
const SYSTEM_TYPES = ['item_deleted', 'deny', 'admin_pending', 'report', 'warning'];
console.log(`[NotificationRoute] Marking comment notifications for item ${itemId} as read for user ${req.session.id}`);
try {
await db`
@@ -645,7 +681,9 @@ export default (router, tpl) => {
next: data.hasMore ? 2 : null
};
data.link = { main: '/notifications', path: '/' };
data.activeTab = tab;
data.domain = cfg.main.url.domain; // For header
data.active_mode = req.session?.mode ?? 0;
return res.html(tpl.render('notifications', data, req));
});
@@ -658,7 +696,7 @@ export default (router, tpl) => {
const tab = req.url.qs.tab || null;
const data = await getNotificationHistory(req.session.id, page, 50, tab);
const html = tpl.render('snippets/notifications-list', data, req);
const html = tpl.render('snippets/notifications-list', { ...data, active_mode: req.session?.mode ?? 0 }, req);
return res.json({
success: true,

136
src/inc/routes/nsfp.mjs Normal file
View File

@@ -0,0 +1,136 @@
import db from "../sql.mjs";
import lib from "../lib.mjs";
import audit from "../audit.mjs";
import { getNsfpIds, setNsfpIds } from "../settings.mjs";
export default (router, tpl) => {
// Admin page
router.get(/^\/admin\/nsfp\/?$/, lib.auth, async (req, res) => {
try {
res.reply({
body: tpl.render("admin/nsfp", {
session: req.session,
totals: await lib.countf0cks(),
csrf_token: req.session?.csrf_token || ''
}, req)
});
} catch (err) {
console.error('[NSFP] Page render failed:', err);
res.reply({ code: 500, body: 'Internal server error' });
}
});
// API: list current NSFP tag IDs with names
router.get('/api/v2/admin/nsfp', lib.auth, async (req, res) => {
try {
const ids = getNsfpIds();
const tagRows = ids.length > 0
? await db`SELECT id, tag, normalized FROM tags WHERE id IN ${db(ids)} ORDER BY id`
: [];
const tagMap = Object.fromEntries(tagRows.map(r => [r.id, r]));
const enriched = ids.map(id => tagMap[id] || { id, tag: '(unknown)', normalized: null });
const blockedCount = ids.length > 0
? Number((await db`
SELECT COUNT(DISTINCT item_id) AS cnt
FROM tags_assign
WHERE tag_id IN ${db(ids)}
AND item_id IN (SELECT id FROM items WHERE active = true)
`)[0].cnt)
: 0;
return res.json({ success: true, nsfp: enriched, raw_ids: ids, blocked_count: blockedCount });
} catch (err) {
return res.json({ success: false, msg: err.message }, 500);
}
});
// API: search tags for the add-tag autocomplete
router.get('/api/v2/admin/nsfp/search', lib.auth, async (req, res) => {
try {
const q = (req.url.qs?.q || '').trim();
if (!q) return res.json({ success: true, tags: [] });
const pattern = '%' + q + '%';
const tags = await db`
SELECT id, tag, normalized
FROM tags
WHERE tag ILIKE ${pattern} OR normalized ILIKE ${pattern}
ORDER BY tag
LIMIT 20
`;
return res.json({ success: true, tags });
} catch (err) {
return res.json({ success: false, msg: err.message }, 500);
}
});
// API: add a tag ID to the NSFP list
router.post('/api/v2/admin/nsfp/add', lib.auth, async (req, res) => {
try {
const tagId = parseInt(req.post?.tag_id);
if (!tagId || isNaN(tagId) || tagId <= 0) {
return res.json({ success: false, msg: 'A valid tag_id is required' }, 400);
}
const tag = await db`SELECT id, tag FROM tags WHERE id = ${tagId} LIMIT 1`;
if (tag.length === 0) {
return res.json({ success: false, msg: 'Tag with id ' + tagId + ' does not exist' }, 404);
}
const current = getNsfpIds();
if (current.includes(tagId)) {
return res.json({ success: false, msg: 'Tag #' + tagId + ' (' + tag[0].tag + ') is already in the NSFP list' }, 409);
}
const updated = [...current, tagId];
setNsfpIds(updated);
await db`
INSERT INTO site_settings (key, value)
VALUES ('nsfp', ${JSON.stringify(updated)})
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value
`;
await audit.log(req.session.id, 'nsfp_add', 'tag', tagId, { tag: tag[0].tag, nsfp: updated });
return res.json({ success: true, nsfp_ids: getNsfpIds(), added: tag[0] });
} catch (err) {
console.error('[NSFP] Add failed:', err);
return res.json({ success: false, msg: err.message }, 500);
}
});
// API: remove a tag ID from the NSFP list
router.post('/api/v2/admin/nsfp/remove', lib.auth, async (req, res) => {
try {
const tagId = parseInt(req.post?.tag_id);
if (!tagId || isNaN(tagId)) {
return res.json({ success: false, msg: 'tag_id is required' }, 400);
}
const current = getNsfpIds();
if (!current.includes(tagId)) {
return res.json({ success: false, msg: 'Tag #' + tagId + ' is not in the NSFP list' }, 404);
}
const updated = current.filter(id => id !== tagId);
setNsfpIds(updated);
await db`
INSERT INTO site_settings (key, value)
VALUES ('nsfp', ${JSON.stringify(updated)})
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value
`;
await audit.log(req.session.id, 'nsfp_remove', 'tag', tagId, { nsfp: updated });
return res.json({ success: true, nsfp_ids: getNsfpIds() });
} catch (err) {
console.error('[NSFP] Remove failed:', err);
return res.json({ success: false, msg: err.message }, 500);
}
});
return router;
};

View File

@@ -39,6 +39,10 @@ export default (router, tpl) => {
}
}
const ratingsRaw = req.cookies.ratings;
const ratingsArr = ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null;
console.log('[RANDOM] ratings cookie:', ratingsRaw, '→ parsed:', ratingsArr);
const data = await f0cklib.getRandom({
user: opts.user,
tag: opts.tag,
@@ -47,6 +51,7 @@ export default (router, tpl) => {
page: opts.page,
fav: opts.mode === 'favs',
mode: req.mode,
ratings: ratingsArr,
strict: opts.strict,
session: !!req.session
});

View File

@@ -78,6 +78,11 @@ export default (router, tpl) => {
where items.active = true
`)[0].total;
const totalUsers = +(await db`
select count(*) as total
from "user"
`)[0].total;
const hoster = await db`
with t as (
select
@@ -135,6 +140,7 @@ export default (router, tpl) => {
xdtop,
totalComments,
totalFavs,
totalUsers,
enable_nsfl: config.enable_nsfl,
diskSize: cachedDiskSize,
tmp: null,

View File

@@ -1,7 +1,7 @@
import db from "../sql.mjs";
import lib from "../lib.mjs";
import security from "../security.mjs";
import { getRegistrationOpen, getDefaultLayout } from "../settings.mjs";
import { getRegistrationOpen, getRegistrationRequireMailAndorToken, getDefaultLayout } from "../settings.mjs";
import { sendMail } from "../../lib/smtp.mjs";
import cfg from "../config.mjs";
import crypto from "crypto";
@@ -48,7 +48,7 @@ export default (router, tpl) => {
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg: errorMsg }));
}
return res.reply({
body: tpl.render("register", { theme: req.cookies.theme ?? (cfg.websrv.theme || "f0ck"), error: errorMsg, registration_open: getRegistrationOpen() })
body: tpl.render("register", { theme: req.cookies?.theme ?? (cfg.websrv.theme || "f0ck"), error: errorMsg, registration_open: getRegistrationOpen() }, req)
});
}
@@ -58,7 +58,7 @@ export default (router, tpl) => {
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg }));
}
return res.reply({
body: tpl.render("register", { theme: req.cookies.theme ?? (cfg.websrv.theme || "f0ck"), error: msg, registration_open: getRegistrationOpen() })
body: tpl.render("register", { theme: req.cookies?.theme ?? (cfg.websrv.theme || "f0ck"), error: msg, registration_open: getRegistrationOpen() }, req)
});
};
@@ -67,7 +67,7 @@ export default (router, tpl) => {
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: true, msg }));
}
return res.reply({
body: tpl.render("register", { theme: req.cookies.theme ?? (cfg.websrv.theme || "f0ck"), success: msg, registration_open: getRegistrationOpen() })
body: tpl.render("register", { theme: req.cookies?.theme ?? (cfg.websrv.theme || "f0ck"), success: msg, registration_open: getRegistrationOpen() }, req)
});
};
@@ -88,26 +88,49 @@ export default (router, tpl) => {
return renderError("Passwords do not match.");
}
// Registration Logic
// reCAPTCHA verification (bypassed for .onion requests as Google reCAPTCHA cannot validate .onion domains)
const isOnion = lib.isOnionRequest(req);
if (!isOnion && cfg.recaptcha?.enabled && cfg.recaptcha?.secret_key) {
const rcToken = req.post['g-recaptcha-response'];
if (!rcToken) return renderError("Please complete the reCAPTCHA.");
try {
const verifyRes = await fetch('https://www.google.com/recaptcha/api/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ secret: cfg.recaptcha.secret_key, response: rcToken, remoteip: ip })
});
const { success } = await verifyRes.json();
if (!success) return renderError("reCAPTCHA verification failed. Please try again.");
} catch (e) {
console.error('[REGISTER] reCAPTCHA error:', e.message);
return renderError("reCAPTCHA check failed. Please try again.");
}
}
let activated = true;
let activationToken = null;
if (!token && !getRegistrationOpen()) {
const registrationOpen = getRegistrationOpen();
const requireMailOrToken = getRegistrationRequireMailAndorToken();
if (!registrationOpen && !token) {
// Closed registration — invite token is always required
return renderError("Invite token is required for registration.");
}
if (token) {
// Invite token path — validate and activate immediately
const tokenRow = await db`
select * from invite_tokens where token = ${token} and is_used = false
`;
if (tokenRow.length === 0) return renderError("Invalid or used invite token");
// Token used, so it will be activated by default
} else {
// No token, Open Registration
if (!email || !email.includes('@')) return renderError("A valid email is required for no-token registration.");
// Token is valid; account activated immediately
} else if (requireMailOrToken) {
// Open registration but email/token required — email path
if (!email || !email.includes('@')) return renderError("A valid email is required for registration.");
activated = false;
activationToken = crypto.randomBytes(32).toString('hex');
}
// else: open registration, no mail/token required — just username+password, activated immediately
// Check user existence
const existing = await db`
@@ -145,8 +168,8 @@ export default (router, tpl) => {
const avatarFile = 'default.png';
await db`
insert into user_options (user_id, mode, theme, fullscreen, avatar, avatar_file, use_new_layout, disable_autoplay, disable_swiping)
values (${userId}, 3, 'amoled', 0, ${avatarId}, ${avatarFile}, ${getDefaultLayout() === 'modern'}, ${cfg.websrv.enable_autoplay === false}, ${cfg.websrv.enable_swiping === false})
insert into user_options (user_id, mode, theme, fullscreen, avatar, avatar_file, use_new_layout, disable_autoplay, disable_swiping, use_alternative_infobox)
values (${userId}, 3, 'amoled', 0, ${avatarId}, ${avatarFile}, ${getDefaultLayout() === 'modern'}, ${cfg.websrv.enable_autoplay === false}, ${cfg.websrv.enable_swiping === false}, ${cfg.websrv.user_alternative_infobox !== false})
`;
} catch (err) {
console.error(`[REGISTER] DB Error during user creation:`, err);
@@ -186,7 +209,7 @@ export default (router, tpl) => {
if (tokenRow.length > 0) {
await db`
update invite_tokens
set is_used = true, used_by = ${userId}
set is_used = true, used_by = ${userId}, used_at = now()
where id = ${tokenRow[0].id}
`;
}

View File

@@ -4,22 +4,57 @@ import lib from "../lib.mjs";
export default (router, tpl) => {
// Serve the scroller page
router.get(/^\/abyss\/?$/, async (req, res) => {
router.get(/^\/abyss(?:\/(?<id>[a-zA-Z0-9_\/-]+))?\/?$/, async (req, res) => {
if (cfg.websrv.abyss_enabled === false) return res.reply({ code: 404, body: tpl.render('error', { message: 'Not found', tmp: null }, req) });
if (cfg.websrv.private_society && !req.session) {
return res.reply({ code: 502, body: '<html><body>502 Bad Gateway</body></html>' });
}
const id = req.params?.id || req.params?.[0];
console.log('[SCROLLER] URL:', req.url.pathname, 'Params:', req.params, 'ID:', id);
let page_meta = {
title: 'doomscroll',
description: 'Scroll through content endlessly',
url: `https://${cfg.main.url.domain}/abyss`
};
if (id && /^\d+$/.test(id.trim())) {
try {
const items = await db`
select i.*, uo.display_name
from "items" i
left join "user" u on u."user" = i.username or u.login = i.username
left join user_options uo on uo.user_id = u.id
where i.id = ${+id} and i.active = true
limit 1
`;
if (items.length > 0) {
const item = items[0];
// Fetch tags to check for NSFW/NSFL
const tags = await db`
select tag_id from tags_assign where item_id = ${+id}
`;
const tagIds = tags.map(t => t.tag_id);
const isBlurred = tagIds.includes(2) || tagIds.includes(cfg.nsfl_tag_id || 3);
page_meta.title = `${id}`;
page_meta.description = cfg.websrv.description || "The webs dumpster";
page_meta.url = `https://${cfg.main.url.domain}/abyss/${id}`;
page_meta.image = `https://${cfg.main.url.domain}/t/${id}${isBlurred ? '_blur' : ''}.webp`;
}
} catch (e) {
console.error('[SCROLLER] Failed to fetch meta for ID:', id, e);
}
}
return res.reply({
body: tpl.render('scroller', {
tmp: null,
session: req.session ? { ...req.session } : false,
enable_nsfl: !!cfg.enable_nsfl,
enable_swf: !!cfg.websrv.enable_swf,
page_meta: {
title: 'doomscroll',
description: 'Scroll through content endlessly',
url: `https://${cfg.main.url.domain}/abyss`
}
page_meta
}, req)
});
});
@@ -131,8 +166,12 @@ export default (router, tpl) => {
const anchorId = qs.anchor ? parseInt(qs.anchor, 10) : null;
const swfMimes = ['application/x-shockwave-flash', 'application/vnd.adobe.flash.movie'];
const archiveMimes = Object.entries(cfg.mimes)
.filter(([mime, ext]) => mime.startsWith('application/') && !['swf', 'pdf'].includes(ext))
.map(([mime]) => mime);
const excludeSwfSQL = !cfg.websrv.enable_swf ? db`AND items.mime != ALL(${swfMimes})` : db``;
const excludePdfSQL = db`AND items.mime != 'application/pdf'`;
const excludeArchiveSQL = db`AND items.mime != ALL(${archiveMimes})`;
const mimeParts = (mime || '').split(',').filter(m => ['video', 'audio', 'image'].includes(m));
const mimeSQL = mimeParts.length > 0
? db`AND (${mimeParts.map(m => db`items.mime ilike ${m + '/%'}`).reduce((a, b) => db`${a} OR ${b}`)})`
@@ -211,7 +250,9 @@ export default (router, tpl) => {
WHERE items.id = ${anchorId}
AND items.active = true
AND ${db.unsafe(modeQuery)}
${excludeSwfSQL}
${excludePdfSQL}
${excludeArchiveSQL}
${!req.session && nsfp ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND (${db.unsafe(nsfp)}))` : db``}
`;
// If the anchor item doesn't pass the rating filter, it's inaccessible to this user.
@@ -229,6 +270,7 @@ export default (router, tpl) => {
AND items.active = true
${excludeSwfSQL}
${excludePdfSQL}
${excludeArchiveSQL}
AND items.id != ${anchorId}
${excludeSQL}
${mimeSQL}
@@ -252,6 +294,7 @@ export default (router, tpl) => {
AND items.active = true
${excludeSwfSQL}
${excludePdfSQL}
${excludeArchiveSQL}
${cursorSQL}
${excludeSQL}
${mimeSQL}
@@ -263,6 +306,8 @@ export default (router, tpl) => {
`;
}
const ytSrcRegex = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\/?\/?\?(?:\S*?&?v=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/i;
const items = rows.map(row => {
const isVideo = row.mime && row.mime.startsWith('video') && row.mime !== 'video/youtube';
const isYouTube = row.mime === 'video/youtube';
@@ -270,7 +315,16 @@ export default (router, tpl) => {
const isImage = row.mime && row.mime.startsWith('image');
let dest = row.dest;
if (!isYouTube && dest) dest = `${cfg.websrv.paths.images}/${row.dest}`;
if (isYouTube) {
// Guard against dest values corrupted by the UUID backfill script:
// dest should be "yt:VIDEO_ID" — if it isn't, recover the ID from src.
if (!dest || !dest.startsWith('yt:')) {
const m = row.src && row.src.match(ytSrcRegex);
if (m) dest = `yt:${m[1]}`;
}
} else if (dest) {
dest = `${cfg.websrv.paths.images}/${row.dest}`;
}
const thumbnail = `${cfg.websrv.paths.thumbnails}/${row.id}.webp`;
let ratingLabel = '?'; let ratingClass = 'untagged';
@@ -295,6 +349,7 @@ export default (router, tpl) => {
fav_count: +row.fav_count || 0,
comment_count: +row.comment_count || 0,
is_swf: !!(row.mime === 'application/x-shockwave-flash' || row.mime === 'application/vnd.adobe.flash.movie'),
is_archive: !!(row.mime && archiveMimes.includes(row.mime)),
is_video: isVideo,
is_youtube: isYouTube,
is_audio: isAudio,

View File

@@ -56,6 +56,48 @@ export default (router, tpl) => {
path: '&page='
};
}
else if (tag.startsWith('title:')) {
const titleQuery = tag.substring(6).trim();
const q = '%' + titleQuery + '%';
total = (await db`
select count(*) as total
from "items"
where title ilike ${q} and active = true
`)[0]?.total ?? 0;
total = +total;
const pages = +Math.ceil(total / _eps);
const act_page = Math.min(Math.max(pages, 1), page || 1);
const offset = Math.max(0, (act_page - 1) * _eps);
ret = await db`
select *
from "items"
where title ilike ${q} and active = true
order by id desc
offset ${offset}
limit ${_eps}
`;
const cheat = [];
for (let i = Math.max(1, act_page - 3); i <= Math.min(act_page + 3, pages); i++)
cheat.push(i);
pagination = {
start: 1,
end: pages,
prev: (act_page > 1) ? act_page - 1 : null,
next: (act_page < pages) ? act_page + 1 : null,
page: act_page,
cheat: cheat,
uff: false
};
link = {
main: `/search/?tag=${encodeURIComponent(tag)}`,
path: '&page='
};
}
else if (mode === 'strict') {
const tags = tag.split(',').map(t => t.trim()).filter(t => t.length > 0);

View File

@@ -23,9 +23,9 @@ export default (router, tpl) => {
join tags t on t.id = et.id
`;
// Get custom avatar file if exists
// Get custom avatar file and banner file if exists
const userOptions = (await db`
select avatar_file from user_options where user_id = ${+req.session.id}
select avatar_file, banner_file from user_options where user_id = ${+req.session.id}
`)[0];
// Get full user info
@@ -46,10 +46,16 @@ export default (router, tpl) => {
sessions,
excluded_tags: excluded_tags || [],
avatar_file: userOptions?.avatar_file || null,
banner_file: userOptions?.banner_file || null,
banner_position: userOptions?.banner_position || 'center',
banner_size: userOptions?.banner_size || 'cover',
email: user?.email || '',
joined: user?.created_at || null,
user_banner_enabled: cfg.websrv.user_banner_enabled !== false,
enable_swf: cfg.enable_swf,
enable_data_export: cfg.websrv.enable_data_export,
enable_user_api_keys: cfg.websrv.enable_user_api_keys !== false,
enable_user_invites: cfg.websrv.enable_user_invites !== false,
site_domain: cfg.main.url.domain,
session: (req.session && req.session.user) ? { ...req.session } : false,
page_meta: {

View File

@@ -23,6 +23,11 @@ export default (router, tpl) => {
route: /^\/s\/koepfe\//
});
router.static({
dir: cfg.paths.fonts,
route: /^\/s\/fonts\//
});
router.static({
dir: path.join(path.resolve(), 'node_modules/@ruffle-rs/ruffle'),
route: /^\/s\/ruffle\//

View File

@@ -40,7 +40,7 @@ export async function regenerateTagImage(tag, mode) {
const inputs = items.map(item => path.join(cfg.paths.t, `${item.id}.webp`));
await fs.mkdir(path.dirname(cachePath), { recursive: true });
await execFilePromise('magick', [...inputs, '+append', '-background', 'none', '-resize', '300x150^', '-gravity', 'center', '-extent', '300x150', cachePath]);
await execFilePromise('magick', [...inputs, '+append', '-background', 'none', '-resize', '600x300^', '-gravity', 'center', '-extent', '600x300', cachePath]);
return cachePath;
}
} catch (err) {
@@ -123,17 +123,17 @@ function generateFallbackSvg(tag) {
const n2 = parseInt(hash.substring(20, 22), 16);
return `
<svg width="300" height="150" viewBox="0 0 300 150" xmlns="http://www.w3.org/2000/svg">
<svg width="600" height="300" viewBox="0 0 600 300" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:${c1};stop-opacity:1" />
<stop offset="100%" style="stop-color:${c2};stop-opacity:1" />
</linearGradient>
</defs>
<rect width="300" height="150" fill="url(#grad)" />
<circle cx="${n1}%" cy="${n2}%" r="${(n1 + n2) / 4}" fill="${c3}" fill-opacity="0.3" />
<circle cx="${100 - n1}%" cy="${100 - n2}%" r="${(n1 + n2) / 3}" fill="${c3}" fill-opacity="0.2" />
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-size="24" fill="#fff" fill-opacity="0.9" font-weight="bold">${displayTag}</text>
<rect width="600" height="300" fill="url(#grad)" />
<circle cx="${n1}%" cy="${n2}%" r="${(n1 + n2) / 2}" fill="${c3}" fill-opacity="0.25" />
<circle cx="${100 - n1}%" cy="${100 - n2}%" r="${(n1 + n2) / 1.5}" fill="${c3}" fill-opacity="0.15" />
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="monospace, sans-serif" font-size="36" fill="#fff" fill-opacity="0.95" font-weight="bold">${displayTag}</text>
</svg>
`.trim();
}

View File

@@ -95,7 +95,7 @@ export default (router, tpl) => {
if (req.headers['x-requested-with'] === 'XMLHttpRequest' || query.ajax) {
return res.json({
success: true,
html: tpl.render('tag-cards', { toptags: tags, session: (req.session && req.session.user) ? { ...req.session } : false }, req),
html: tpl.render('tag-cards', { toptags: tags, user: req.session?.user ? { user: req.session.user } : null, session: (req.session && req.session.user) ? { ...req.session } : false }, req),
currentPage: page,
hasMore: tags.length === TAGS_PER_PAGE
});
@@ -128,6 +128,7 @@ export default (router, tpl) => {
phrase,
tmp: null,
hidePagination: true,
user: req.session?.user ? { user: req.session.user } : null,
session: (req.session && req.session.user) ? { ...req.session } : false,
page_meta: {
title: 'Tags',

View File

@@ -163,7 +163,7 @@ export default (router, tpl) => {
const item = data.item;
data.is_mod_or_admin = !!(session && (session.admin || session.is_moderator));
data.can_manage_item = !!(session && (session.admin || session.is_moderator || session.user === item.username));
data.can_extract_meta = !!(item.mime && item.mime.indexOf('flash') === -1 && item.mime.indexOf('youtube') === -1);
data.can_extract_meta = !!(item.mime && item.mime.indexOf('flash') === -1 && !(item.mime.startsWith('application/') && cfg.mimes[item.mime] && !['swf', 'pdf'].includes(cfg.mimes[item.mime])));
data.user_has_favorited = !!(session && Array.isArray(item.favorites) && item.favorites.some(f => f.user === session.user));
data.halls_slugs = Array.isArray(item.halls) ? item.halls.map(h => h.slug).join(',') : '';
data.user_halls_slugs = Array.isArray(item.user_halls) ? item.user_halls.map(h => h.slug).join(',') : '';
@@ -171,9 +171,11 @@ export default (router, tpl) => {
data.item_rating_label = item.is_nsfl ? 'NSFL' : (item.is_nsfw ? 'NSFW' : (item.is_sfw ? 'SFW' : '?'));
data.item_username_lower = (item.username || '').toLowerCase();
data.is_flash_item = !!(item.mime && (item.mime.indexOf('flash') !== -1 || item.mime.indexOf('shockwave') !== -1));
data.is_archive_item = !!(item.mime && item.mime.startsWith('application/') && cfg.mimes[item.mime] && !['swf', 'pdf'].includes(cfg.mimes[item.mime]));
data.current_hall_slug = (data.tmp && data.tmp.hall && typeof data.tmp.hall === 'object') ? data.tmp.hall.slug : (data.tmp && data.tmp.hall ? data.tmp.hall : '');
data.current_user_hall_slug = (data.tmp && data.tmp.userHall && typeof data.tmp.userHall === 'object') ? data.tmp.userHall.slug : (data.tmp && data.tmp.userHall ? data.tmp.userHall : '');
data.current_user_hall_owner = (data.tmp && data.tmp.userHallOwner) ? data.tmp.userHallOwner : '';
data.item_has_dimensions = !!(item.width && item.height);
}
// Precompute hall display
@@ -268,7 +270,7 @@ export default (router, tpl) => {
await fs.mkdir(CACHE_DIR, { recursive: true });
await execFile('magick', [
...inputs, '+append', '-background', 'none',
'-resize', '300x150^', '-gravity', 'center', '-extent', '300x150', cachePath
'-resize', '600x300^', '-gravity', 'center', '-extent', '600x300', cachePath
]);
res.writeHead(200, { 'Content-Type': 'image/webp', 'Cache-Control': 'public, max-age=3600' });
return res.end(await fs.readFile(cachePath));

View File

@@ -0,0 +1,197 @@
import db from "../../inc/sql.mjs";
import lib from "../../inc/lib.mjs";
import cfg from "../../inc/config.mjs";
import url from "url";
const TAGS_PER_PAGE = 50; // Smaller chunks for better infinite scroll
export default (router, tpl) => {
const getTagsQuery = async (userId, mode, offset, limit, sessionObj = false, strict = false) => {
const excludedTags = sessionObj ? (sessionObj.excluded_tags || []) : [];
const isGuest = !sessionObj;
const modequery = lib.getMode(mode);
let restrictedFilter = db``;
if (isGuest && cfg.nsfp && cfg.nsfp.length > 0) {
restrictedFilter = db`
AND t.id NOT IN ${db(cfg.nsfp)}
AND NOT EXISTS (
SELECT 1 FROM tags_assign ta_res
WHERE ta_res.item_id = items.id
AND ta_res.tag_id IN ${db(cfg.nsfp)}
)
`;
}
const userExcludeFilter = excludedTags.length > 0
? db`AND NOT EXISTS (SELECT 1 FROM tags_assign ta_ex WHERE ta_ex.item_id = items.id AND ta_ex.tag_id = ANY(${excludedTags}::int[]))`
: db``;
// Step 1: Get tags sorted by exact count (fast, indexed)
// Group by normalized to merge duplicates (e.g. "Music" and "music")
const baseTags = await db`
SELECT MIN(t.id) as id, MIN(t.tag) as tag, t.normalized, COUNT(DISTINCT items.id) AS total_items
FROM tags t
JOIN tags_assign ta ON t.id = ta.tag_id
JOIN items ON items.id = ta.item_id
WHERE items.active = true
AND t.id NOT IN (1, 2)
AND ta.user_id = ${userId}
AND ${db.unsafe(modequery)}
${restrictedFilter}
${userExcludeFilter}
GROUP BY t.normalized
HAVING COUNT(DISTINCT items.id) >= 1
ORDER BY total_items DESC, MIN(t.id) DESC
OFFSET ${offset}
LIMIT ${limit}
`;
// Step 2: In normal (non-strict) mode, replace counts with fuzzy counts
// Only runs for the ~50 tags being displayed, not all tags
if (!strict && baseTags.length > 0) {
await Promise.all(baseTags.map(async (tag) => {
if (!tag.normalized) return;
const [row] = await db`
SELECT COUNT(DISTINCT items.id) as total
FROM tags t
JOIN tags_assign ta ON t.id = ta.tag_id
JOIN items ON items.id = ta.item_id
WHERE t.normalized LIKE '%' || ${tag.normalized} || '%'
AND items.active = true
AND ta.user_id = ${userId}
AND ${db.unsafe(modequery)}
${restrictedFilter}
${userExcludeFilter}
`;
tag.total_items = +row.total;
}));
}
return baseTags;
};
const processTags = (tags) => tags.map(t => ({
...t,
safe_tag: t.normalized || encodeURIComponent(t.tag),
encoded_tag: encodeURIComponent(t.tag)
}));
// API endpoint for lazy loading tags for a user
router.get(/^\/api\/user\/(?<user>[^\/]+)\/tags$/, async (req, res) => {
const userParam = decodeURIComponent(req.params.user);
const u = await db`
SELECT "user".id, "user".user
FROM "user"
WHERE "user".user ILIKE ${userParam}
`;
if (!u.length) {
return res.reply({ code: 404, body: JSON.stringify({ success: false, msg: "User not found" }) });
}
const userId = u[0].id;
const userName = u[0].user;
let query = {};
if (typeof req.url === 'string') {
const parsedUrl = url.parse(req.url, true);
query = parsedUrl.query;
} else {
query = req.url.qs || {};
}
const page = Math.max(1, +(query.page ?? 1));
const offset = (page - 1) * TAGS_PER_PAGE;
const mode = req.mode ?? 0;
const isStrict = !!(query.strict === '1' || req.session?.strict_mode);
const tags = processTags(await getTagsQuery(userId, mode, offset, TAGS_PER_PAGE, req.session, isStrict));
if (req.headers['x-requested-with'] === 'XMLHttpRequest' || query.ajax) {
const paginationHtml = tpl.render('snippets/pagination', {
pagination: {
page: page,
prev: page > 1 ? page - 1 : null,
next: tags.length === TAGS_PER_PAGE ? page + 1 : null,
cheat: [1]
},
link: `/user/${encodeURIComponent(userName)}/tags`
}, req);
return res.json({
success: true,
html: tpl.render('tag-cards', { toptags: tags, user: { user: userName }, session: (req.session && req.session.user) ? { ...req.session } : false }, req),
currentPage: page,
pagination: paginationHtml,
hasMore: tags.length === TAGS_PER_PAGE
});
}
res.json({
success: true,
tags,
currentPage: page,
hasMore: tags.length === TAGS_PER_PAGE
});
});
// Main tags page
router.get(/^\/user\/(?<user>[^\/]+)\/tags$/, async (req, res) => {
const userParam = decodeURIComponent(req.params.user);
const u = await db`
SELECT "user".id, "user".user, user_options.avatar, user_options.avatar_file, user_options.username_color
FROM "user"
LEFT JOIN user_options ON "user".id = user_options.user_id
WHERE "user".user ILIKE ${userParam}
`;
if (!u.length) {
return res.reply({ code: 404, body: "User not found" });
}
const userRow = u[0];
const userId = userRow.id;
const mode = req.mode ?? 0;
const query = req.url.qs || {};
const isStrict = !!(query.strict === '1' || req.session?.strict_mode);
const toptags = processTags(await getTagsQuery(userId, mode, 0, TAGS_PER_PAGE, req.session, isStrict));
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
res.setHeader('Surrogate-Control', 'no-store');
const data = {
user: userRow,
toptags: toptags,
tmp: null,
hidePagination: false,
pagination: {
page: 1,
prev: null,
next: toptags.length === TAGS_PER_PAGE ? 2 : null,
cheat: [1]
},
link: `/user/${encodeURIComponent(userRow.user)}/tags`,
session: (req.session && req.session.user) ? { ...req.session } : false,
page_meta: {
title: `${userRow.user}'s Tags`,
description: `Browse ${toptags.length}+ tags made by ${userRow.user}`,
url: `https://${cfg.main.url.domain}/user/${encodeURIComponent(userRow.user)}/tags`
}
};
if (req.headers['x-requested-with'] === 'XMLHttpRequest') {
return res.reply({
body: tpl.render('tags_user-partial', data, req)
});
}
res.reply({
body: tpl.render('tags_user', data, req)
});
});
return router;
};

View File

@@ -21,6 +21,11 @@ export default (router, tpl) => {
// Broadcast to SSE clients instantly
if (result.length > 0) {
await db`
INSERT INTO notifications (user_id, type, reference_id, data, is_read)
VALUES (${+user_id}, 'warning', 0, ${JSON.stringify({ reason: reason.trim(), warning_id: result[0].id })}, false)
`;
await db`SELECT pg_notify('warnings', ${JSON.stringify({
user_id: +user_id,
warning_id: result[0].id,

View File

@@ -0,0 +1,83 @@
import db from "../sql.mjs";
import lib from "../lib.mjs";
import audit from "../audit.mjs";
export default (router, tpl) => {
// Auto-migration on startup
db`CREATE TABLE IF NOT EXISTS public.wordfilter (
id SERIAL PRIMARY KEY,
word VARCHAR(255) NOT NULL UNIQUE,
replacement VARCHAR(255) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
)`.catch(err => console.error('[WORDFILTER] DB Table Setup Failed:', err));
// Admin View Render
router.get(/^\/admin\/wordfilter\/?$/, lib.auth, async (req, res) => {
res.reply({
body: tpl.render("admin/wordfilter", {
session: req.session,
totals: await lib.countf0cks(),
csrf_token: req.session?.csrf_token || ''
}, req)
});
});
// API list rules
router.get('/api/v2/admin/wordfilter', lib.auth, async (req, res) => {
try {
const filters = await db`SELECT * FROM wordfilter ORDER BY created_at DESC`;
return res.json({ success: true, filters });
} catch (err) {
return res.json({ success: false, msg: err.message }, 500);
}
});
// API create rule
router.post('/api/v2/admin/wordfilter', lib.auth, async (req, res) => {
try {
const { word, replacement } = req.post || {};
if (!word || !word.trim() || !replacement || !replacement.trim()) {
return res.json({ success: false, msg: 'Word and replacement are required' }, 400);
}
const cleanWord = word.trim();
const cleanReplacement = replacement.trim();
// Ensure no infinite loops or matches
if (cleanWord.toLowerCase() === cleanReplacement.toLowerCase()) {
return res.json({ success: false, msg: 'Word and replacement cannot be identical' }, 400);
}
await db`
INSERT INTO wordfilter (word, replacement)
VALUES (${cleanWord}, ${cleanReplacement})
ON CONFLICT (word) DO UPDATE SET replacement = EXCLUDED.replacement
`;
await audit.log(req.session.id, 'add_wordfilter', 'wordfilter', 0, { word: cleanWord, replacement: cleanReplacement });
return res.json({ success: true });
} catch (err) {
return res.json({ success: false, msg: err.message }, 500);
}
});
// API delete rule
router.post('/api/v2/admin/wordfilter/delete', lib.auth, async (req, res) => {
try {
const { id } = req.post || {};
if (!id) return res.json({ success: false, msg: 'ID required' }, 400);
const rows = await db`DELETE FROM wordfilter WHERE id = ${id} RETURNING word`;
if (rows.length > 0) {
await audit.log(req.session.id, 'delete_wordfilter', 'wordfilter', id, { word: rows[0].word });
}
return res.json({ success: true });
} catch (err) {
return res.json({ success: false, msg: err.message }, 500);
}
});
return router;
};

View File

@@ -7,6 +7,8 @@ let trusted_uploads = 0;
let bypass_duplicate_check = false;
let protect_files = false;
let private_messages = true;
let dm_attachments = true;
let dm_unencrypted = false;
let default_layout = 'modern';
let enable_pdf = false;
let enable_cleanup = false;
@@ -47,6 +49,11 @@ export const getRegistrationOpen = () => {
};
export const setRegistrationOpen = (val) => registration_open = !!val;
// When false (default): open_registration=true means anyone can register with just username+password, activated immediately.
// When true: even in open registration, a valid email OR invite token is required.
export const getRegistrationRequireMailAndorToken = () => !!cfg.websrv.open_registration_require_mail_andor_token;
export const setRegistrationRequireMailAndorToken = (val) => {}; // No-op, strictly config-based
export const getTrustedUploads = () => trusted_uploads;
export const setTrustedUploads = (val) => trusted_uploads = Math.max(0, parseInt(val) ?? 3);
@@ -59,6 +66,17 @@ export const setProtectFiles = (val) => protect_files = !!val;
export const getPrivateMessages = () => private_messages;
export const setPrivateMessages = (val) => private_messages = !!val;
export const getDmAttachments = () => dm_attachments;
export const setDmAttachments = (val) => dm_attachments = !!val;
export const getDmUnencrypted = () => dm_unencrypted;
export const setDmUnencrypted = (val) => dm_unencrypted = !!val;
export const getDmAttachmentExpiryDays = () => {
const v = parseInt(cfg.websrv.dm_attachment_expiry_days);
return (Number.isFinite(v) && v > 0) ? v : 90;
};
export const getDefaultLayout = () => default_layout;
export const setDefaultLayout = (val) => default_layout = (val === 'legacy' ? 'legacy' : 'modern');
@@ -67,3 +85,17 @@ export const setLogUserIps = (val) => {}; // No-op, strictly config-based
export const getHashUserIps = () => !!cfg.websrv.hash_user_ips;
export const setHashUserIps = (val) => {}; // No-op, strictly config-based
export const getAllowCommentDeletion = () => !!cfg.websrv.allow_comment_deletion;
export const setAllowCommentDeletion = (val) => {}; // No-op, strictly config-based
// Live-editable NSFP tag ID list — seeded from config.json, can be overridden by DB setting
let nsfp_ids = Array.isArray(cfg.nsfp) ? [...cfg.nsfp.map(Number).filter(n => !isNaN(n))] : [];
export const getNsfpIds = () => nsfp_ids;
export const setNsfpIds = (ids) => {
nsfp_ids = Array.isArray(ids) ? ids.map(Number).filter(n => !isNaN(n) && n > 0) : [];
// Also sync to cfg.nsfp so all code reading cfg.nsfp directly still works
cfg.nsfp = [...nsfp_ids];
};

View File

@@ -2,7 +2,7 @@ import cfg from "../config.mjs";
import db from "../sql.mjs";
import lib from "../lib.mjs";
const regex = new RegExp(`(https?:\\/\\/${cfg.main.url.regex})(\\/(?:video|image|audio|tag\\/[^/\\s]+|user\\/[^/\\s]+(?:\\/favs)?))?\\/(\\d+|(?:b\\/)\\w{8}\\.(?:jpg|webm|gif|mp4|png|mov|mp3|ogg|flac))`, 'gi');
const regex = new RegExp(`(https?:\\/\\/${cfg.main.url.regex})(\\/(?:video|image|audio|tag\\/[^/\\s]+|user\\/[^/\\s]+(?:\\/favs)?|h\\/[^/\\s]+))?\\/(\\d+|(?:b\\/)\\w{8}\\.(?:jpg|webm|gif|mp4|png|mov|mp3|ogg|flac))`, 'gi');
export default async bot => {
@@ -12,9 +12,10 @@ export default async bot => {
active: true,
f: async e => {
const dat = e.message.match(regex)[0].split(/\//).pop();
const nsflId = cfg.nsfl_tag_id || 3;
const rows = await db`
select i.id, i.mime, i.size, i.username, i.stamp,
(select t.tag from tags_assign ta join tags t on t.id = ta.tag_id where ta.item_id = i.id and t.id in (1,2) limit 1) as rating
(select t.tag from tags_assign ta join tags t on t.id = ta.tag_id where ta.item_id = i.id and ta.tag_id in (1, 2, ${nsflId}) order by ta.tag_id asc limit 1) as rating
from "items" i
${dat.includes('.')
? db`where i.dest = ${dat}`
@@ -32,15 +33,6 @@ export default async bot => {
if (e.type === 'irc') {
const color = rating === 'sfw' ? 'green' : (rating === 'nsfw' ? 'red' : 'brown');
ratingStr = `[color=${color}]${rating}[/color]`;
} else if (e.type === 'matrix') {
const color = rating === 'sfw' ? '#00ff00' : (rating === 'nsfw' ? '#ff0000' : '#888888');
ratingStr = `[b][color=${color}]${rating}[/color][/b]`;
// matrix.mjs format() handles [b], but not [color].
// However, matrix.mjs send() handles objects with formatted_body.
// Let's use a simpler approach that works with the existing formatter if possible,
// or just construct the object.
} else if (e.type === 'tg') {
ratingStr = `[b]${rating}[/b]`;
}
const link = `${cfg.main.url.full}/${row.id}`.replace('http://', 'https://');

View File

@@ -1,4 +1,5 @@
import { getLevel } from "../admin.mjs";
import cfg from "../config.mjs";
export default async self => {
return [{
@@ -45,10 +46,11 @@ export default async self => {
// Deduplicate and sort
const uniqueCommands = [...new Set(availableCommands)].sort();
const trigger = cfg.main.trigger || "!w";
if (uniqueCommands.length === 0) {
availableCommands.push(e.type === 'matrix' ? "!w -sfw/nsfw -t tag1,tag2,tag3" : "!w <url> or attachment");
availableCommands.push(e.type === 'matrix' ? `${trigger} -sfw/nsfw -t tag1,tag2,tag3` : `${trigger} <url> or attachment`);
} else {
availableCommands.push(e.type === 'matrix' ? "!w -sfw/nsfw -t tag1,tag2,tag3" : "!w <url> or attachment");
availableCommands.push(e.type === 'matrix' ? `${trigger} -sfw/nsfw -t tag1,tag2,tag3` : `${trigger} <url> or attachment`);
}
// Re-sort to include manually added command

View File

@@ -37,11 +37,56 @@ const extractJSON = (stdout) => {
}
};
const sanitizeLogUrl = url => typeof url === 'string' ? url.replace(/\/bot[0-9a-zA-Z_-]+/i, '/bot<token>') : url;
const getMimeViaCurl = async (link) => {
try {
let referer = link;
try {
const parsedUrl = new URL(link);
let host = parsedUrl.hostname;
const parts = host.split('.');
if (parts.length >= 2) {
host = parts.slice(-2).join('.');
}
referer = `${parsedUrl.protocol}//${host}/`;
} catch(e) {}
const curlArgs = ['-I', '-s', '-f', '-L', '--user-agent', pcUA, '--referer', referer, link];
if (cfg.main.socks && cfg.main.socks !== 'undefined' && cfg.main.socks !== '') {
const proxyHost = cfg.main.socks.includes('://') ? cfg.main.socks.split('://')[1] : cfg.main.socks;
curlArgs.push('--socks5-hostname', proxyHost);
}
const headOut = await queue.spawn('curl', curlArgs);
const contentTypeMatch = headOut.stdout.match(/content-type:\s*([^\r\n]+)/i);
if (contentTypeMatch) {
let tmphead = contentTypeMatch[1].trim();
if (tmphead.includes(';')) {
tmphead = tmphead.split(';')[0].trim();
}
tmphead = tmphead.toLowerCase();
const ext = cfg.mimes[tmphead];
if (ext) {
console.log(`[PARSER DEBUG] Generic Metadata Fallback (curl) success: ${tmphead} -> ${ext}`);
return ext;
} else {
console.warn(`[PARSER DEBUG] Generic Metadata Fallback (curl) unsupported MIME: "${tmphead}"`);
}
}
} catch(fErr) {
console.error(`[METADATA ERROR] Generic Fallback curl failed for ${sanitizeLogUrl(link)}:`, fErr.message);
}
return null;
};
const trigger = cfg.main.trigger || "!w";
const escapedTrigger = trigger.replace(/[.*+?^${}()|[\\]\\]/g, '\\$&');
export default async bot => {
return [{
name: "parser",
call: new RegExp(`${regex.all.source}|^!w(0bm)?\\b`, 'i'),
call: new RegExp(`${regex.all.source}|^${escapedTrigger}(0bm)?\\b`, 'i'),
active: true,
clients: ["irc", "tg", "slack", "discord", "matrix"],
f: async e => {
@@ -98,6 +143,47 @@ export default async bot => {
if (replyLinks) links.push(...replyLinks);
}
}
// Telegram: reply to a media message with !w
if (e.type === 'tg' && e.raw?.reply_to_message) {
const replied = e.raw.reply_to_message;
console.log(`[PARSER DEBUG] TG reply_to_message keys: ${Object.keys(replied).join(', ')}`);
// Try to resolve a media file from the replied-to message
const allowedTgKeys = ['video', 'audio', 'photo', 'document', 'animation', 'voice', 'video_note'];
const mediaKey = Object.keys(replied).find(k => allowedTgKeys.includes(k));
if (mediaKey) {
try {
// Get the TG client instance to call getFile()
const tgWrapper = bot.bot?.clients?.find(c => c.type === 'tg');
const tgClient = tgWrapper?.client;
if (!tgClient) throw new Error('TG client not available');
let mediaObj = replied[mediaKey];
// photo is an array — pick the largest (last)
if (mediaKey === 'photo') mediaObj = mediaObj[mediaObj.length - 1];
const fileUrl = await tgClient.getFile(mediaObj.file_id);
if (fileUrl) {
console.log(`[PARSER] TG reply media resolved: ${fileUrl.replace(/\/bot[0-9a-zA-Z_-]+/i, '/bot<token>')}`);
links.push(fileUrl);
} else {
await e.reply('Could not resolve the replied-to file. It may be too large (>20MB) for the Telegram Bot API.');
return false;
}
} catch (err) {
console.error('[PARSER] TG reply getFile error:', err);
await e.reply('Failed to fetch the replied-to media file.');
return false;
}
} else if (replied.text || replied.caption) {
// No media — extract any URLs from replied-to text
const replyText = replied.text || replied.caption || '';
const replyLinks = replyText.match(regex.all)?.filter(l => !l.includes(cfg.main.url.domain));
if (replyLinks?.length) links.push(...replyLinks);
}
}
}
console.log(`[PARSER DEBUG] Final links count: ${links.length}`, links);
@@ -114,24 +200,24 @@ export default async bot => {
}
// Check for !w command
const isWCommand = e.message.match(/\!w(0bm)?\b/i);
const isWCommand = e.message.match(new RegExp(`${escapedTrigger}(0bm)?\\b`, 'i'));
// Matrix-specific: enforce strict !w format
let matrixRating = null; // 'sfw' or 'nsfw'
let matrixTags = []; // user-provided tags
// Matrix / Telegram: enforce strict !w format with rating + tags
let botRating = null; // 'sfw' or 'nsfw'
let botTags = []; // user-provided tags
let isNSFW = false;
if (isWCommand && e.type === 'matrix') {
if (isWCommand && (e.type === 'matrix' || e.type === 'tg')) {
const msgLower = e.message.toLowerCase();
const hasSfw = /(?:^|\s)-sfw\b/i.test(msgLower);
const hasNsfw = /(?:^|\s)-nsfw\b/i.test(msgLower);
console.log(`[PARSER DEBUG] Matrix Flags: hasSfw=${hasSfw}, hasNsfw=${hasNsfw}, msg='${msgLower}'`);
console.log(`[PARSER DEBUG] ${e.type} Flags: hasSfw=${hasSfw}, hasNsfw=${hasNsfw}, msg='${msgLower}'`);
const hasRating = hasSfw || hasNsfw;
const tagMatch = e.message.match(/-t\s+([^\s].+)/i);
const hasTags = !!tagMatch;
// Bare !w with no arguments → show help
if (!hasRating && !hasTags) {
await e.reply(`!w -sfw/nsfw -t tag1,tag2,tag3 (at least ${getMinTags()} tags required)`);
await e.reply(`${trigger} -sfw/-nsfw -t tag1,tag2,tag3 (at least ${getMinTags()} tags required)`);
return false;
}
@@ -143,12 +229,12 @@ export default async bot => {
// Missing rating
if (!hasRating) {
await e.reply('missing rating: !w -sfw/nsfw -t tag1,tag2,tag3');
await e.reply(`missing rating: ${trigger} -sfw/-nsfw -t tag1,tag2,tag3`);
return false;
}
// Parse rating
matrixRating = hasNsfw ? 'nsfw' : 'sfw';
botRating = hasNsfw ? 'nsfw' : 'sfw';
if (hasNsfw) isNSFW = true;
const minTags = getMinTags();
@@ -160,17 +246,17 @@ export default async bot => {
} else {
// Remove links, !w and -sfw/nsfw to get tags
tagsInput = e.message.replace(regex.all, "")
.replace(/\!w(0bm)?\b/i, "")
.replace(new RegExp(`${escapedTrigger}(0bm)?\\b`, 'i'), "")
.replace(/\s*-(nsfw|sfw)\b/gi, "")
.replace(/\s*-t\b/gi, "")
.trim();
}
// Split by commas only to support multi-word tags
matrixTags = tagsInput.split(',').map(t => t.trim()).filter(t => t.length > 0);
botTags = tagsInput.split(',').map(t => t.trim()).filter(t => t.length > 0);
if (matrixTags.length < minTags) {
await e.reply(`at least ${minTags} tags required (got ${matrixTags.length}): !w -sfw/nsfw tag1, tag2, tag3`);
if (botTags.length < minTags) {
await e.reply(`at least ${minTags} tags required (got ${botTags.length}): ${trigger} -sfw/-nsfw -t tag1, tag2, tag3`);
return false;
}
}
@@ -179,7 +265,8 @@ export default async bot => {
const isForwarded = e.raw?.forward_from !== undefined;
const mediaGroupId = e.raw?.media_group_id;
if ((e.type === 'matrix' || !e.channel.includes("w0bm")) && (!isWCommand && !isForwarded)) {
const channelKeyword = (cfg.main.upload_channel_keyword || "w0bm").toLowerCase();
if ((e.type === 'matrix' || !e.channel.toLowerCase().includes(channelKeyword)) && (!isWCommand && !isForwarded)) {
console.log(`[PARSER DEBUG] Channel/Client check failed. Channel: ${e.channel}, Type: ${e.type}, IsW: ${!!isWCommand}`);
return false;
}
@@ -187,9 +274,10 @@ export default async bot => {
// --- LINKED ACCOUNT CHECK ---
let websiteUser = null;
if (e.type === 'matrix' || e.type === 'discord') {
// Identify lookup key
if (e.type === 'matrix' || e.type === 'discord' || e.type === 'tg') {
// Identify lookup key and type
// Matrix: Use unique ID (MXID)
// Telegram: Use numeric user ID (most stable, never changes)
// Discord: Use Nick or Username (Legacy) - TODO: Migration to ID recommended later
let lookupAlias = e.user.nick || e.user.username;
let lookupType = 'discord'; // default check
@@ -197,6 +285,9 @@ export default async bot => {
if (e.type === 'matrix') {
lookupAlias = e.user.account; // MXID
lookupType = 'matrix';
} else if (e.type === 'tg') {
lookupAlias = e.user.account; // numeric Telegram user ID as string
lookupType = 'telegram';
}
// Check DB
@@ -220,7 +311,8 @@ export default async bot => {
// Enforce Link for !w command
if (isWCommand && !websiteUser) {
await e.reply(`You must link your account to use this command. Go to ${cfg.main.url.full}/settings to link your ${e.type} account.`);
const linkType = e.type === 'tg' ? 'Telegram' : e.type;
await e.reply(`You must link your account to use this command. Go to ${cfg.main.url.full}/settings to link your ${linkType} account. Then send !link <TOKEN> to this bot.`);
return false;
}
}
@@ -250,10 +342,11 @@ export default async bot => {
// Use for..of to handle async await properly and serialize debugging
for (const link of links) {
console.log(`[PARSER LOOP] Processing link: ${link}`);
const sanitizedLink = link.replace(/\/bot[0-9a-zA-Z_-]+/i, '/bot<token>');
console.log(`[PARSER LOOP] Processing link: ${sanitizedLink}`);
// check repost (link)
try {
repost = await queue.checkrepostlink(link);
repost = await queue.checkrepostlink(sanitizedLink);
} catch (e) {
console.error(`[PARSER LOOP] Checkrepost failed:`, e);
}
@@ -302,18 +395,7 @@ export default async bot => {
console.error(`[METADATA ERROR] Pornhub yt-dlp failed for ${link}:`, err.message);
if (err.stderr) console.error(`[METADATA ERROR] stderr:`, err.stderr);
lastErr = err;
try {
const headFetch = await fetch(link, {
method: "HEAD",
headers: { 'User-Agent': pcUA }
});
const tmphead = headFetch.headers["content-type"];
const status = headFetch.status || headFetch.statusCode || (headFetch.res ? headFetch.res.statusCode : 'unknown');
console.log(`[PARSER DEBUG] Fallback fetch for ${link} (Status: ${status}): ${tmphead}`);
ext = cfg.mimes[tmphead];
} catch(fErr) {
console.error(`[METADATA ERROR] Fallback fetch failed for ${link}:`, fErr.message);
}
ext = await getMimeViaCurl(link);
}
}
else if (link.match(regex.instagram)) {
@@ -325,8 +407,7 @@ export default async bot => {
} catch (err) {
console.error(`[METADATA ERROR] Instagram yt-dlp failed for ${link}:`, err.message);
lastErr = err;
const tmphead = (await fetch(link, { method: "HEAD" })).headers["content-type"];
ext = cfg.mimes[tmphead];
ext = await getMimeViaCurl(link);
}
}
else if (link.match(regex.imgur)) {
@@ -338,36 +419,7 @@ export default async bot => {
} catch (err) {
console.error(`[METADATA ERROR] Imgur yt-dlp failed for ${link}:`, err.message);
lastErr = err;
// Fallback: Check MIME via curl (more robust than fetch for blocked direct links)
try {
let referer = link;
try {
const parsedUrl = new URL(link);
let host = parsedUrl.hostname;
if (host.includes('imgur.com')) host = 'imgur.com';
referer = `${parsedUrl.protocol}//${host}/`;
} catch(e) {}
const curlArgs = ['-I', '-s', '-f', '-L', '--user-agent', pcUA, '--referer', referer, link];
if (cfg.main.socks && cfg.main.socks !== 'undefined' && cfg.main.socks !== '') {
const proxyHost = cfg.main.socks.includes('://') ? cfg.main.socks.split('://')[1] : cfg.main.socks;
curlArgs.push('--socks5-hostname', proxyHost);
}
const headOut = await queue.spawn('curl', curlArgs);
const contentTypeMatch = headOut.stdout.match(/content-type:\s*([^\r\n]+)/i);
if (contentTypeMatch) {
const tmphead = contentTypeMatch[1].trim();
ext = cfg.mimes[tmphead];
if (ext) {
console.log(`[PARSER DEBUG] Imgur Metadata Fallback (curl) success: ${tmphead} -> ${ext}`);
} else {
console.warn(`[PARSER DEBUG] Imgur Metadata Fallback (curl) unsupported MIME: "${tmphead}"`);
}
}
} catch(fErr) {
console.error(`[METADATA ERROR] Imgur Fallback curl failed for ${link}:`, fErr.message);
}
ext = await getMimeViaCurl(link);
}
}
else if (link.match(regex.yt)) {
@@ -378,8 +430,7 @@ export default async bot => {
} catch (err) {
console.error(`[METADATA ERROR] YouTube yt-dlp failed for ${link}:`, err.message);
lastErr = err;
const tmphead = (await fetch(link, { method: "HEAD" })).headers["content-type"];
ext = cfg.mimes[tmphead];
ext = await getMimeViaCurl(link);
}
}
else if (link.match(regex.fourchan)) {
@@ -390,8 +441,7 @@ export default async bot => {
} catch (err) {
console.error(`[METADATA ERROR] 4chan yt-dlp failed for ${link}:`, err.message);
lastErr = err;
const tmphead = (await fetch(link, { method: "HEAD" })).headers["content-type"];
ext = cfg.mimes[tmphead];
ext = await getMimeViaCurl(link);
}
}
else {
@@ -402,10 +452,7 @@ export default async bot => {
} catch (err) {
console.error(`[METADATA ERROR] General yt-dlp failed for ${link}:`, err.message);
if (err.stderr) console.error(`[METADATA ERROR] stderr:`, err.stderr);
const errorMsg = `something went wrong lol`.slice(0, 1024);
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, errorMsg);
return await e.reply(errorMsg);
ext = await getMimeViaCurl(link);
}
}
@@ -420,6 +467,13 @@ export default async bot => {
disable_notification: true
});
// Safe TG edit helper — falls back to e.reply() if the charging message was never sent
const tgEdit = (text) => {
if (msg?.result)
return e.editMessageText(msg.result.chat.id, msg.result.message_id, text);
return e.reply(text);
};
// <download data>
const start = new Date();
console.log(`[PARSER] Downloading ${link}...`);
@@ -450,7 +504,7 @@ export default async bot => {
console.error('Pornhub dl error:', err);
const errorMsg = `something went wrong lol`.slice(0, 1024);
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, errorMsg);
return await tgEdit(errorMsg);
return await e.reply(errorMsg);
}
}
@@ -462,7 +516,7 @@ export default async bot => {
console.error('Instagram dl error:', err);
const errorMsg = `something went wrong lol`.slice(0, 1024);
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, errorMsg);
return await tgEdit(errorMsg);
return await e.reply(errorMsg);
}
}
@@ -523,7 +577,7 @@ export default async bot => {
console.error(`[PARSER] All Imgur download stages failed for ${link}:`, fallbackErr.message);
const errorMsg = `something went wrong lol`.slice(0, 1024);
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, errorMsg);
return await tgEdit(errorMsg);
return await e.reply(errorMsg);
}
}
@@ -535,7 +589,7 @@ export default async bot => {
console.error('YouTube dl error:', err);
const errorMsg = `something went wrong lol`.slice(0, 1024);
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, errorMsg);
return await tgEdit(errorMsg);
return await e.reply(errorMsg);
}
}
@@ -546,7 +600,7 @@ export default async bot => {
console.error('4chan dl error:', err);
const errorMsg = `something went wrong lol`.slice(0, 1024);
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, errorMsg);
return await tgEdit(errorMsg);
return await e.reply(errorMsg);
}
}
@@ -557,20 +611,20 @@ export default async bot => {
console.error('General dl error:', err);
const errorMsg = `something went wrong lol`.slice(0, 1024);
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, errorMsg);
return await tgEdit(errorMsg);
return await e.reply(errorMsg);
}
}
if (!source) {
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, "something went wrong lol");
return await tgEdit("something went wrong lol");
return await e.reply("something went wrong lol");
}
if (source.match(/larger than/)) {
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, "too large lol");
return await tgEdit("too large lol");
return await e.reply("too large lol");
}
const end = ~~((new Date() - start) / 1e3);
@@ -580,7 +634,7 @@ export default async bot => {
if (size > maxfilesize) {
await fs.promises.unlink(source).catch(_ => { });
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, `too large lol. (${lib.formatSize(size)} / ${lib.formatSize(maxfilesize)})`);
return await tgEdit(`too large lol. (${lib.formatSize(size)} / ${lib.formatSize(maxfilesize)})`);
return await e.reply(`too large lol. (${lib.formatSize(size)} / ${lib.formatSize(maxfilesize)})`);
}
@@ -603,17 +657,29 @@ export default async bot => {
} catch (err) {
await fs.promises.unlink(source).catch(_ => { });
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, "something went wrong lol");
return await tgEdit("something went wrong lol");
return await e.reply("something went wrong lol");
}
if (!Object.keys(cfg.mimes).includes(mime)) {
await fs.promises.unlink(source).catch(_ => { });
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, `lol, go f0ck yourself (${mime})`);
return await tgEdit(`lol, go f0ck yourself (${mime})`);
return await e.reply(`lol, go f0ck yourself (${mime})`);
}
// Enforce allowedMimes whitelist from config (e.g. block archives/pdf if not configured)
const allowedMimes = cfg.allowedMimes || [];
const mimeCategory = mime.split('/')[0]; // e.g. 'video', 'image', 'audio', 'application'
const mimeAllowed = allowedMimes.some(allowed => allowed === mime || allowed === mimeCategory);
if (!mimeAllowed) {
await fs.promises.unlink(source).catch(_ => { });
const blockedMsg = `lol, go f0ck yourself (blocked type: ${mime})`;
if (e.type == 'tg')
return await tgEdit(blockedMsg);
return await e.reply(blockedMsg);
}
// generate checksum
const checksum = (await queue.spawn('sha256sum', [source])).stdout.trim().split(" ")[0];
@@ -645,8 +711,11 @@ export default async bot => {
if (repost) {
await fs.promises.unlink(source).catch(_ => { });
if (e.type == 'tg')
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, `repost motherf0cker (checksum): ${cfg.main.url.full}/${repost}`);
if (e.type == 'tg') {
if (msg?.result)
return await e.editMessageText(msg.result.chat.id, msg.result.message_id, `repost motherf0cker (checksum): ${cfg.main.url.full}/${repost}`);
return await e.reply(`repost motherf0cker (checksum): ${cfg.main.url.full}/${repost}`);
}
if (e.type === 'discord') {
// For Discord, we EDIT the original "charging" message
@@ -673,7 +742,7 @@ export default async bot => {
await db`
insert into items ${db({
src: e.media ? "" : link,
src: (e.media || link.includes('api.telegram.org') || link.startsWith('mxc://')) ? "" : link,
dest: filename,
mime: mime,
size: size,
@@ -702,10 +771,48 @@ export default async bot => {
console.error('[PARSER] Failed to auto-subscribe uploader:', err);
}
// Telegram: assign rating + user tags (same as Matrix)
if (botRating && botTags.length >= getMinTags()) {
try {
const userId = websiteUser ? websiteUser.id : 1;
// Assign rating tag (sfw=1, nsfw=2)
const ratingTagId = botRating === 'sfw' ? 1 : 2;
await db`
insert into "tags_assign" ${db({
tag_id: ratingTagId,
item_id: itemid,
user_id: userId
})}
`;
// Assign user-provided tags
for (const tagName of botTags) {
let tagid;
const tag_exists = await db`select id from "tags" where tag = ${tagName}`;
if (tag_exists.length === 0) {
tagid = (await db`insert into "tags" ${db({ tag: tagName })} returning id`)[0].id;
} else {
tagid = tag_exists[0].id;
}
await db`
insert into "tags_assign" ${db({
tag_id: tagid,
item_id: itemid,
user_id: userId
})}
`;
}
console.log(`[PARSER] TG tags assigned: ${botRating}, [${botTags.join(', ')}] to item ${itemid}`);
} catch (err) {
console.error('[PARSER] Failed to assign TG tags:', err);
}
}
// Generate Thumbnail
try {
await queue.genThumbnail(filename, mime, itemid, link, manualApproval);
if (isNSFW) await queue.genBlurredThumbnail(itemid, manualApproval);
await queue.genBlurredThumbnail(itemid, manualApproval);
} catch (err) {
const tDir = manualApproval ? path.join(cfg.paths.pending, 't') : cfg.paths.t;
await queue.spawn('magick', ['./mugge.png', path.join(tDir, `${itemid}.webp`)]);
@@ -729,7 +836,8 @@ export default async bot => {
console.error('[PARSER] Matrix notification error:', err);
}
await e.deleteMessage(msg.result.chat.id, msg.result.message_id);
if (msg?.result)
await e.deleteMessage(msg.result.chat.id, msg.result.message_id);
await e.reply(`${outputmsgirc} | link: ${cfg.main.url.full}/${itemid}`);
}
else {
@@ -740,7 +848,7 @@ export default async bot => {
await db`
insert into items ${db({
src: e.media ? "" : link,
src: (e.media || link.includes('api.telegram.org') || link.startsWith('mxc://')) ? "" : link,
dest: filename,
mime: mime,
size: size,
@@ -769,13 +877,13 @@ export default async bot => {
console.error('[PARSER] Failed to auto-subscribe uploader:', err);
}
// Matrix: assign rating + user tags
if (e.type === 'matrix' && matrixRating && matrixTags.length >= getMinTags()) {
// Matrix / Telegram: assign rating + user tags
if (botRating && botTags.length >= getMinTags()) {
try {
const userId = websiteUser ? websiteUser.id : 1;
// Assign rating tag (sfw=1, nsfw=2)
const ratingTagId = matrixRating === 'sfw' ? 1 : 2;
const ratingTagId = botRating === 'sfw' ? 1 : 2;
await db`
insert into "tags_assign" ${db({
tag_id: ratingTagId,
@@ -785,7 +893,7 @@ export default async bot => {
`;
// Assign user-provided tags
for (const tagName of matrixTags) {
for (const tagName of botTags) {
let tagid;
const tag_exists = await db`
select id from "tags" where tag = ${tagName}
@@ -806,16 +914,16 @@ export default async bot => {
})}
`;
}
console.log(`[PARSER] Matrix tags assigned: ${matrixRating}, [${matrixTags.join(', ')}] to item ${itemid}`);
console.log(`[PARSER] Tags assigned: ${botRating}, [${botTags.join(', ')}] to item ${itemid}`);
} catch (err) {
console.error('[PARSER] Failed to assign Matrix tags:', err);
console.error('[PARSER] Failed to assign tags:', err);
}
}
// Generate Thumbnail
try {
await queue.genThumbnail(filename, mime, itemid, link, manualApproval);
if (isNSFW) await queue.genBlurredThumbnail(itemid, manualApproval);
await queue.genBlurredThumbnail(itemid, manualApproval);
} catch (err) {
const tDir = manualApproval ? path.join(cfg.paths.pending, 't') : cfg.paths.t;
await queue.spawn('magick', ['./mugge.png', path.join(tDir, `${itemid}.webp`)]);

View File

@@ -0,0 +1,78 @@
import db from "../sql.mjs";
import cfg from "../config.mjs";
export default async self => {
return [{
name: "telegram_link",
call: /^!link(?:\s+(.+))?$/i,
active: true,
clients: ["tg"],
f: async e => {
// Only for Telegram
if (e.type !== 'tg') return false;
let token = (e.args[0] || '').trim().toUpperCase();
// Scenario 1: User typed "!link" only (no token)
if (!token) {
await e.reply(`Please generate a link token on the website at ${cfg.main.url.full}/settings and then send: !link <TOKEN>`);
return true;
}
// Scenario 2: Processing a token
try {
// Find token in DB
const linkData = (await db`
SELECT user_id FROM link_token WHERE token = ${token}
`)[0];
if (!linkData) {
return await e.reply("Invalid or expired token. Please generate a new one at the website settings page.");
}
// Use the Telegram numeric user ID as the alias (most stable identifier)
const alias = e.user.account; // e.g. "123456789"
// Check if already linked to THIS user
const existing = await db`
SELECT 1 FROM user_alias
WHERE userid = ${linkData.user_id}
AND alias = ${alias}
AND type = 'telegram'
`;
if (existing.length > 0) {
return await e.reply("This Telegram account is already linked to your website profile.");
}
// Check if this Telegram account is linked to ANOTHER user (prevent hijacking)
const taken = await db`
SELECT 1 FROM user_alias
WHERE alias = ${alias}
AND type = 'telegram'
`;
if (taken.length > 0) {
return await e.reply("This Telegram account is already linked to a different website profile.");
}
// Perform Link
await db`
INSERT INTO user_alias (userid, alias, type)
VALUES (${linkData.user_id}, ${alias}, 'telegram')
ON CONFLICT DO NOTHING
`;
// Delete used token
await db`DELETE FROM link_token WHERE token = ${token}`;
const tgUsername = e.user.username ? `@${e.user.username}` : e.user.nick;
return await e.reply(`Successfully linked Telegram account ${tgUsername} (ID: ${alias}) to your website profile!`);
} catch (err) {
console.error("[Telegram Link] Error:", err);
return await e.reply("An internal error occurred while linking your account.");
}
}
}];
};

44
src/inc/wordfilter.mjs Normal file
View File

@@ -0,0 +1,44 @@
import db from "./sql.mjs";
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Replaces words matching database rules inside comments.
* @param {string} content
* @returns {Promise<string>} The filtered comment text.
*/
export async function applyWordFilter(content) {
if (!content || typeof content !== 'string') return content;
try {
const filters = await db`SELECT word, replacement FROM wordfilter`;
if (filters.length === 0) return content;
let filtered = content;
for (const f of filters) {
const escaped = escapeRegExp(f.word);
const regex = new RegExp(escaped, 'gi');
filtered = filtered.replace(regex, (match) => {
// 1. Check if the matched substring is entirely UPPERCASE
if (match === match.toUpperCase() && match !== match.toLowerCase()) {
return f.replacement.toUpperCase();
}
// 2. Check if the matched substring is Capitalized / Titlecase
if (match[0] === match[0].toUpperCase() && match[0] !== match[0].toLowerCase()) {
return f.replacement.charAt(0).toUpperCase() + f.replacement.slice(1);
}
// 3. Check if the matched substring is lowercase
if (match === match.toLowerCase()) {
return f.replacement.toLowerCase();
}
// Fallback to exact replacement string
return f.replacement;
});
}
return filtered;
} catch (err) {
console.error('[WORDFILTER] Error applying filter:', err);
return content;
}
}

View File

@@ -10,14 +10,17 @@ import { getAboutText, setAboutText, getRulesText, setRulesText, getTermsText, s
import flummpress from "flummpress";
import { handleUpload } from "./upload_handler.mjs";
import { handleAvatarUpload, handleAvatarDelete } from "./avatar_handler.mjs";
import { handleBannerUpload, handleBannerDelete } from "./banner_handler.mjs";
import { handleRethumbUpload } from "./rethumb_handler.mjs";
import { handleMemeUpload } from "./meme_upload_handler.mjs";
import { handleEmojiUpload } from "./emoji_upload_handler.mjs";
import { handleMemeUpload, handleMemeEdit } from "./meme_upload_handler.mjs";
import { handleEmojiUpload, handleEmojiEdit } from "./emoji_upload_handler.mjs";
import { handleImportTelegramPack } from "./sticker_pack_handler.mjs";
import { handleHallImageUpload, handleHallImageDelete, handleHallDelete, handleHallUpdate, handleHallCreate } from "./hall_image_handler.mjs";
import { handleMetaExtract } from "./meta_extract_handler.mjs";
import { handleMetaStrip } from "./meta_strip_handler.mjs";
import { handleCommentUpload } from "./comment_upload_handler.mjs";
import { getManualApproval, setManualApproval, getMinTags, setMinTags, getRegistrationOpen, setRegistrationOpen, getTrustedUploads, setTrustedUploads, getBypassDuplicateCheck, setBypassDuplicateCheck, getProtectFiles, setProtectFiles, getPrivateMessages, setPrivateMessages, getDefaultLayout, setDefaultLayout, getEnablePdf, setEnablePdf, getEnableCleanup, setEnableCleanup, getCleanupStartDate, setCleanupStartDate, getCleanupEndDate, setCleanupEndDate, getLogUserIps, setLogUserIps, getHashUserIps, setHashUserIps, getShitpostMode, setShitpostMode } from "./inc/settings.mjs";
import { handleCommentUpload, handleCommentUploadCancel } from "./comment_upload_handler.mjs";
import { handleDmAttachmentUpload, handleDmAttachmentDownload, handleDmAttachmentDelete } from "./dm_attachment_handler.mjs";
import { getManualApproval, setManualApproval, getMinTags, setMinTags, getRegistrationOpen, setRegistrationOpen, getTrustedUploads, setTrustedUploads, getBypassDuplicateCheck, setBypassDuplicateCheck, getProtectFiles, setProtectFiles, getPrivateMessages, setPrivateMessages, getDmAttachments, setDmAttachments, getDmUnencrypted, setDmUnencrypted, getDefaultLayout, setDefaultLayout, getEnablePdf, setEnablePdf, getEnableCleanup, setEnableCleanup, getCleanupStartDate, setCleanupStartDate, getCleanupEndDate, setCleanupEndDate, getLogUserIps, setLogUserIps, getHashUserIps, setHashUserIps, getShitpostMode, setShitpostMode, getAllowCommentDeletion, setAllowCommentDeletion, getNsfpIds, setNsfpIds } from "./inc/settings.mjs";
import { updateHallsCache, getHalls } from "./inc/halls_cache.mjs";
import { createI18n } from "./inc/i18n.mjs";
import security from "./inc/security.mjs";
@@ -46,7 +49,7 @@ const gateOptions = {
},
cloudflare_status: {
status: 'ok',
location: 'Frankfurt',
location: cfg.websrv.private_society_gate_location || 'Frankfurt',
name: 'Cloudflare',
status_text: 'Working',
},
@@ -76,7 +79,13 @@ const nginx502Fallback = `<html>
</html>`;
// Login + Register modal injected before </body>
const gateLoginInjection = `
// Dynamic function so reCAPTCHA can be bypassed for .onion requests
const _rcEnabled = !!(cfg.recaptcha && cfg.recaptcha.enabled && cfg.recaptcha.site_key);
const _rcSiteKey = (cfg.recaptcha && cfg.recaptcha.site_key) || '';
function getGateLoginInjection(req) {
const rcEnabled = _rcEnabled && !lib.isOnionRequest(req);
return `
<div id="hot-corner" style="position:fixed;bottom:0;left:0;width:20px;height:20px;z-index:9999;"></div>
<div id="gate-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.45);z-index:10000;align-items:center;justify-content:center;">
@@ -116,6 +125,7 @@ const gateLoginInjection = `
<input type="text" name="token" placeholder="Invite token" autocomplete="off"
style="background:white;color:black;border:1px solid #bbb;padding:7px 10px;width:100%;box-sizing:border-box;font-size:14px;font-family:inherit;" />
<input type="text" name="email_confirm_field" style="display:none !important;" tabindex="-1" autocomplete="off" />
${rcEnabled ? '<div id="gate-recaptcha" style="margin:4px 0;transform-origin:left top;"></div>' : ''}
<button type="submit" id="gate-register-btn" style="background:#0051c3;color:white;border:none;padding:9px;font-weight:600;font-size:14px;cursor:pointer;font-family:inherit;"
onmouseover="this.style.background='#003681'" onmouseout="if(!this.disabled)this.style.background='#0051c3'">Create account</button>
<p style="text-align:center;font-size:0.85em;margin:6px 0 0;color:#555;">
@@ -136,6 +146,7 @@ const gateLoginInjection = `
function gateShowView(view) {
document.getElementById('gate-login-view').style.display = view === 'login' ? '' : 'none';
document.getElementById('gate-register-view').style.display = view === 'register' ? '' : 'none';
if (view === 'register') gateRenderRecaptcha();
}
function gateSetError(id, msg) {
var el = document.getElementById(id);
@@ -151,6 +162,24 @@ const gateLoginInjection = `
btn.style.cursor = loading ? 'default' : 'pointer';
}
// reCAPTCHA
var _gateRcWidgetId = null;
var _gateRcLoaded = false;
function gateRenderRecaptcha() {
var el = document.getElementById('gate-recaptcha');
if (!el || !window.grecaptcha) return;
if (_gateRcWidgetId !== null) {
try { grecaptcha.reset(_gateRcWidgetId); } catch(e) {}
} else {
_gateRcWidgetId = grecaptcha.render(el, { sitekey: '${_rcSiteKey}', theme: 'light' });
}
}
window.onRecaptchaGateReady = function() {
_gateRcLoaded = true;
var rv = document.getElementById('gate-register-view');
if (rv && rv.style.display !== 'none') gateRenderRecaptcha();
};
document.addEventListener('DOMContentLoaded', function() {
var modal = document.getElementById('gate-modal');
var close = document.getElementById('gate-modal-close');
@@ -163,7 +192,7 @@ const gateLoginInjection = `
var hc = document.getElementById('hot-corner');
if (hc) hc.onclick = function() { openLoginGate('login'); };
// ── Login form ──────────────────────────────────────────────────────────
// Login form
document.getElementById('gate-login-form').onsubmit = function(e) {
e.preventDefault();
gateSetError('gate-login-error', '');
@@ -181,23 +210,28 @@ const gateLoginInjection = `
gateSetError('gate-login-error', d.msg || 'Login failed.');
gateSetBtn('gate-login-btn', false);
} else {
// success — server set the cookie, reload to enter the site
window.location.reload();
}
})
.catch(function() {
// On redirect (301) fetch follows it — if the redirect lands on '/' we reload
window.location.reload();
});
.catch(function() { window.location.reload(); });
};
// ── Register form ───────────────────────────────────────────────────────
// Register form
document.getElementById('gate-register-form').onsubmit = function(e) {
e.preventDefault();
gateSetError('gate-register-error', '');
gateSetError('gate-register-ok', '');
gateSetBtn('gate-register-btn', true);
var fd = new FormData(this);
if (_gateRcWidgetId !== null && window.grecaptcha) {
var token = grecaptcha.getResponse(_gateRcWidgetId);
if (!token) {
gateSetError('gate-register-error', 'Please complete the CAPTCHA.');
gateSetBtn('gate-register-btn', false);
return;
}
fd.append('g-recaptcha-response', token);
}
var body = new URLSearchParams(fd).toString();
fetch('/register', {
method: 'POST',
@@ -209,6 +243,7 @@ const gateLoginInjection = `
gateSetBtn('gate-register-btn', false);
if (d.success === false) {
gateSetError('gate-register-error', d.msg || 'Registration failed.');
if (_gateRcWidgetId !== null && window.grecaptcha) { try { grecaptcha.reset(_gateRcWidgetId); } catch(e) {} }
} else {
document.getElementById('gate-register-ok').textContent = d.msg || 'Account created! You can now sign in.';
document.getElementById('gate-register-ok').style.display = '';
@@ -219,6 +254,7 @@ const gateLoginInjection = `
.catch(function() {
gateSetBtn('gate-register-btn', false);
gateSetError('gate-register-error', 'An error occurred. Please try again.');
if (_gateRcWidgetId !== null && window.grecaptcha) { try { grecaptcha.reset(_gateRcWidgetId); } catch(e) {} }
});
};
});
@@ -230,7 +266,9 @@ const gateLoginInjection = `
if (_sb.length > 12) _sb = _sb.slice(-12);
});
</script>
${rcEnabled ? '<script src="https://www.google.com/recaptcha/api.js?onload=onRecaptchaGateReady&render=explicit" async defer><\/script>' : ''}
`;
}
// Text injected into the "What can I do?" section
@@ -247,11 +285,40 @@ try {
}
// Called on every gated request — produces a fresh page with unique Ray ID + timestamp
// Accepts an optional request object to inject the visitor's real IP into the footer reveal.
// Accepts an optional request object to inject the visitor's real IP into the footer reveal and dynamic host into page text/title.
function buildGatePage(req) {
if (!_cfRender) return nginx502Fallback;
let html = _cfRender({ ...gateOptions, what_can_i_do: gateSignInButton });
let reqHost = null;
if (req && req.headers) {
const rawHost = req.headers['x-forwarded-host'] || req.headers['host'];
if (rawHost) {
const firstHost = rawHost.split(',')[0].trim();
let extracted = '';
if (firstHost.startsWith('[')) {
const closeBracket = firstHost.indexOf(']');
extracted = closeBracket !== -1 ? firstHost.substring(1, closeBracket) : firstHost;
} else {
extracted = firstHost.split(':')[0].trim();
}
const isLocalHost = ['localhost', '127.0.0.1', '::1', 'f0ckm', '0.0.0.0', 'localhost.localdomain'].includes(extracted.toLowerCase());
if (extracted && !isLocalHost) {
reqHost = extracted;
}
}
}
if (!reqHost) reqHost = cfg.main.url.domain;
const currentGateOptions = {
...gateOptions,
host_status: {
...gateOptions.host_status,
location: reqHost,
},
what_can_i_do: gateSignInButton,
};
let html = _cfRender(currentGateOptions);
// Inject real visitor IP into the footer "Your IP: [Click to reveal]" span
if (req) {
@@ -270,9 +337,9 @@ function buildGatePage(req) {
// Patch the <title> to include the domain — matches real Cloudflare behaviour
html = html.replace(
'<title>502: Bad Gateway</title>',
`<title>${cfg.main.url.domain} | 502: Bad gateway</title>`
`<title>${reqHost} | 502: Bad gateway</title>`
);
html = html.replace('</body>', gateLoginInjection + '\n</body>');
html = html.replace('</body>', getGateLoginInjection(req) + '\n</body>');
return html;
}
@@ -281,7 +348,14 @@ const nginx502 = (cfg.websrv.private_society && cfg.websrv.private_society_gate
? null
: nginx502Fallback;
// Custom gate template — resolved once at boot from config
// Set private_society_gate: "custom" and private_society_gate_template: "your-template-name" (no .html)
const _customGateTemplate = (cfg.websrv.private_society && cfg.websrv.private_society_gate === 'custom' && cfg.websrv.private_society_gate_template)
? String(cfg.websrv.private_society_gate_template).replace(/\.html$/i, '')
: null;
if (nginx502 === null) console.log('[BOOT] Private society gate: Cloudflare dynamic mode');
if (_customGateTemplate) console.log(`[BOOT] Private society gate: Custom template → views/${_customGateTemplate}.html (flummpress resolves extension)`);
// ─────────────────────────────────────────────────────────────────────────────
@@ -351,9 +425,10 @@ process.on('uncaughtException', err => {
path.join(cfg.paths.deleted, 'b'), path.join(cfg.paths.deleted, 't'), path.join(cfg.paths.deleted, 'ca')
];
for (const dir of initDirs) {
if (!fs.existsSync(dir)) {
console.log(`[BOOT] Creating directory: ${dir}`);
try {
fs.mkdirSync(dir, { recursive: true });
} catch (e) {
if (e.code !== 'EEXIST') console.warn(`[BOOT] Could not create directory ${dir}: ${e.message}`);
}
}
@@ -418,11 +493,55 @@ process.on('uncaughtException', err => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
// Encourage connection reuse — helps external tools like ShareX avoid repeated TCP/TLS handshakes
res.setHeader('Connection', 'keep-alive');
// Block incoming requests to .onion if Tor Hidden Service is explicitly disabled in config
if (cfg.websrv?.enable_tor_hs === false && lib.isOnionRequest(req)) {
res.writeHead(503).end();
req.url.pathname = '/tor_hs_disabled_bypass';
return;
}
// Tor Onion-Location header: advertises .onion service counterpart to Tor Browser users when enabled
if (cfg.websrv?.enable_tor_hs !== false && cfg.main?.onion && !lib.isOnionRequest(req)) {
const p = req.url?.pathname || '/';
const s = req.url?.search || '';
const onionHost = cfg.main.onion.replace(/\/+$/, '');
res.setHeader('Onion-Location', `${onionHost}${p}${s}`);
}
if (isSecure) {
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
});
// Cache-Control headers for static assets.
// flummpress router.static() sends no caching headers, which forces Chrome to
// re-fetch all thumbnails on every grid visit even when they haven't changed.
// Guard: only set long-lived caching when protect_files is OFF so we never attach
// immutable headers to a 401 response (which would be incorrectly cached by browsers).
app.use(async (req, res) => {
const p = req.url?.pathname;
if (!p) return;
if (getProtectFiles()) return; // Protect-files gates these with auth — don't cache
if (p.startsWith('/t/') || p.startsWith('/ca/') || p.startsWith('/b/')) {
// Thumbnails, covers, and source blobs: 1-year cache.
// These never change for a given ID (content-addressed by item ID).
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
} else if (p.startsWith('/s/') && !p.startsWith('/s/emojis/') && !p.startsWith('/s/koepfe/')) {
// CSS/JS/images in /s/ are versioned by query param (?v=...) — safe to cache long-term.
// Emojis and koepfe are excluded (user-uploadable, mutable).
res.setHeader('Cache-Control', 'public, max-age=86400');
} else if (p.startsWith('/a/')) {
// Avatars can be re-uploaded — use short cache with revalidation.
res.setHeader('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
} else if (p.startsWith('/memes/') || p.startsWith('/s/emojis/') || p.startsWith('/s/koepfe/')) {
// Mutable user content: short cache.
res.setHeader('Cache-Control', 'public, max-age=3600');
}
});
// Block source map requests early — flummpress crashes on unknown MIME types (e.g. .map)
app.use(async (req, res) => {
if (req.url?.pathname?.endsWith('.map')) {
@@ -441,6 +560,45 @@ process.on('uncaughtException', err => {
}
});
// ─── Session cache ────────────────────────────────────────────────────────
// The session middleware runs in parallel with all other app.use() handlers
// (flummpress uses Promise.all). With many concurrent requests each doing a
// DB SELECT, the pool (max:50) drains and nginx sees 502s. Caching the
// session row for 5s and the upload-count for 30s eliminates the hot path.
const SESSION_CACHE_TTL = 5_000; // ms — short enough to pick up bans quickly
const UPLOAD_COUNT_CACHE_TTL = 30_000; // ms — upload window is 12h, stale for 30s is fine
const _sessionCache = new Map(); // sha256(cookie) -> { data: row, exp: number }
const _uploadCountCache = new Map(); // username -> { count: number, exp: number }
const _scGet = (hash) => {
const e = _sessionCache.get(hash);
if (e && e.exp > Date.now()) return e.data;
_sessionCache.delete(hash);
return null;
};
const _scSet = (hash, data) => {
_sessionCache.set(hash, { data, exp: Date.now() + SESSION_CACHE_TTL });
if (_sessionCache.size > 2000) {
const now = Date.now();
for (const [k, v] of _sessionCache) if (v.exp <= now) _sessionCache.delete(k);
}
};
// Exposed so logout/ban routes can force-evict immediately
global._invalidateSessionCache = (hash) => _sessionCache.delete(hash);
const _ucGet = (username) => {
const e = _uploadCountCache.get(username);
if (e && e.exp > Date.now()) return e.count;
_uploadCountCache.delete(username);
return null;
};
const _ucSet = (username, count) => {
_uploadCountCache.set(username, { count, exp: Date.now() + UPLOAD_COUNT_CACHE_TTL });
};
// Allow upload handler to bust the cache after a successful upload
global._invalidateUploadCountCache = (username) => _uploadCountCache.delete(username);
// ──────────────────────────────────────────────────────────────────────────
app.use(async (req, res) => {
// This can be used to annoy people on discord sending links to your site lmao, shouldnt be used though since it sucks ass
// if (cfg.main.development && req.method === 'POST') console.error(`[BOOT] [DEBUG_POST] ${req.method} ${req.url.pathname}`);
@@ -485,32 +643,44 @@ process.on('uncaughtException', err => {
if (req.url.pathname === '/manifest.json' || req.url.pathname === '/sw.js')
return;
if (req.url.pathname.match(/^\/(b|c|t|ca|a|memes)\//) || req.url.pathname.startsWith('/s/emojis/')) {
if (cfg.websrv.private_society && !req.cookies?.session) {
res.writeHead(200, { 'Content-Type': 'text/html' }).end(nginx502 ?? buildGatePage(req));
req.url.pathname = '/private_society_media_bypass';
return;
}
// protect_files gates raw file URLs behind a session (401 if not logged in).
// private_society also gates file URLs — but only when protect_files is ALSO enabled.
// If private_society is on but protect_files is off, direct file URLs are intentionally
// left public so they can be shared without requiring a login.
if (getProtectFiles() && !req.cookies?.session) {
res.writeHead(401).end('Unauthorized');
req.url.pathname = '/protect_files_bypass';
if (cfg.websrv.private_society) {
res.writeHead(200, { 'Content-Type': 'text/html' }).end(nginx502 ?? buildGatePage(req));
req.url.pathname = '/private_society_media_bypass';
} else {
res.writeHead(401).end('Unauthorized');
req.url.pathname = '/protect_files_bypass';
}
return;
}
return;
}
const availableThemes = cfg.websrv.themes || ['amoled', 'atmos', 'f0ck', 'f0ck95d', 'iced', 'orange', 'p1nk', '4d'];
const availableThemes = cfg.websrv.themes || ['amoled', 'atmos', 'f0ck', 'f0ck95d', 'f0ck98', 'iced', 'orange', 'p1nk', '4d'];
const defaultTheme = cfg.websrv.theme || 'amoled';
req.theme = (req.cookies?.theme && availableThemes.includes(req.cookies.theme)) ? req.cookies.theme : defaultTheme;
req.fullscreen = req.cookies.fullscreen || 0;
if (req.cookies.session) {
const user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user".is_moderator, "user".banned, "user".ban_reason, "user".ban_expires, "user".force_password_change, "user_sessions".id as sess_id, "user_sessions".csrf_token, "user_options".mode, "user_options".theme, "user_options".fullscreen, "user_options".excluded_tags, "user_options".avatar, "user_options".avatar_file, "user_options".show_motd, "user_options".strict_mode, "user_options".show_background, "user_options".use_new_layout, "user_options".username_color, "user_options".font, "user_options".disable_autoplay, "user_options".disable_swiping, "user_options".description, "user_options".display_name, COALESCE("user_options".min_xd_score, 0) as min_xd_score, "user_options".ruffle_volume, "user_options".ruffle_background, "user_options".quote_emojis, "user_options".embed_youtube_in_comments, "user_options".hide_koepfe, "user_options".language, "user_options".use_alternative_infobox, "user_options".receive_system_notifications, "user_options".receive_user_notifications, "user_options".do_not_disturb, "user_options".comment_display_mode, "user_options".force_comment_display_mode
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
left join "user_options" on "user_options".user_id = "user_sessions".user_id
where "user_sessions".session = ${lib.sha256(req.cookies.session)}
limit 1
`;
const _sessionHash = lib.sha256(req.cookies.session);
let _cachedRow = _scGet(_sessionHash);
let user;
if (_cachedRow) {
user = [_cachedRow];
} else {
user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user".is_moderator, "user".banned, "user".ban_reason, "user".ban_expires, "user".force_password_change, "user_sessions".id as sess_id, "user_sessions".csrf_token, "user_options".mode, "user_options".theme, "user_options".fullscreen, "user_options".excluded_tags, "user_options".avatar, "user_options".avatar_file, "user_options".show_motd, "user_options".strict_mode, "user_options".show_background, "user_options".use_new_layout, "user_options".username_color, "user_options".font, "user_options".disable_autoplay, "user_options".disable_swiping, "user_options".description, "user_options".display_name, COALESCE("user_options".min_xd_score, 0) as min_xd_score, "user_options".ruffle_volume, "user_options".ruffle_background, "user_options".quote_emojis, "user_options".embed_youtube_in_comments, "user_options".hide_koepfe, "user_options".language, "user_options".use_alternative_infobox, "user_options".use_alternative_steuerung, "user_options".receive_system_notifications, "user_options".receive_user_notifications, "user_options".do_not_disturb, "user_options".comment_display_mode, "user_options".force_comment_display_mode
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
left join "user_options" on "user_options".user_id = "user_sessions".user_id
where "user_sessions".session = ${_sessionHash}
limit 1
`;
if (user.length > 0) _scSet(_sessionHash, user[0]);
}
if (user.length === 0) {
res.writeHead(307, { // delete session
@@ -583,17 +753,22 @@ process.on('uncaughtException', err => {
req.session.pending_count = pending[0].c;
}
// Calculate uploads remaining globally for the modal
// Calculate uploads remaining globally for the modal (cached 30s per user)
if (!req.session.admin && !req.session.is_moderator) {
const twelveHoursAgo = ~~(Date.now() / 1000) - (12 * 3600);
const uploadCount = await db`
SELECT count(*) as count
FROM items
WHERE username = ${req.session.user}
AND stamp > ${twelveHoursAgo}
AND is_deleted = false
`;
req.session.uploads_remaining = Math.max(0, cfg.main.upload_limit - parseInt(uploadCount[0].count));
let cachedUploadCount = _ucGet(req.session.user);
if (cachedUploadCount === null) {
const twelveHoursAgo = ~~(Date.now() / 1000) - (12 * 3600);
const uploadCount = await db`
SELECT count(*) as count
FROM items
WHERE username = ${req.session.user}
AND stamp > ${twelveHoursAgo}
AND is_deleted = false
`;
cachedUploadCount = parseInt(uploadCount[0].count);
_ucSet(req.session.user, cachedUploadCount);
}
req.session.uploads_remaining = Math.max(0, cfg.main.upload_limit - cachedUploadCount);
} else {
req.session.uploads_remaining = undefined; // Unlimited for admins/mods
}
@@ -631,9 +806,10 @@ process.on('uncaughtException', err => {
hide_koepfe: user[0].hide_koepfe ?? false,
language: (user[0].language && user[0].language.trim()) ? user[0].language.trim() : null,
use_alternative_infobox: user[0].use_alternative_infobox ?? (cfg.websrv.user_alternative_infobox !== false),
use_alternative_steuerung: user[0].use_alternative_steuerung ?? (cfg.websrv.user_alternative_steuerung !== false),
comment_display_mode: user[0].comment_display_mode ?? (cfg.websrv.default_comment_display_mode || 0),
force_comment_display_mode: user[0].force_comment_display_mode ?? 0
}, 'user_id', 'mode', 'theme', 'fullscreen', 'excluded_tags', 'font', 'disable_autoplay', 'disable_swiping', 'show_background', 'ruffle_volume', 'ruffle_background', 'quote_emojis', 'embed_youtube_in_comments', 'hide_koepfe', 'language', 'use_alternative_infobox', 'comment_display_mode', 'force_comment_display_mode')
}, 'user_id', 'mode', 'theme', 'fullscreen', 'excluded_tags', 'font', 'disable_autoplay', 'disable_swiping', 'show_background', 'ruffle_volume', 'ruffle_background', 'quote_emojis', 'embed_youtube_in_comments', 'hide_koepfe', 'language', 'use_alternative_infobox', 'use_alternative_steuerung', 'comment_display_mode', 'force_comment_display_mode')
}
on conflict ("user_id") do update set
theme = excluded.theme,
@@ -650,6 +826,7 @@ process.on('uncaughtException', err => {
hide_koepfe = excluded.hide_koepfe,
language = excluded.language,
use_alternative_infobox = excluded.use_alternative_infobox,
use_alternative_steuerung = excluded.use_alternative_steuerung,
comment_display_mode = excluded.comment_display_mode,
force_comment_display_mode = excluded.force_comment_display_mode,
user_id = excluded.user_id
@@ -659,14 +836,19 @@ process.on('uncaughtException', err => {
const queryMode = req.url.qs?.mode !== undefined ? +req.url.qs.mode : undefined;
req.mode = queryMode !== undefined ? queryMode : (req.session ? +(req.session.mode ?? 0) : +(req.cookies?.mode ?? 0));
// Guest protection: Strictly enforce SFW mode (0) for non-logged-in users
// public_nsfw: when true, the *default* for guests is mode 3 (all content).
// Only applies when the guest has no explicit mode preference (no ?mode= param, no cookie).
// If the guest has chosen a filter (e.g. SFW), that choice is always respected.
if (!req.session) {
req.mode = 0;
const hasExplicitMode = queryMode !== undefined || req.cookies?.mode !== undefined;
if (!hasExplicitMode) {
req.mode = cfg.websrv.public_nsfw ? 3 : 0;
}
}
// Private Society gate — require login for all content when enabled
if (cfg.websrv.private_society && !req.session) {
const publicPaths = /^\/(s|login|logout|register|activate|forgot-password|reset-password|banned|api\/v2\/auth|manifest\.json|sw\.js|robots\.txt|favicon\.(ico|png|gif)|s\/img\/duck-icon-(192|512)\.png)(\/.*)?$/;
const publicPaths = /^\/(s|login|logout|register|activate|forgot-password|reset-password|banned|api\/v2\/auth|api\/v2\/upload|manifest\.json|sw\.js|robots\.txt|favicon\.(ico|png|gif)|s\/img\/duck-icon-(192|512)\.png)(\/.*)?$/;
if (!publicPaths.test(req.url.pathname)) {
// For AJAX requests, return 502 so it looks like the backend is down
if (req.headers['x-requested-with'] === 'XMLHttpRequest') {
@@ -674,18 +856,21 @@ process.on('uncaughtException', err => {
req.url.pathname = '/private_society_bypass';
return;
}
// For page requests, return 502 Bad Gateway for all paths except homepage (which shows the gate)
if (req.url.pathname !== '/') {
// For page requests, serve the gate for all paths (custom template or fallback)
if (_customGateTemplate) {
res.writeHead(200, { 'Content-Type': 'text/html' }).end(tpl.render(_customGateTemplate, {}, req));
} else if (req.url.pathname !== '/') {
// Non-home paths: always show the static/cloudflare gate
res.writeHead(200, { 'Content-Type': 'text/html' }).end(nginx502 ?? buildGatePage(req));
req.url.pathname = '/private_society_bypass';
return;
}
// Homepage: in cloudflare dynamic mode serve gate directly; otherwise fall through to template
if (nginx502 === null) {
} else if (nginx502 === null) {
// Homepage in cloudflare dynamic mode: serve the CF gate directly
res.writeHead(200, { 'Content-Type': 'text/html' }).end(buildGatePage(req));
req.url.pathname = '/private_society_bypass';
} else {
// Homepage in plain nginx mode: fall through to index.html template
return;
}
req.url.pathname = '/private_society_bypass';
return;
}
}
});
@@ -711,7 +896,9 @@ process.on('uncaughtException', err => {
// because the session middleware will have completed by the time router callbacks execute.
app.use(async (req, res) => {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return;
if (['/login', '/register', '/api/v2/upload', '/api/v2/settings/uploadAvatar', '/api/v2/admin/memes', '/api/v2/admin/emojis', '/api/v2/meta/extract-file', '/api/v2/meta/strip-gps', '/api/v2/scroller/external/rehost-meta', '/api/v2/comments/upload'].includes(req.url.pathname)) return;
if (['/login', '/register', '/api/v2/upload', '/api/v2/settings/uploadAvatar', '/api/v2/settings/uploadBanner', '/api/v2/admin/memes', '/api/v2/admin/emojis', '/api/v2/meta/extract-file', '/api/v2/meta/strip-gps', '/api/v2/scroller/external/rehost-meta', '/api/v2/comments/upload', '/api/v2/admin/sticker-packs/import'].includes(req.url.pathname)) return;
// DM attachment upload validates CSRF internally
if (req.url.pathname.match(/^\/api\/dm\/attachment\/upload\//)) return;
// Hall manager routes are handled by bypass middleware with their own session auth
if (cfg.websrv.halls_enabled !== false && req.url.pathname.match(/^\/api\/v2\/admin\/halls(\/|$)/)) return;
// User hall image upload is handled by bypass middleware below
@@ -754,6 +941,23 @@ process.on('uncaughtException', err => {
}
});
// Bypass middleware for banner upload (needs raw body before router consumes it)
// CSRF is validated inside handleBannerUpload/handleBannerDelete after their own session lookups
app.use(async (req, res) => {
if (req.url.pathname === '/api/v2/settings/uploadBanner') {
if (cfg.websrv.user_banner_enabled === false) {
return res.reply({ success: false, msg: 'Banner feature is currently disabled' }, 403);
}
if (req.method === 'POST') {
await handleBannerUpload(req, res);
req.url.pathname = '/handled_banner_upload_bypass';
} else if (req.method === 'DELETE') {
await handleBannerDelete(req, res);
req.url.pathname = '/handled_banner_delete_bypass';
}
}
});
// Bypass middleware for custom thumbnail uploads
app.use(async (req, res) => {
const thumbMatch = req.url.pathname.match(/^\/api\/v2\/items\/([^/]+)\/thumbnail$/);
@@ -771,6 +975,16 @@ process.on('uncaughtException', err => {
}
});
// Bypass middleware for meme template edits
app.use(async (req, res) => {
const editMatch = req.url.pathname.match(/^\/api\/v2\/admin\/memes\/(\d+)\/edit$/);
if (req.method === 'POST' && editMatch) {
req.params = { id: editMatch[1] };
await handleMemeEdit(req, res);
req.url.pathname = '/handled_meme_edit_bypass';
}
});
// Bypass middleware for emoji uploads
app.use(async (req, res) => {
if (req.method === 'POST' && req.url.pathname === '/api/v2/admin/emojis') {
@@ -779,6 +993,33 @@ process.on('uncaughtException', err => {
}
});
// Bypass middleware for emoji edits
app.use(async (req, res) => {
const editMatch = req.url.pathname.match(/^\/api\/v2\/admin\/emojis\/(\d+)\/edit$/);
if (req.method === 'POST' && editMatch) {
req.params = { id: editMatch[1] };
await handleEmojiEdit(req, res);
req.url.pathname = '/handled_emoji_edit_bypass';
}
});
// Bypass middleware for Telegram sticker pack import
app.use(async (req, res) => {
if (req.method === 'POST' && req.url.pathname === '/api/v2/admin/sticker-packs/import') {
await handleImportTelegramPack(req, res);
req.url.pathname = '/handled_sticker_pack_import_bypass';
}
});
// Bypass middleware for koepfe uploads
app.use(async (req, res) => {
if (req.method === 'POST' && req.url.pathname === '/api/v2/admin/koepfe/upload') {
const { handleKoepfeUpload } = await import('./koepfe_handler.mjs');
await handleKoepfeUpload(req, res);
req.url.pathname = '/handled_koepfe_upload_bypass';
}
});
// Bypass middleware for hall image uploads (multipart — needs raw body)
app.use(async (req, res) => {
if (cfg.websrv.halls_enabled === false) return;
@@ -832,6 +1073,28 @@ process.on('uncaughtException', err => {
await handleCommentUpload(req, res);
req.url.pathname = '/handled_comment_upload_bypass';
}
// DELETE /api/v2/comments/upload/:id — user cancels a staged attachment
const cancelMatch = req.url.pathname.match(/^\/api\/v2\/comments\/upload\/(\d+)$/);
if (req.method === 'DELETE' && cancelMatch) {
await handleCommentUploadCancel(req, res, cancelMatch[1]);
req.url.pathname = '/handled_comment_upload_cancel_bypass';
}
});
// Bypass middleware for DM encrypted attachment upload/download/delete
app.use(async (req, res) => {
const uploadMatch = req.url.pathname.match(/^\/api\/dm\/attachment\/upload\/(\d+)$/);
const downloadMatch = req.url.pathname.match(/^\/api\/dm\/attachment\/(\d+)$/);
if (req.method === 'POST' && uploadMatch) {
await handleDmAttachmentUpload(req, res, uploadMatch[1]);
req.url.pathname = '/handled_dm_attachment_upload_bypass';
} else if (req.method === 'GET' && downloadMatch) {
await handleDmAttachmentDownload(req, res, downloadMatch[1]);
req.url.pathname = '/handled_dm_attachment_download_bypass';
} else if (req.method === 'DELETE' && downloadMatch) {
await handleDmAttachmentDelete(req, res, downloadMatch[1]);
req.url.pathname = '/handled_dm_attachment_delete_bypass';
}
});
tpl.views = "views";
@@ -982,7 +1245,15 @@ process.on('uncaughtException', err => {
// Default is true; set to false to fully disable private messaging
setPrivateMessages(cfg.websrv.private_messages !== false);
console.log(`[BOOT] Private messaging: ${cfg.websrv.private_messages !== false ? 'ENABLED' : 'DISABLED'}`);
// Load dm_attachments from config.json (static — not a DB setting)
// Default is true; requires private_messages to also be enabled
setDmAttachments(cfg.websrv.dm_attachments !== false);
console.log(`[BOOT] DM attachments: ${cfg.websrv.dm_attachments !== false ? 'ENABLED' : 'DISABLED'}`);
// Load dm_unencrypted from config.json (static — not a DB setting)
setDmUnencrypted(!!cfg.websrv.dm_unencrypted);
console.log(`[BOOT] DM unencrypted: ${cfg.websrv.dm_unencrypted ? 'ENABLED' : 'DISABLED'}`);
// Load default_layout from config.json (static)
if (cfg.websrv.default_layout) {
setDefaultLayout(cfg.websrv.default_layout);
@@ -1022,6 +1293,22 @@ process.on('uncaughtException', err => {
console.warn(`[BOOT] Terms text fetch failed:`, e.message);
}
// Fetch nsfp (NSFP tag IDs) setting — overrides config.json if set in DB
try {
const nsfpSetting = await db`SELECT value FROM site_settings WHERE key = 'nsfp' LIMIT 1`;
if (nsfpSetting.length > 0) {
const parsed = JSON.parse(nsfpSetting[0].value);
if (Array.isArray(parsed)) {
setNsfpIds(parsed);
console.log(`[BOOT] NSFP tag IDs loaded from DB: [${getNsfpIds().join(', ')}]`);
}
} else {
console.log(`[BOOT] No NSFP setting in DB, using config.json: [${getNsfpIds().join(', ')}]`);
}
} catch (e) {
console.warn(`[BOOT] NSFP setting fetch failed:`, e.message);
}
const globals = {
lul: cfg.websrv.lul,
themes: cfg.websrv.themes,
@@ -1037,17 +1324,25 @@ process.on('uncaughtException', err => {
get min_tags() { return getMinTags(); },
get registration_open() { return getRegistrationOpen(); },
registration_web_toggle_enabled: cfg.websrv.open_registration_web_toggle !== false,
registration_require_mail_andor_token: !!cfg.websrv.open_registration_require_mail_andor_token,
get trusted_uploads() { return getTrustedUploads(); },
get shitpost_mode() { return getShitpostMode(); },
shitpost_require_rating: !!cfg.websrv.shitpost_require_rating,
shitpost_min_tags: parseInt(cfg.websrv.shitpost_min_tags) || 0,
get about_text() { return getAboutText(); },
get rules_text() { return getRulesText(); },
get terms_text() { return getTermsText(); },
get about_text_b64() { return Buffer.from(getAboutText() || '').toString('base64'); },
get rules_text_b64() { return Buffer.from(getRulesText() || '').toString('base64'); },
get terms_text_b64() { return Buffer.from(getTermsText() || '').toString('base64'); },
get halls() { return getHalls(); },
halls_enabled: cfg.websrv.halls_enabled !== false,
userhalls_enabled: cfg.websrv.userhalls_enabled !== false,
enable_userhall_image_upload: cfg.websrv.enable_userhall_image_upload !== false,
abyss_enabled: cfg.websrv.abyss_enabled !== false,
smtp_enabled: !!(cfg.smtp && cfg.smtp.enabled && cfg.smtp.mail_reset_password),
recaptcha_enabled: !!(cfg.recaptcha && cfg.recaptcha.enabled && cfg.recaptcha.site_key),
recaptcha_site_key: (cfg.recaptcha && cfg.recaptcha.site_key) || '',
show_background_cfg: cfg.websrv.background !== false,
allowed_mimes: Object.keys(cfg.mimes).concat([...new Set(Object.values(cfg.mimes))].map(ext => `.${ext}`)).join(','),
mimes_json: JSON.stringify(cfg.mimes),
@@ -1055,6 +1350,7 @@ process.on('uncaughtException', err => {
show_mime_picker: cfg.websrv.show_mime_picker !== false,
private_society: cfg.websrv.private_society || false,
private_society_gate: cfg.websrv.private_society_gate || '',
private_society_gate_location: cfg.websrv.private_society_gate_location || 'Frankfurt',
show_content_warning: cfg.websrv.show_content_warning !== false,
web_url_upload: !!cfg.websrv.web_url_upload,
enable_youtube_upload: cfg.websrv.enable_youtube_upload !== false,
@@ -1062,6 +1358,8 @@ process.on('uncaughtException', err => {
meme_creator: !!cfg.websrv.meme_creator,
custom_favicon: cfg.websrv.custom_favicon || "",
custom_brand_image: Array.isArray(cfg.websrv.custom_brand_image) ? cfg.websrv.custom_brand_image[0] : (cfg.websrv.custom_brand_image || ""),
custom_navbar_brand_text: cfg.websrv.custom_navbar_brand_text || "",
default_font: cfg.websrv.default_font || "",
site_description: cfg.websrv.description || "The webs dumpster",
enable_nsfl: !!cfg.enable_nsfl,
nsfl_tag_id: cfg.nsfl_tag_id || 3,
@@ -1069,23 +1367,39 @@ process.on('uncaughtException', err => {
themes_json: JSON.stringify(cfg.websrv.themes || []),
enable_profile_description: !!cfg.websrv.enable_profile_description,
get private_messages() { return getPrivateMessages(); },
get dm_attachments() { return getDmAttachments(); },
get dm_unencrypted() { return getDmUnencrypted(); },
get allow_comment_deletion() { return getAllowCommentDeletion(); },
get enable_pdf() { return getEnablePdf(); },
get enable_cleanup() { return getEnableCleanup(); },
get cleanup_start_date() { return getCleanupStartDate(); },
get cleanup_end_date() { return getCleanupEndDate(); },
matrix_enabled: cfg.clients.find(c => c.type === 'matrix')?.enabled || false,
telegram_enabled: cfg.clients.find(c => c.type === 'tg')?.enabled || false,
ts: Date.now(),
get default_layout() { return getDefaultLayout(); },
show_koepfe: !!cfg.websrv.show_koepfe,
hide_sidebar_default: !!cfg.websrv.hide_sidebar_default,
allow_language_change: cfg.websrv.allow_language_change !== false,
enable_xd_score: !!cfg.websrv.enable_xd_score,
enable_dynamic_thumbs: !!cfg.websrv.enable_dynamic_thumbs,
comment_max_length: cfg.main.comment_max_length ?? null,
enable_swf: !!cfg.websrv.enable_swf,
enable_archive: !!cfg.websrv.enable_archive,
enable_danmaku: cfg.websrv.enable_danmaku !== false,
enable_item_title: cfg.websrv.enable_item_title !== false,
enable_global_chat: !!cfg.websrv.enable_global_chat,
embed_youtube_in_comments: cfg.websrv.embed_youtube_in_comments !== false,
koepfe_json: JSON.stringify(cfg.websrv.koepfe || []),
get koepfe_json() {
try {
const kDir = cfg.paths.koepfe;
if (!fs.existsSync(kDir)) return JSON.stringify(cfg.websrv.koepfe || []);
const files = fs.readdirSync(kDir).filter(f => /\.(png|jpe?g|gif|webp|avif)$/i.test(f)).map(f => '/s/koepfe/' + f);
return JSON.stringify(files.length ? files : (cfg.websrv.koepfe || []));
} catch (e) {
return JSON.stringify(cfg.websrv.koepfe || []);
}
},
custom_brand_images_json: JSON.stringify(cfg.websrv.custom_brand_image || []),
allowed_comment_images: cfg.websrv.allowed_comment_images || [],
allowed_comment_images_json: JSON.stringify(cfg.websrv.allowed_comment_images || []),
@@ -1096,10 +1410,12 @@ process.on('uncaughtException', err => {
fileupload_comments_size: cfg.websrv.fileupload_comments_size || (10 * 1024 * 1024),
fileupload_comments_max: cfg.websrv.fileupload_comments_max || 5,
fileupload_comments_mode: cfg.websrv.fileupload_comments_mode || 'attachment',
fileupload_comments_mimes: Array.isArray(cfg.websrv.fileupload_comments_mimes) ? cfg.websrv.fileupload_comments_mimes : ['image', 'video', 'audio'],
enable_comment_polls: cfg.websrv.enable_comment_polls || false,
get fonts() {
try {
const fontsDir = path.join(path.resolve(), 'public/s/fonts');
const fontsDir = cfg.paths.fonts;
if (!fs.existsSync(fontsDir)) return [];
return fs.readdirSync(fontsDir).filter(f => /\.(ttf|otf|woff2?)$/i.test(f)).map(f => ({
name: f.split('.').shift(),
@@ -1146,26 +1462,53 @@ process.on('uncaughtException', err => {
}
}
// Resolve per-request recaptcha preference (disabled for .onion requests or when passed false)
const effectiveReq = req || (data && data.req);
const defaultRecaptcha = !!(cfg.recaptcha && cfg.recaptcha.enabled && cfg.recaptcha.site_key);
let perRequestRecaptcha = defaultRecaptcha;
if (effectiveReq && lib.isOnionRequest(effectiveReq)) {
perRequestRecaptcha = false;
} else if (data && typeof data.recaptcha_enabled === 'boolean') {
perRequestRecaptcha = data.recaptcha_enabled;
}
// Build data: globals first, then caller-supplied data, then per-request i18n last
// so t/lang always reflect the user's language, not the site default.
// ALSO mutate globals.t and globals.lang: flummpress spreads this.#globals LAST
// ALSO mutate globals.t, globals.lang, globals.recaptcha_enabled: flummpress spreads this.#globals LAST
// inside render(), so globals must carry the per-request values too.
globals.t = perRequestT;
globals.lang = perRequestLang;
globals.recaptcha_enabled = perRequestRecaptcha;
// Resolve per-request infobox preference
const useAltInfobox = (req && req.session && typeof req.session.use_alternative_infobox === 'boolean')
? req.session.use_alternative_infobox
: (data && typeof data.user_alternative_infobox === 'boolean'
? data.user_alternative_infobox
: (cfg.websrv.user_alternative_infobox !== false));
// Guests always get false — the alternative infobox is a logged-in user preference only
const activeReq = req || effectiveReq;
const useAltInfobox = (activeReq && activeReq.session && typeof activeReq.session.use_alternative_infobox === 'boolean')
? activeReq.session.use_alternative_infobox
: (activeReq && !activeReq.session
? false
: (data && typeof data.user_alternative_infobox === 'boolean'
? data.user_alternative_infobox
: (cfg.websrv.user_alternative_infobox !== false)));
const useAltSteuerung = (activeReq && activeReq.session && typeof activeReq.session.use_alternative_steuerung === 'boolean')
? activeReq.session.use_alternative_steuerung
: (activeReq && !activeReq.session
? false
: (data && typeof data.user_alternative_steuerung === 'boolean'
? data.user_alternative_steuerung
: (cfg.websrv.user_alternative_steuerung !== false)));
data = Object.assign({}, globals, data || {}, {
t: perRequestT,
lang: perRequestLang,
recaptcha_enabled: perRequestRecaptcha,
user_alternative_infobox: useAltInfobox,
comment_display_mode: (req && req.session && typeof req.session.comment_display_mode === 'number')
? req.session.comment_display_mode
user_alternative_steuerung: useAltSteuerung,
user_banner_enabled: cfg.websrv.user_banner_enabled !== false,
comment_display_mode: (activeReq && activeReq.session && typeof activeReq.session.comment_display_mode === 'number')
? activeReq.session.comment_display_mode
: (data && typeof data.comment_display_mode === 'number'
? data.comment_display_mode
: (cfg.websrv.default_comment_display_mode || 0))
@@ -1177,17 +1520,19 @@ process.on('uncaughtException', err => {
data.custom_brand_image = brand[Math.floor(Math.random() * brand.length)];
}
if (req) {
if (req.mode !== undefined) data.mode = req.mode;
data.theme = req.theme || req.cookies?.theme || cfg.websrv.theme || 'f0ck';
if (!data.url) data.url = req.url;
data.user_strict_bool = (req.session && req.session.strict_mode) ? true : false;
data.user_logged_in_bool = !!req.session;
data.csrf_token = req.session?.csrf_token || '';
data.max_file_size = lib.formatSize(cfg.main.maxfilesize * (req.session?.admin ? cfg.main.adminmultiplier : 1));
data.max_file_size_bytes = Math.floor(cfg.main.maxfilesize * (req.session?.admin ? cfg.main.adminmultiplier : 1));
if (activeReq) {
data.recaptcha_enabled = perRequestRecaptcha;
if (activeReq.mode !== undefined) data.mode = activeReq.mode;
data.theme = activeReq.theme || activeReq.cookies?.theme || cfg.websrv.theme || 'f0ck';
if (!data.url) data.url = activeReq.url;
data.user_strict_bool = (activeReq.session && activeReq.session.strict_mode) ? true : false;
data.user_logged_in_bool = !!activeReq.session;
data.csrf_token = activeReq.session?.csrf_token || '';
data.max_file_size = lib.formatSize(cfg.main.maxfilesize * (activeReq.session?.admin ? cfg.main.adminmultiplier : 1));
data.max_file_size_bytes = Math.floor(cfg.main.maxfilesize * (activeReq.session?.admin ? cfg.main.adminmultiplier : 1));
data.web_url_upload = data.web_url_upload !== undefined ? data.web_url_upload : !!cfg.websrv.web_url_upload;
} else {
data.recaptcha_enabled = perRequestRecaptcha;
data.theme = data.theme || cfg.websrv.theme || 'f0ck';
data.user_strict_bool = false;
data.user_logged_in_bool = false;
@@ -1223,4 +1568,60 @@ process.on('uncaughtException', err => {
setTimeout(cleanupStaleSessions, 30_000);
setInterval(cleanupStaleSessions, CLEANUP_INTERVAL_MS);
// ── Inactivity ban — permanently ban accounts that haven't logged in for N days
// Set websrv.inactivity_ban_days = 0 (or omit) to disable this feature entirely.
const INACTIVITY_BAN_DAYS = parseInt(cfg.websrv.inactivity_ban_days) || 0;
if (INACTIVITY_BAN_DAYS <= 0) {
console.log(`[BOOT] Inactivity ban: DISABLED (set websrv.inactivity_ban_days > 0 to enable)`);
} else {
const INACTIVITY_BAN_INTERVAL_MS = 6 * 60 * 60 * 1000; // every 6 hours
const banInactiveUsers = async () => {
try {
const cutoffSecs = ~~(Date.now() / 1e3) - INACTIVITY_BAN_DAYS * 24 * 60 * 60;
// Find activated, non-banned, non-admin, non-moderator accounts whose
// last_seen timestamp has passed the inactivity threshold.
// Accounts with last_seen = 0 (never logged in) are also included.
const targets = await db`
SELECT id, login
FROM "user"
WHERE banned = false
AND activated = true
AND admin = false
AND is_moderator = false
AND login != 'deleted_user'
AND last_seen <= ${cutoffSecs}
`;
if (targets.length === 0) return;
const ids = targets.map(u => u.id);
const reason = `Inactivity (no login for ${INACTIVITY_BAN_DAYS}+ days)`;
await db`
UPDATE "user"
SET banned = true,
ban_reason = ${reason},
ban_expires = NULL
WHERE id = ANY(${ids})
`;
// Terminate all open sessions for banned accounts
await db`DELETE FROM user_sessions WHERE user_id = ANY(${ids})`;
console.log(`[INACTIVITY BAN] Banned ${targets.length} inactive account(s) (threshold: ${INACTIVITY_BAN_DAYS} days): ${targets.map(u => u.login).join(', ')}`);
} catch (err) {
console.error('[INACTIVITY BAN] Failed:', err.message);
}
};
console.log(`[BOOT] Inactivity ban: enabled — threshold ${INACTIVITY_BAN_DAYS} days (config: websrv.inactivity_ban_days)`);
// Run once after startup (60s delay to let DB settle), then every 6 hours
setTimeout(banInactiveUsers, 60_000);
setInterval(banInactiveUsers, INACTIVITY_BAN_INTERVAL_MS);
}
})();

92
src/koepfe_handler.mjs Normal file
View File

@@ -0,0 +1,92 @@
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
import lib from './inc/lib.mjs';
import cfg from './inc/config.mjs';
function parseMultipart(req) {
return new Promise((resolve, reject) => {
let body = [];
req.on('data', chunk => body.push(chunk));
req.on('end', () => {
const buffer = Buffer.concat(body);
const boundaryMatch = req.headers['content-type']?.match(/boundary=(.+)$/i);
if (!boundaryMatch) return reject(new Error('No boundary'));
const boundary = '--' + boundaryMatch[1];
let start = buffer.indexOf(boundary) + boundary.length + 2;
let fileData = null;
let filename = null;
let csrfToken = null;
while (start < buffer.length) {
const headerEnd = buffer.indexOf('\r\n\r\n', start);
if (headerEnd === -1) break;
const headerStr = buffer.slice(start, headerEnd).toString();
const nextBoundary = buffer.indexOf(boundary, headerEnd);
if (nextBoundary === -1) break;
const chunkData = buffer.slice(headerEnd + 4, nextBoundary - 2);
if (headerStr.includes('name="file"')) {
const fnMatch = headerStr.match(/filename="(.+?)"/);
if (fnMatch) filename = fnMatch[1];
fileData = chunkData;
} else if (headerStr.includes('name="csrf_token"')) {
csrfToken = chunkData.toString();
}
start = nextBoundary + boundary.length + 2;
}
resolve({ fileData, filename, csrfToken });
});
req.on('error', reject);
});
}
import db from './inc/sql.mjs';
export async function handleKoepfeUpload(req, res) {
// Manual Session Lookup since this is a bypass middleware
let user = [];
if (req.cookies && req.cookies.session) {
user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user_sessions".csrf_token
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
where "user_sessions".session = ${lib.sha256(req.cookies.session)}
limit 1
`;
}
if (user.length === 0 || !user[0].admin) {
return res.reply ? res.reply({ code: 403, body: JSON.stringify({ success: false, msg: 'Forbidden' }) }) : res.writeHead(403, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg: 'Forbidden' }));
}
req.session = user[0];
try {
const { fileData, filename, csrfToken } = await parseMultipart(req);
if (!req.session.csrf_token || csrfToken !== req.session.csrf_token) {
return res.writeHead(403, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg: 'Invalid CSRF' }));
}
if (!fileData || fileData.length === 0) {
throw new Error('No file data');
}
const ext = path.extname(filename || '.png').toLowerCase();
if (!['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif'].includes(ext)) {
throw new Error('Unsupported format');
}
const newName = crypto.randomBytes(8).toString('hex') + ext;
const targetPath = path.join(cfg.paths.koepfe, newName);
await fs.writeFile(targetPath, fileData);
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: true, file: '/s/koepfe/' + newName }));
} catch (e) {
console.error(e);
return res.writeHead(500, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg: e.message }));
}
}

View File

@@ -107,3 +107,117 @@ export const handleMemeUpload = async (req, res) => {
return sendJson(res, { success: false, message: err.message }, 500);
}
};
export const handleMemeEdit = async (req, res) => {
console.log('[BOOT] [MEME HANDLER] Edit Started');
// Manual Session Lookup
let user = [];
if (req.cookies && req.cookies.session) {
user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user".is_moderator, "user_sessions".id as sess_id, "user_sessions".csrf_token
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
where "user_sessions".session = ${lib.sha256(req.cookies.session)}
limit 1
`;
}
if (user.length === 0 || !user[0].admin) {
console.log('[MEME HANDLER] Unauthorized');
return sendJson(res, { success: false, message: 'Unauthorized' }, 403);
}
req.session = user[0];
// CSRF validation
if (req.session.csrf_token) {
const csrfToken = req.headers['x-csrf-token'];
if (!csrfToken || csrfToken !== req.session.csrf_token) {
console.warn(`[CSRF] Blocked meme edit for user ${req.session.user}. Invalid token.`);
return sendJson(res, { success: false, message: 'Invalid CSRF token' }, 403);
}
}
const id = req.params.id;
try {
// Fetch existing template first
const currentMeme = await db`SELECT * FROM meme_templates WHERE id = ${id}`;
if (currentMeme.length === 0) {
return sendJson(res, { success: false, message: 'Meme template not found' }, 404);
}
const contentType = req.headers['content-type'] || '';
const boundaryMatch = contentType.match(/boundary=([^;]+)/);
if (!boundaryMatch) {
return sendJson(res, { success: false, message: 'Invalid content type' }, 400);
}
let boundary = boundaryMatch[1].trim();
if (boundary.startsWith('"') && boundary.endsWith('"')) {
boundary = boundary.substring(1, boundary.length - 1);
}
const bodyBuffer = await collectBody(req);
const parts = parseMultipart(bodyBuffer, boundary);
const template_id = (parts.template_id || '').trim().toLowerCase();
const name = (parts.name || '').trim();
const category = (parts.category || '').trim() || 'General';
let url = (parts.url || '').trim();
if (!template_id || !name) {
return sendJson(res, { success: false, message: 'Template ID and Name are required' }, 400);
}
if (!/^[a-z0-9-]+$/.test(template_id)) {
return sendJson(res, { success: false, message: 'Invalid ID. Use lowercase a-z, 0-9, - only.' }, 400);
}
// Ensure template_id is unique
const existing = await db`SELECT id FROM meme_templates WHERE template_id = ${template_id} AND id != ${id}`;
if (existing.length > 0) {
return sendJson(res, { success: false, message: 'Template ID is already in use by another template' }, 400);
}
const file = parts.file;
if (file && file.data && file.data.length > 0) {
const extMatch = file.filename.match(/\.([a-z0-9]+)$/i);
const ext = extMatch ? extMatch[1].toLowerCase() : 'jpg';
const filename = `${template_id}_${Math.random().toString(36).substring(7)}.${ext}`;
const filePath = path.join(cfg.paths.memes, filename);
console.error(`[BOOT] [MEME HANDLER] Writing file to: ${filePath} (Size: ${file.data.length})`);
await fs.writeFile(filePath, file.data);
const exists = (await fs.stat(filePath)).size > 0;
console.error(`[BOOT] [MEME HANDLER] Write verify: ${exists ? 'SUCCESS' : 'FAILURE'}`);
if (exists) {
url = `/memes/${filename}`;
} else {
throw new Error("File was written but verify failed (size 0 or not found)");
}
}
// If no file uploaded and no URL input provided, keep the existing one
if (!url) {
url = currentMeme[0].url;
}
await db`
UPDATE meme_templates
SET template_id = ${template_id}, name = ${name}, category = ${category}, url = ${url}
WHERE id = ${id}
`;
return sendJson(res, { success: true });
} catch (err) {
console.error('[MEME HANDLER ERROR]', err);
return sendJson(res, { success: false, message: err.message }, 500);
}
};

View File

@@ -104,7 +104,8 @@ export const handleRethumbUpload = async (req, res, itemId) => {
}
// Save to tmp for verification
const uuid = (await db`select gen_random_uuid() as uuid`)[0].uuid.substring(0, 8);
const raw = (await db`select replace(gen_random_uuid()::text, '-', '') || replace(gen_random_uuid()::text, '-', '') as uuid`)[0].uuid;
const uuid = raw.substring(0, 48);
const tmpPath = path.join(cfg.paths.tmp, `rethumb_${uuid}_${itemId}`);
await fs.mkdir(cfg.paths.tmp, { recursive: true });
@@ -130,16 +131,8 @@ export const handleRethumbUpload = async (req, res, itemId) => {
try {
await execFile('magick', [tmpPath, '-coalesce', '-resize', `${thumbSpec}^`, '-gravity', 'center', '-crop', `${thumbSpec}+0+0`, '+repage', finalPath]);
// Check if item contains NSFW or NSFL tag
const tags = await db`
select tag_id from tags_assign
where item_id = ${+item.id}
and tag_id in (2, ${cfg.nsfl_tag_id || 3})
`;
if (tags.length > 0) {
// Generate blurred thumbnail
await queue.genBlurredThumbnail(item.id, !item.active);
}
// Generate blurred thumbnail
await queue.genBlurredThumbnail(item.id, !item.active);
} catch (err) {
console.error('[RETHUMB HANDLER] Magick error:', err);

View File

@@ -0,0 +1,286 @@
import { promises as fs } from "fs";
import db from "./inc/sql.mjs";
import lib from "./inc/lib.mjs";
import cfg from "./inc/config.mjs";
import { collectBody } from "./inc/multipart.mjs";
import path from "path";
import { fileURLToPath } from "url";
import { execFile as _execFile } from "child_process";
import { promisify } from "util";
import crypto from "crypto";
import fetch from "flumm-fetch"; // used for JSON API calls only
import https from "https";
import http from "http";
const execFile = promisify(_execFile);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const MAGICK_POLICY_PATH = path.resolve(__dirname, '../config/magick-policy');
const magickEnv = { ...process.env, MAGICK_CONFIGURE_PATH: MAGICK_POLICY_PATH };
const sendJson = (res, data, code = 200) => {
res.writeHead(code, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
};
const requireAdmin = async (req, res) => {
let user = [];
if (req.cookies && req.cookies.session) {
user = await db`
select "user".id, "user".login, "user".user, "user".admin, "user".is_moderator, "user_sessions".id as sess_id, "user_sessions".csrf_token
from "user_sessions"
left join "user" on "user".id = "user_sessions".user_id
where "user_sessions".session = ${lib.sha256(req.cookies.session)}
limit 1
`;
}
if (user.length === 0 || !user[0].admin) {
sendJson(res, { success: false, message: 'Unauthorized' }, 403);
return null;
}
const csrfToken = req.headers['x-csrf-token'];
if (user[0].csrf_token && (!csrfToken || csrfToken !== user[0].csrf_token)) {
sendJson(res, { success: false, message: 'Invalid CSRF token' }, 403);
return null;
}
return user[0];
};
/**
* Download a file from a URL and return it as a raw Buffer.
* Uses Node's built-in https/http directly — flumm-fetch's .buffer() method
* calls setEncoding('utf8') which corrupts binary image data.
*/
const downloadBuffer = (url) => {
return new Promise((resolve, reject) => {
const mod = url.startsWith('https://') ? https : http;
mod.get(url, (res) => {
if (res.statusCode >= 400) {
res.resume(); // drain the socket
return reject(new Error('HTTP ' + res.statusCode + ' fetching ' + url));
}
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => resolve(Buffer.concat(chunks)));
res.on('error', reject);
}).on('error', reject);
});
};
/**
* Convert a buffer to WebP and write to the emojis dir.
* Returns the relative URL path.
*/
const saveAsWebP = async (buffer, originalExt) => {
const randSuffix = crypto.randomBytes(24).toString('hex');
const webpFilename = randSuffix + '.webp';
const webpPath = path.join(cfg.paths.emojis, webpFilename);
if (originalExt === 'webp') {
await fs.writeFile(webpPath, buffer);
} else {
const tmpFilename = randSuffix + '_tmp.' + originalExt;
const tmpPath = path.join(cfg.paths.emojis, tmpFilename);
await fs.writeFile(tmpPath, buffer);
try {
await execFile('magick', [tmpPath, '-coalesce', '-quality', '80', webpPath], { env: magickEnv });
} finally {
await fs.unlink(tmpPath).catch(() => {});
}
}
const stat = await fs.stat(webpPath);
if (!stat || stat.size === 0) throw new Error('WebP conversion produced empty file');
return '/s/emojis/' + webpFilename;
};
/**
* Save a raw buffer directly to the emojis dir with the given extension (no re-encoding).
* Used for video stickers (.webm) which browsers can play natively.
*/
const saveRaw = async (buffer, ext) => {
const randSuffix = crypto.randomBytes(24).toString('hex');
const filename = randSuffix + '.' + ext;
const filePath = path.join(cfg.paths.emojis, filename);
await fs.writeFile(filePath, buffer);
const stat = await fs.stat(filePath);
if (!stat || stat.size === 0) throw new Error('Saved file is empty');
return '/s/emojis/' + filename;
};
/**
* Import a Telegram sticker pack given its name (short name from t.me/addstickers/<name>).
* Creates a sticker_pack record and downloads all stickers as custom_emojis.
*/
export const handleImportTelegramPack = async (req, res) => {
const user = await requireAdmin(req, res);
if (!user) return;
let body = {};
try {
const raw = await collectBody(req);
body = JSON.parse(raw.toString());
} catch (e) {
return sendJson(res, { success: false, message: 'Invalid JSON body' }, 400);
}
const { pack_name, display_name } = body;
if (!pack_name || typeof pack_name !== 'string') {
return sendJson(res, { success: false, message: 'pack_name is required' }, 400);
}
// Get Telegram bot token
const tgClient = cfg.clients.find(c => c.type === 'tg');
if (!tgClient || !tgClient.token) {
return sendJson(res, { success: false, message: 'Telegram bot not configured' }, 500);
}
const botToken = tgClient.token;
const tgName = pack_name.trim().replace(/^https?:\/\/t\.me\/addstickers\//i, '');
if (!tgName) {
return sendJson(res, { success: false, message: 'Could not extract pack name from URL' }, 400);
}
console.log(`[STICKER PACK] Importing Telegram pack: ${tgName}`);
// Check if pack already imported
const existing = await db`SELECT id FROM sticker_packs WHERE tg_name = ${tgName} LIMIT 1`;
if (existing.length > 0) {
return sendJson(res, { success: false, message: `Pack "${tgName}" was already imported (ID ${existing[0].id})` }, 409);
}
// Call Telegram API
let stickerSet;
try {
const apiRes = await fetch(`https://api.telegram.org/bot${botToken}/getStickerSet?name=${encodeURIComponent(tgName)}`);
const apiData = await apiRes.json();
if (!apiData.ok) {
return sendJson(res, { success: false, message: `Telegram API error: ${apiData.description || 'unknown'}` }, 400);
}
stickerSet = apiData.result;
} catch (e) {
console.error('[STICKER PACK] Telegram API fetch failed:', e);
return sendJson(res, { success: false, message: `Failed to contact Telegram API: ${e.message}` }, 500);
}
const packTitle = display_name?.trim() || stickerSet.title || tgName;
const stickers = stickerSet.stickers || [];
console.log(`[STICKER PACK] Found ${stickers.length} stickers in "${stickerSet.title}"`);
// Create pack record
const [newPack] = await db`
INSERT INTO sticker_packs (name, tg_name, tg_title, sticker_count)
VALUES (${packTitle}, ${tgName}, ${stickerSet.title}, ${stickers.length})
RETURNING id, name, tg_name, tg_title
`;
// Generate a static WebP thumbnail for the pack from the first sticker's Telegram thumbnail.
// Telegram always provides a static webp thumbnail for every sticker regardless of type.
let packThumbUrl = null;
const firstThumb = stickers[0]?.thumbnail;
if (firstThumb && firstThumb.file_id) {
try {
const tRes = await fetch('https://api.telegram.org/bot' + botToken + '/getFile?file_id=' + encodeURIComponent(firstThumb.file_id));
const tData = await tRes.json();
if (tData.ok && tData.result && tData.result.file_path) {
const tBuf = await downloadBuffer('https://api.telegram.org/file/bot' + botToken + '/' + tData.result.file_path);
const tExt = (tData.result.file_path.match(/\.([a-z0-9]+)$/i) || ['', 'webp'])[1].toLowerCase();
packThumbUrl = await saveAsWebP(tBuf, tExt);
await db`UPDATE sticker_packs SET thumb_url = ${packThumbUrl} WHERE id = ${newPack.id}`;
console.log('[STICKER PACK] Pack thumbnail saved: ' + packThumbUrl);
}
} catch (e) {
console.warn('[STICKER PACK] Could not save pack thumbnail:', e.message);
}
}
let imported = 0;
let failed = 0;
const errors = [];
// Derive a slug from the pack's display name (admin-supplied > Telegram title > URL slug)
// e.g. "My Cool Pack" → "my_cool_pack"
const safeName = packTitle
.replace(/[^a-z0-9]/gi, '_')
.toLowerCase()
.replace(/_+/g, '_')
.replace(/^_|_$/g, '') || tgName.replace(/[^a-z0-9_]/gi, '_').toLowerCase();
for (let i = 0; i < stickers.length; i++) {
const sticker = stickers[i];
try {
// Skip only animated TGS stickers (Lottie format — cannot be displayed as-is)
const isAnimated = sticker.is_animated || false;
const isVideo = sticker.is_video || false;
if (isAnimated) {
console.log('[STICKER PACK] Skipping animated (TGS) sticker ' + (i + 1));
continue;
}
const fileId = sticker.file_id;
// Resolve the download URL via getFile
const fileRes = await fetch('https://api.telegram.org/bot' + botToken + '/getFile?file_id=' + encodeURIComponent(fileId));
const fileData = await fileRes.json();
if (!fileData.ok || !fileData.result || !fileData.result.file_path) {
throw new Error('getFile failed: ' + (fileData.description || 'no file_path'));
}
const filePath = fileData.result.file_path;
const extMatch = filePath.match(/\.([a-z0-9]+)$/i);
const ext = extMatch ? extMatch[1].toLowerCase() : 'webp';
const downloadUrl = 'https://api.telegram.org/file/bot' + botToken + '/' + filePath;
const buffer = await downloadBuffer(downloadUrl);
// Generate emoji name: <pack_display_slug>_<padded_index>
const emojiName = safeName + '_' + String(i + 1).padStart(3, '0');
// Check for name conflict
const nameConflict = await db`SELECT id FROM custom_emojis WHERE name = ${emojiName} LIMIT 1`;
const finalName = nameConflict.length > 0 ? emojiName + '_' + crypto.randomBytes(3).toString('hex') : emojiName;
// Save: video stickers (.webm) stored as-is; static stickers converted to WebP
let savedUrl;
if (isVideo) {
savedUrl = await saveRaw(buffer, ext); // keeps original webm, no re-encoding
console.log('[STICKER PACK] Saved video sticker ' + (i + 1) + ' as ' + ext);
} else {
savedUrl = await saveAsWebP(buffer, ext);
}
await db`
INSERT INTO custom_emojis (name, url, pack_id)
VALUES (${finalName}, ${savedUrl}, ${newPack.id})
`;
imported++;
console.log('[STICKER PACK] Imported sticker ' + (i + 1) + '/' + stickers.length + ': ' + finalName + ' (' + (isVideo ? 'video' : 'static') + ')');
// Small delay to avoid Telegram rate limits
if (i < stickers.length - 1) await new Promise(function(resolve) { setTimeout(resolve, 50); });
} catch (e) {
console.error('[STICKER PACK] Failed sticker ' + (i + 1) + ':', e.message);
errors.push('Sticker ' + (i + 1) + ': ' + e.message);
failed++;
}
}
// Update pack with actual imported count
await db`UPDATE sticker_packs SET sticker_count = ${imported} WHERE id = ${newPack.id}`;
// Notify clients that emojis changed
await db`NOTIFY emojis_updated, '{}'`;
console.log(`[STICKER PACK] Done. Imported: ${imported}, Failed: ${failed}`);
return sendJson(res, {
success: true,
pack: { ...newPack, sticker_count: imported },
imported,
failed,
errors
});
};

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