This commit is contained in:
2026-09-14 22:30:09 +02:00
parent 22ffc3b51a
commit 912deeb28e
42 changed files with 2998 additions and 618 deletions
+247 -25
View File
@@ -40,6 +40,11 @@
--badge-tag: #090909; --badge-tag: #090909;
--posts-meta-bg: #000000b8; --posts-meta-bg: #000000b8;
--x2154: #215483; --x2154: #215483;
--bg-canvas-opacity: 1.0;
--bg-canvas-blur: 300px;
--onara-bg-opacity: 0.84;
--onara-backdrop-blur: 5px;
--onara-grid-dim-opacity: 0.15;
} }
html:not([theme]), html[theme=""] { html:not([theme]), html[theme=""] {
@@ -3716,6 +3721,144 @@ body.sidebar-right-hidden #sidebar-drag-zone {
color: #fff; color: #fff;
} }
/* ── Tuner Sub-Tabs Navigation ────────────────────────────── */
.f0ck-tuner-subtabs-nav {
display: flex;
gap: 4px;
background: rgba(0, 0, 0, 0.45);
padding: 3px;
border-radius: 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
flex: 1;
margin-right: 8px;
}
.f0ck-tuner-subtab-btn {
flex: 1;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 5px;
background: transparent;
border: none;
color: #8e8e93;
font-size: 11px;
font-weight: 600;
padding: 5px 8px;
border-radius: 6px;
cursor: pointer;
transition: all 0.15s ease;
white-space: nowrap;
}
.f0ck-tuner-subtab-btn:hover {
color: #fff;
background: rgba(255, 255, 255, 0.06);
}
.f0ck-tuner-subtab-btn.active {
color: #000;
background: var(--accent, #99ff00);
font-weight: 700;
box-shadow: 0 2px 8px color-mix(in srgb, var(--accent, #99ff00) 40%, transparent);
}
.f0ck-tuner-subtab-pane {
display: none;
}
.f0ck-tuner-subtab-pane.active {
display: block;
}
/* ── Danmaku Debug Tools & Buttons Grid ───────────────────── */
.f0ck-danmaku-debug-card {
background: rgba(0, 0, 0, 0.25);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
padding: 10px;
margin-bottom: 12px;
}
.f0ck-danmaku-spawner-row {
display: flex;
gap: 6px;
margin-bottom: 8px;
}
.f0ck-danmaku-spawner-meta {
display: flex;
gap: 6px;
margin-bottom: 8px;
align-items: center;
}
.f0ck-danmaku-debug-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin-bottom: 8px;
}
.f0ck-danmaku-debug-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 5px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.12);
color: #ddd;
padding: 6px 8px;
border-radius: 6px;
font-size: 11px;
font-weight: 600;
cursor: pointer;
transition: all 0.15s ease;
white-space: nowrap;
}
.f0ck-danmaku-debug-btn:hover {
background: rgba(var(--accent-rgb, 153, 255, 0), 0.15);
border-color: var(--accent, #99ff00);
color: var(--accent, #99ff00);
}
.f0ck-danmaku-debug-btn.btn-primary {
background: var(--accent, #99ff00);
color: #000;
border-color: var(--accent, #99ff00);
font-weight: 700;
}
.f0ck-danmaku-debug-btn.btn-primary:hover {
filter: brightness(1.15);
color: #000;
}
.f0ck-danmaku-debug-btn.btn-danger {
background: rgba(255, 68, 68, 0.12);
border-color: rgba(255, 68, 68, 0.35);
color: #ff6b6b;
}
.f0ck-danmaku-debug-btn.btn-danger:hover {
background: rgba(255, 68, 68, 0.28);
border-color: #ff4444;
color: #fff;
}
.f0ck-danmaku-debug-btn.btn-warning {
background: rgba(255, 180, 0, 0.12);
border-color: rgba(255, 180, 0, 0.35);
color: #ffb833;
}
.f0ck-danmaku-debug-btn.btn-warning:hover {
background: rgba(255, 180, 0, 0.28);
border-color: #ffaa00;
color: #fff;
}
.sidebar-video-details { .sidebar-video-details {
display: flex; display: flex;
margin-top: 8px; margin-top: 8px;
@@ -9846,6 +9989,43 @@ span#favs[hidden] {
opacity: 0.8; opacity: 0.8;
} }
._error_filter_actions {
margin-top: 10px;
display: flex;
justify-content: center;
}
._error_see_anyways_btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
background: var(--accent, #f2ef0b);
color: #111;
font-weight: 700;
font-size: 0.95em;
border-radius: 4px;
border: none;
cursor: pointer;
text-decoration: none;
transition: opacity 0.15s ease, transform 0.1s ease;
}
._error_see_anyways_btn i {
color: #111;
opacity: 0.9;
margin-right: 2px;
}
._error_see_anyways_btn:hover {
opacity: 0.9;
transform: translateY(-1px);
}
._error_see_anyways_btn:active {
transform: translateY(0);
}
/* Admin search css early test */ /* Admin search css early test */
.admin-search { .admin-search {
margin-top: 15px; margin-top: 15px;
@@ -10139,10 +10319,9 @@ div.favs div.posts {
a GPU blur pass on every compositor frame (incl. during the fade transition), a GPU blur pass on every compositor frame (incl. during the fade transition),
which is extremely expensive. Firefox uses a cheaper path for this. */ which is extremely expensive. Firefox uses a cheaper path for this. */
transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0);
z-index: 0;
transition: opacity 1.5s cubic-bezier(0.4, 0, 0.2, 1);
opacity: 0.2;
z-index: -2; z-index: -2;
transition: opacity 1.5s cubic-bezier(0.4, 0, 0.2, 1);
opacity: var(--bg-canvas-opacity, 1.0);
} }
button#togglebg { button#togglebg {
@@ -10179,13 +10358,13 @@ button#togglebg {
} }
100% { 100% {
opacity: 0.2; opacity: var(--bg-canvas-opacity, 1.0);
} }
} }
@keyframes fadeOut { @keyframes fadeOut {
0% { 0% {
opacity: 0.2; opacity: var(--bg-canvas-opacity, 1.0);
} }
100% { 100% {
@@ -10193,13 +10372,12 @@ button#togglebg {
} }
} }
#bg.fader-in,
.fader-in { .fader-in {
/*opacity: 0.4 !important;*/ opacity: var(--bg-canvas-opacity, 1.0) !important;
/* default */
opacity: 0.08 !important;
/* darker */
} }
#bg.fader-out,
.fader-out { .fader-out {
opacity: 0 !important; opacity: 0 !important;
} }
@@ -12503,6 +12681,45 @@ html[theme='paper'] .steuerung.steuerung-icon button:hover,
width: 100%; width: 100%;
} }
body.layout-modern .blahlol {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
}
body.layout-modern .blahlol .blahlol-meta {
display: inline-flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 6px;
width: 100%;
}
body.layout-modern .blahlol .gapRight {
display: inline-flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 6px;
}
body.layout-modern .blahlol:not(:has(.blahlol-meta)) {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 8px;
}
body.layout-modern .blahlol:not(:has(.blahlol-meta)) .gapRight {
flex-basis: 100%;
width: 100%;
}
span#favs { span#favs {
background: transparent !important; background: transparent !important;
} }
@@ -20500,31 +20717,35 @@ html:has(body.onara-modal-open) {
scrollbar-gutter: auto !important; scrollbar-gutter: auto !important;
} }
/* Background main page elements (outside posts) are dimmed and softly blurred */ /* Background main page elements and containers are transparent so #bg canvas and grid shine through */
body.onara-modal-open .pagewrapper { body.onara-modal-open .pagewrapper {
pointer-events: none !important; pointer-events: none !important;
user-select: none !important; user-select: none !important;
margin-top: var(--navbar-h, 50px) !important; margin-top: var(--navbar-h, 50px) !important;
background: transparent !important;
}
body.onara-modal-open .index-container,
body.onara-modal-open div.posts {
background: transparent !important;
} }
body.onara-modal-open .pagewrapper > *:not(.index-layout-wrapper):not(#main), body.onara-modal-open .pagewrapper > *:not(.index-layout-wrapper):not(#main),
body.onara-modal-open .index-container > *:not(.posts), body.onara-modal-open .index-container > *:not(.posts),
body.onara-modal-open #footbar, body.onara-modal-open #footbar,
body.onara-modal-open .pagination-container-fluid { body.onara-modal-open .pagination-container-fluid {
opacity: 0.25 !important; opacity: var(--onara-grid-dim-opacity, 1) !important;
filter: blur(1.5px) !important; filter: none !important;
transition: opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1), transition: opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1) !important;
filter 0.25s cubic-bezier(0.16, 1, 0.3, 1) !important;
} }
/* All non-active background thumbnails are strictly dimmed, blurred, with no outlines or badges */ /* All non-active background thumbnails shine through with the configured grid opacity */
body.onara-modal-open .posts > a.thumb:not(.onara-active) { body.onara-modal-open .posts > a.thumb:not(.onara-active) {
opacity: 0.25 !important; opacity: var(--onara-grid-dim-opacity, 1) !important;
filter: blur(1.5px) !important; filter: none !important;
box-shadow: none !important; box-shadow: none !important;
outline: none !important; outline: none !important;
transition: opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1), transition: opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1) !important;
filter 0.25s cubic-bezier(0.16, 1, 0.3, 1) !important;
} }
body.onara-modal-open .posts > a.thumb:not(.onara-active)::after { body.onara-modal-open .posts > a.thumb:not(.onara-active)::after {
@@ -20532,12 +20753,13 @@ body.onara-modal-open .posts > a.thumb:not(.onara-active)::after {
opacity: 0 !important; opacity: 0 !important;
} }
/* ONLY the single currently active thumbnail in the background shines through with TAB highlight */ /* ONLY the single currently active thumbnail in the background shines through with prominent glow */
body.onara-modal-open .posts > a.thumb.onara-active { body.onara-modal-open .posts > a.thumb.onara-active {
opacity: 1 !important; opacity: 1 !important;
filter: none !important; filter: none !important;
box-shadow: 0 0 0 2px var(--white, #fff), 0 0 16px rgba(255, 255, 255, 0.6) !important; box-shadow: 0 0 0 3px var(--accent, #9f0), 0 0 20px var(--accent, #9f0), 0 0 35px rgba(255, 255, 255, 0.9) !important;
z-index: 25 !important; z-index: 50 !important;
position: relative !important;
} }
body.onara-modal-open .posts > a.thumb.onara-active::after { body.onara-modal-open .posts > a.thumb.onara-active::after {
@@ -20599,9 +20821,9 @@ body.onara-modal-open .admin-bar.open {
z-index: 10050 !important; z-index: 10050 !important;
display: none; display: none;
flex-direction: column !important; flex-direction: column !important;
background: rgba(0, 0, 0, 0.35) !important; background: rgba(0, 0, 0, var(--onara-bg-opacity, 0.84)) !important;
backdrop-filter: blur(5px) saturate(130%) !important; backdrop-filter: blur(var(--onara-backdrop-blur, 5px)) saturate(130%) !important;
-webkit-backdrop-filter: blur(5px) saturate(130%) !important; -webkit-backdrop-filter: blur(var(--onara-backdrop-blur, 5px)) saturate(130%) !important;
overflow-y: auto !important; overflow-y: auto !important;
overflow-x: hidden !important; overflow-x: hidden !important;
-webkit-overflow-scrolling: touch; -webkit-overflow-scrolling: touch;
+27
View File
@@ -978,6 +978,33 @@
font-family: monospace; font-family: monospace;
} }
.global-redirect-section {
margin: 4px 0 2px 0;
}
.global-redirect-section .upload-checkbox-label {
display: inline-flex;
align-items: center;
gap: 8px;
cursor: pointer;
font-size: 0.88rem;
color: rgba(255, 255, 255, 0.85);
user-select: none;
transition: color 0.15s ease;
}
.global-redirect-section .upload-checkbox-label:hover {
color: #fff;
}
.global-redirect-section input[type="checkbox"] {
accent-color: var(--accent);
cursor: pointer;
width: 15px;
height: 15px;
margin: 0;
}
.upload-status { .upload-status {
text-align: center; text-align: center;
padding: 1rem; padding: 1rem;
+150 -10
View File
@@ -393,13 +393,14 @@
display: inline-flex; display: inline-flex;
flex-direction: column; /* stack lines vertically */ flex-direction: column; /* stack lines vertically */
align-items: flex-start; align-items: flex-start;
padding: 2px 0; padding: 2px 4px;
font-family: var(--font, inherit); font-family: var(--font, inherit);
font-size: 35px; font-size: var(--danmaku-font-size, 35px);
font-weight: 700; font-weight: var(--danmaku-font-weight, 700);
line-height: 1.1; line-height: 1.1;
gap: 0; gap: 0;
color: #fff; color: var(--danmaku-color, #fff);
opacity: var(--danmaku-opacity, 1);
/* Multi-layer outline shadow for readability over any background */ /* Multi-layer outline shadow for readability over any background */
text-shadow: text-shadow:
-1px -1px 0 #000, -1px -1px 0 #000,
@@ -412,12 +413,48 @@
background: none; background: none;
border: none; border: none;
text-align: left; text-align: left;
transition: opacity 0.15s ease;
}
/* Pill Background Variations */
.danmaku-overlay.danmaku-bg-glass .danmaku-pill {
background: rgba(10, 10, 14, 0.65);
backdrop-filter: blur(6px);
-webkit-backdrop-filter: blur(6px);
padding: 4px 12px;
border-radius: 8px;
border: 1px solid rgba(255, 255, 255, 0.12);
}
.danmaku-overlay.danmaku-bg-capsule .danmaku-pill {
background: rgba(18, 18, 24, 0.85);
padding: 4px 14px;
border-radius: 999px;
border: 1px solid rgba(var(--accent-rgb, 153, 255, 0), 0.35);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.6);
}
/* Shadow / Glow Variations */
.danmaku-overlay.danmaku-glow-neon .danmaku-pill {
text-shadow:
0 0 8px var(--danmaku-color, #99ff00),
0 0 18px var(--danmaku-color, #99ff00),
-1px -1px 0 #000,
1px 1px 0 #000;
}
.danmaku-overlay.danmaku-glow-none .danmaku-pill {
text-shadow: none;
}
.danmaku-overlay.danmaku-glow-subtle .danmaku-pill {
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.8);
} }
.danmaku-pill .dpill-text { .danmaku-pill .dpill-text {
font-family: var(--font, inherit); font-family: var(--font, inherit);
font-size: 35px; font-size: var(--danmaku-font-size, 35px);
font-weight: 700; font-weight: var(--danmaku-font-weight, 700);
white-space: nowrap; white-space: nowrap;
} }
@@ -434,6 +471,10 @@
white-space: nowrap; white-space: nowrap;
} }
.danmaku-overlay.danmaku-no-greentext .danmaku-pill .dpill-greentext {
color: inherit;
}
/* Spoiler inside a flying pill — black-on-black, click to reveal */ /* Spoiler inside a flying pill — black-on-black, click to reveal */
.danmaku-pill .dpill-spoiler { .danmaku-pill .dpill-spoiler {
background: #000; background: #000;
@@ -492,8 +533,8 @@
/* Inline image URL embedded in pill */ /* Inline image URL embedded in pill */
.danmaku-pill .dpill-img { .danmaku-pill .dpill-img {
max-height: 80px; max-height: var(--danmaku-media-max-h, 80px);
max-width: 120px; max-width: 140px;
width: auto; width: auto;
height: auto; height: auto;
vertical-align: middle; vertical-align: middle;
@@ -505,8 +546,8 @@
/* Inline video (converted GIF) in pill */ /* Inline video (converted GIF) in pill */
.danmaku-pill .dpill-video { .danmaku-pill .dpill-video {
max-height: 80px; max-height: var(--danmaku-media-max-h, 80px);
max-width: 120px; max-width: 140px;
width: auto; width: auto;
height: auto; height: auto;
vertical-align: middle; vertical-align: middle;
@@ -522,6 +563,105 @@
font-size: 0.9em; font-size: 0.9em;
} }
/* ── Danmaku Debug Overlays ────────────────────────────────── */
.danmaku-lane-guides-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 2;
box-sizing: border-box;
}
.danmaku-lane-guide {
position: absolute;
left: 0;
width: 100%;
border-top: 1px dashed rgba(var(--accent-rgb, 153, 255, 0), 0.35);
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 8px;
font-family: monospace;
font-size: 10px;
color: rgba(255, 255, 255, 0.6);
background: rgba(0, 0, 0, 0.04);
transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
}
.danmaku-lane-guide.occupied {
background: rgba(255, 60, 60, 0.12);
border-top: 1px dashed rgba(255, 60, 60, 0.65);
color: #ff7070;
}
.danmaku-lane-badge {
background: rgba(0, 0, 0, 0.65);
border: 1px solid rgba(255, 255, 255, 0.15);
padding: 1px 5px;
border-radius: 4px;
font-weight: 700;
}
.danmaku-lane-status {
font-size: 9px;
opacity: 0.9;
}
/* Diagnostic Live HUD */
.danmaku-debug-hud {
position: absolute;
top: 14px;
left: 14px;
z-index: 10;
background: rgba(12, 12, 16, 0.88);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid rgba(var(--accent-rgb, 153, 255, 0), 0.45);
border-radius: 8px;
padding: 8px 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 11px;
color: #e0e0e0;
pointer-events: none;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.7);
display: flex;
flex-direction: column;
gap: 4px;
line-height: 1.3;
min-width: 170px;
}
.danmaku-debug-hud .hud-title {
color: var(--accent, #99ff00);
font-weight: 700;
font-size: 11px;
border-bottom: 1px solid rgba(255, 255, 255, 0.12);
padding-bottom: 3px;
margin-bottom: 2px;
display: flex;
align-items: center;
gap: 6px;
}
.danmaku-debug-hud .hud-row {
display: flex;
justify-content: space-between;
gap: 12px;
}
.danmaku-debug-hud .hud-val {
color: #fff;
font-weight: 700;
}
.danmaku-debug-hud .hud-val.accent {
color: var(--accent, #99ff00);
}
@keyframes danmaku-fly { @keyframes danmaku-fly {
from { transform: translateX(calc(100vw + 100%)); } from { transform: translateX(calc(100vw + 100%)); }
to { transform: translateX(calc(-100% - 200px)); } to { transform: translateX(calc(-100% - 200px)); }
+52 -10
View File
@@ -288,9 +288,9 @@
if (!ctx) return; if (!ctx) return;
const { postid } = ctx; const { postid } = ctx;
// Read state BEFORE the API call so we know which direction to toggle // Read state BEFORE the API call so we have a fallback
const favoBtn = document.querySelector("#a_favo"); const favoBtns = document.querySelectorAll("#a_favo");
const wasAlreadyFav = favoBtn && favoBtn.classList.contains('fa-solid'); const wasAlreadyFav = favoBtns.length > 0 && favoBtns[0].classList.contains('fa-solid');
try { try {
const res = await post('/api/v2/togglefav', { const res = await post('/api/v2/togglefav', {
@@ -300,21 +300,60 @@
if (window.invalidateItemCache) { if (window.invalidateItemCache) {
window.invalidateItemCache(postid); window.invalidateItemCache(postid);
} }
// New state is the logical opposite of what it was before the API call // Authoritative server state takes priority; fallback to inverting previous UI state
const isNowFav = !wasAlreadyFav; const isNowFav = (res.favorited !== undefined) ? !!res.favorited : !wasAlreadyFav;
if (favoBtn) { favoBtns.forEach(favoBtn => {
favoBtn.classList.toggle('fa-solid', isNowFav); favoBtn.classList.toggle('fa-solid', isNowFav);
favoBtn.classList.toggle('fa-regular', !isNowFav); favoBtn.classList.toggle('fa-regular', !isNowFav);
} });
const favcontainer = document.querySelector('#favs'); const favcontainer = document.querySelector('#favs');
if (favcontainer) {
favcontainer.innerHTML = ""; favcontainer.innerHTML = "";
if (res.favs && res.favs.length > 0) { if (res.favs && res.favs.length > 0) {
const isAnonymized = !!(window.f0ckSession?.is_anonymized ?? (window.f0ckSession?.guest_anonymize && !window.f0ckSession?.logged_in) ?? (window.f0ckSession?.is_anon && window.f0ckSession?.anon_anonymize));
const fragment = document.createDocumentFragment();
res.favs.forEach(f => { res.favs.forEach(f => {
const isSelf = window.f0ckSession && (
(window.f0ckSession.id && f.user_id && Number(window.f0ckSession.id) === Number(f.user_id)) ||
(window.f0ckSession.user && f.user && window.f0ckSession.user.toLowerCase() === f.user.toLowerCase()) ||
(window.f0ckSession.login && f.login && window.f0ckSession.login.toLowerCase() === f.login.toLowerCase())
);
const isFavAnon = f.is_anon || f.user === 'anonymous' || (typeof f.user === 'string' && f.user.startsWith('anon_'));
if (f.hide_fav_badge && !isSelf) {
const a = document.createElement('a'); const a = document.createElement('a');
a.href = `/user/${f.user}`; a.className = 'ghost-fav';
a.setAttribute('tooltip', f.display_name || f.user); a.setAttribute('tooltip', '?');
a.setAttribute('flow', 'up');
a.style.cursor = 'default';
const img = document.createElement('img');
img.src = '/s/img/ghost_fav.svg';
img.style.height = "32px";
img.style.width = "32px";
a.appendChild(img);
fragment.appendChild(a);
} else if (isAnonymized || isFavAnon) {
const a = document.createElement('a');
a.className = 'ghost-fav';
a.setAttribute('tooltip', 'anonymous');
a.setAttribute('flow', 'up');
a.style.cursor = 'default';
const img = document.createElement('img');
img.src = '/a/default.png';
img.style.height = "32px";
img.style.width = "32px";
a.appendChild(img);
fragment.appendChild(a);
} else {
const a = document.createElement('a');
a.href = `/user/${(f.user || '').toLowerCase()}`;
a.setAttribute('tooltip', f.display_name || f.user || 'anonymous');
a.setAttribute('flow', 'up'); a.setAttribute('flow', 'up');
const img = document.createElement('img'); const img = document.createElement('img');
@@ -324,12 +363,15 @@
if (f.username_color) img.style.borderColor = f.username_color; if (f.username_color) img.style.borderColor = f.username_color;
a.appendChild(img); a.appendChild(img);
favcontainer.appendChild(a); fragment.appendChild(a);
}
}); });
favcontainer.appendChild(fragment);
favcontainer.hidden = false; favcontainer.hidden = false;
} else { } else {
favcontainer.hidden = true; favcontainer.hidden = true;
} }
}
window.flashMessage((window.f0ckI18n && (isNowFav ? window.f0ckI18n.fav_added : window.f0ckI18n.fav_removed)) || (isNowFav ? 'ADDED TO FAVORITES' : 'REMOVED FROM FAVORITES')); window.flashMessage((window.f0ckI18n && (isNowFav ? window.f0ckI18n.fav_added : window.f0ckI18n.fav_removed)) || (isNowFav ? 'ADDED TO FAVORITES' : 'REMOVED FROM FAVORITES'));
if (navigator.vibrate) navigator.vibrate(50); if (navigator.vibrate) navigator.vibrate(50);
+346 -88
View File
@@ -12,11 +12,42 @@
const PILL_MIN_MS = 6000; // Fastest a pill can cross the screen const PILL_MIN_MS = 6000; // Fastest a pill can cross the screen
const PILL_MAX_MS = 12000; // Slowest a pill can cross the screen const PILL_MAX_MS = 12000; // Slowest a pill can cross the screen
const LANE_COUNT = 10; // Vertical lane slots
const LOOKAHEAD_SEC = 0.25; // How far ahead of currentTime we look when scanning const LOOKAHEAD_SEC = 0.25; // How far ahead of currentTime we look when scanning
const MIN_RANDOM_SECS = 2; // Random timecode lower bound (avoid very start) const MIN_RANDOM_SECS = 2; // Random timecode lower bound (avoid very start)
const RANDOM_SPREAD = 0.85; // Use 85% of duration for random spread const RANDOM_SPREAD = 0.85; // Use 85% of duration for random spread
const DEFAULT_DANMAKU_TUNING = {
fontSize: 35,
opacity: 1.0,
speedMultiplier: 1.0,
laneCount: 10,
laneCoverage: 100,
fontWeight: 700,
outlineStyle: 2, // 0=None, 1=Subtle, 2=Default Outline, 3=Neon Glow
useCustomColor: 0,
customColor: '#ffffff',
pillBackground: 0, // 0=None, 1=Glass Card, 2=Solid Capsule
allowMediaEmbeds: 1,
mediaMaxHeight: 80,
showGreentext: 1,
densityLimit: 35,
flashInterval: 2.5,
showLaneGuides: 0,
showDebugHUD: 0
};
const loadDanmakuTuning = () => {
try {
const raw = localStorage.getItem('f0ck_danmaku_tuning');
return raw ? Object.assign({}, DEFAULT_DANMAKU_TUNING, JSON.parse(raw)) : Object.assign({}, DEFAULT_DANMAKU_TUNING);
} catch (e) {
return Object.assign({}, DEFAULT_DANMAKU_TUNING);
}
};
window.DEFAULT_DANMAKU_TUNING = DEFAULT_DANMAKU_TUNING;
window.danmakuTuning = window.danmakuTuning || loadDanmakuTuning();
/** /**
* SyntheticClock — emulates a <video> element's time API for non-video items * SyntheticClock — emulates a <video> element's time API for non-video items
* (Flash/Ruffle). Ticks at 4 Hz so Danmaku's timeupdate handler fires normally. * (Flash/Ruffle). Ticks at 4 Hz so Danmaku's timeupdate handler fires normally.
@@ -74,7 +105,10 @@ class Danmaku {
this.items = []; this.items = [];
this._lastTime = -1; this._lastTime = -1;
this._paused = false; this._paused = false;
this._laneUntil = new Array(LANE_COUNT).fill(0);
const initialLanes = Math.max(2, Math.min(30, Number(window.danmakuTuning?.laneCount) || 10));
this._laneUntil = new Array(initialLanes).fill(0);
// Site-wide config default // Site-wide config default
const configDefault = (window.f0ckSession && window.f0ckSession.enable_danmaku !== undefined) const configDefault = (window.f0ckSession && window.f0ckSession.enable_danmaku !== undefined)
? !!window.f0ckSession.enable_danmaku ? !!window.f0ckSession.enable_danmaku
@@ -100,12 +134,15 @@ class Danmaku {
this._initEmojiCache(); this._initEmojiCache();
this._createOverlay(); this._createOverlay();
this._applyTuning();
this._bound_onTuningChange = () => this._applyTuning();
window.addEventListener('f0ck:danmaku_tuning_changed', this._bound_onTuningChange);
this.media.addEventListener('timeupdate', this._bound_onTime, { passive: true }); this.media.addEventListener('timeupdate', this._bound_onTime, { passive: true });
this.media.addEventListener('seeked', this._bound_onSeek, { passive: true }); this.media.addEventListener('seeked', this._bound_onSeek, { passive: true });
this.media.addEventListener('pause', this._bound_onPause, { passive: true }); this.media.addEventListener('pause', this._bound_onPause, { passive: true });
this.media.addEventListener('play', this._bound_onPlay, { passive: true }); this.media.addEventListener('play', this._bound_onPlay, { passive: true });
// For Ruffle/SyntheticClock: no poller needed — clock runs freely
} }
/** /**
@@ -135,14 +172,12 @@ class Danmaku {
window.addEventListener('f0ck:emojis_ready', this._bound_onEmojis); window.addEventListener('f0ck:emojis_ready', this._bound_onEmojis);
// Aggressive retry: try every 500 ms for up to 30 attempts. // Aggressive retry: try every 500 ms for up to 30 attempts.
// Each attempt checks CommentSystem first (free), then falls back to a fetch.
let attempts = 0; let attempts = 0;
let fetched = false; let fetched = false;
const retry = () => { const retry = () => {
if (this._emojiCache && Object.keys(this._emojiCache).length > 0) return; // already got them if (this._emojiCache && Object.keys(this._emojiCache).length > 0) return;
if (++attempts > 30) return; if (++attempts > 30) return;
// 1. CommentSystem populated by now?
const cs = tryCs(); const cs = tryCs();
if (cs) { if (cs) {
this._emojiCache = cs; this._emojiCache = cs;
@@ -150,7 +185,6 @@ class Danmaku {
return; return;
} }
// 2. Kick off the HTTP fetch once; then just wait for it / the event
if (!fetched) { if (!fetched) {
fetched = true; fetched = true;
fetch('/api/v2/emojis') fetch('/api/v2/emojis')
@@ -169,14 +203,13 @@ class Danmaku {
}) })
.catch(err => { .catch(err => {
console.warn('[Danmaku] emoji fetch failed:', err.message); console.warn('[Danmaku] emoji fetch failed:', err.message);
fetched = false; // allow retry fetched = false;
}); });
} }
// Schedule next check
if (!this._destroyed) setTimeout(retry, 500); if (!this._destroyed) setTimeout(retry, 500);
}; };
setTimeout(retry, 200); // first attempt after a short grace window setTimeout(retry, 200);
} }
// ── Public API ──────────────────────────────────────────────────────────── // ── Public API ────────────────────────────────────────────────────────────
@@ -205,14 +238,11 @@ class Danmaku {
})); }));
if (this._synthClock) { if (this._synthClock) {
// Flash/Ruffle mode: bypass the timeline entirely.
// Store pool and start the random continuous loop.
this._flashPool = mapped; this._flashPool = mapped;
this._startFlashLoop(); this._startFlashLoop();
return; // don't touch this.items / _lastTime return;
} }
// Normal video mode: use video_time, random spread for nulls
this.items = mapped.map(item => { this.items = mapped.map(item => {
if (item.raw_time !== null) { if (item.raw_time !== null) {
item.video_time = item.raw_time; item.video_time = item.raw_time;
@@ -231,16 +261,13 @@ class Danmaku {
/** /**
* Random continuous loop for Flash/Ruffle. * Random continuous loop for Flash/Ruffle.
* Fires one comment every 2-5 s (random), reshuffles pool on exhaustion.
*/ */
_startFlashLoop() { _startFlashLoop() {
// Cancel any previous loop
if (this._flashTimer) clearTimeout(this._flashTimer); if (this._flashTimer) clearTimeout(this._flashTimer);
this._flashTimer = null; this._flashTimer = null;
if (!this._flashPool || this._flashPool.length === 0) return; if (!this._flashPool || this._flashPool.length === 0) return;
// Shuffle helper
const shuffle = arr => { const shuffle = arr => {
for (let i = arr.length - 1; i > 0; i--) { for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); const j = Math.floor(Math.random() * (i + 1));
@@ -249,14 +276,12 @@ class Danmaku {
return arr; return arr;
}; };
// Working queue — randomised copy of pool
let queue = shuffle([...this._flashPool]); let queue = shuffle([...this._flashPool]);
let idx = 0; let idx = 0;
const tick = () => { const tick = () => {
if (this._destroyed || !this._enabled) return; if (this._destroyed || !this._enabled) return;
// Refill and reshuffle when queue exhausted
if (idx >= queue.length) { if (idx >= queue.length) {
queue = shuffle([...this._flashPool]); queue = shuffle([...this._flashPool]);
idx = 0; idx = 0;
@@ -265,12 +290,12 @@ class Danmaku {
const item = queue[idx++]; const item = queue[idx++];
this._spawnPill(item.text, item.username, item.color); this._spawnPill(item.text, item.username, item.color);
// Random delay 2 5 seconds between pills const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
const delay = 2000 + Math.random() * 3000; const baseInterval = Math.max(0.4, Number(cfg.flashInterval) || 2.5);
const delay = (baseInterval * 1000) + Math.random() * (baseInterval * 1200);
this._flashTimer = setTimeout(tick, delay); this._flashTimer = setTimeout(tick, delay);
}; };
// Small initial delay so page finishes loading before first pill
this._flashTimer = setTimeout(tick, 800); this._flashTimer = setTimeout(tick, 800);
} }
@@ -284,8 +309,6 @@ class Danmaku {
/** /**
* Add a new comment to the timeline so it loops back in future playback. * Add a new comment to the timeline so it loops back in future playback.
* Also fires it immediately as a one-shot pill.
* @param {Object} comment — raw comment object from API
*/ */
addItem(comment) { addItem(comment) {
if (!comment || !comment.content) return; if (!comment || !comment.content) return;
@@ -314,7 +337,7 @@ class Danmaku {
text: this._prepareText(comment.content), text: this._prepareText(comment.content),
username: comment.display_name || comment.username || '?', username: comment.display_name || comment.username || '?',
color: comment.username_color || null, color: comment.username_color || null,
fired: true // mark as already fired — caller handles any immediate one-shot fired: true
}; };
if (this._synthClock && this._flashPool) { if (this._synthClock && this._flashPool) {
@@ -324,7 +347,6 @@ class Danmaku {
return; return;
} }
// Insert in sorted order
const idx = this.items.findIndex(i => i.video_time > t); const idx = this.items.findIndex(i => i.video_time > t);
if (idx === -1) this.items.push(item); if (idx === -1) this.items.push(item);
else this.items.splice(idx, 0, item); else this.items.splice(idx, 0, item);
@@ -334,9 +356,8 @@ class Danmaku {
toggle() { toggle() {
this._enabled = !this._enabled; this._enabled = !this._enabled;
localStorage.setItem('danmaku', this._enabled ? 'true' : 'false'); localStorage.setItem('danmaku', this._enabled ? 'true' : 'false');
this.overlay.style.display = this._enabled ? '' : 'none'; if (this.overlay) this.overlay.style.display = this._enabled ? '' : 'none';
// Update the switch if it exists in the player
const sw = this.player.querySelector('#toggledanmaku'); const sw = this.player.querySelector('#toggledanmaku');
if (sw) sw.classList.toggle('active', this._enabled); if (sw) sw.classList.toggle('active', this._enabled);
} }
@@ -348,13 +369,123 @@ class Danmaku {
isEnabled() { return this._enabled; } isEnabled() { return this._enabled; }
toggleLoop(forcedVal, options = {}) {
this._loopMode = (forcedVal !== undefined) ? !!forcedVal : !this._loopMode;
if (this._loopMode) {
this.items.forEach(i => { i.fired = false; });
this._startDebugContinuousLoop(options.interval || 220, options.customText, options.username, options.color);
} else {
this._stopDebugContinuousLoop();
}
return this._loopMode;
}
isLooping() {
return !!this._loopMode;
}
_getSampleComments() {
return [
{ text: 'Danmaku burst test! :kreygasm:', username: 'BurstUser', color: '#ffcc00' },
{ text: '>be me\n>browsing f0ck\n>feels good man', username: 'Anon', color: '#78b87a' },
{ text: '[spoiler]Secret Classified Spoiler[/spoiler]', username: 'Agent007', color: '#ff5577' },
{ text: '[blur]Sensitive content blur reveal[/blur]', username: 'ModUser', color: '#bb77ff' },
{ text: 'Testing flight speed & collision avoidance 🚀', username: 'DevTester', color: '#00e5ff' },
{ text: '弾幕 Nico Nico style flying comment', username: 'Otaku', color: '#ff88aa' },
{ text: 'Super high density bullet stream! ⚡⚡', username: 'HyperUser', color: '#99ff00' },
{ text: 'FeelsGoodMan :feelsgood:', username: 'Pepe', color: '#55cc55' },
{ text: 'Nice visualizer and danmaku sync! 🔥', username: 'Vibes', color: '#ff6600' },
{ text: '>mfw danmaku is running infinitely :dance_fart:', username: 'F0cker', color: '#78b87a' }
];
}
_startDebugContinuousLoop(interval = 220, customText = null, username = null, color = null) {
if (this._debugLoopTimer) clearInterval(this._debugLoopTimer);
let idx = 0;
const tick = () => {
if (this._destroyed || !this._enabled || !this._loopMode) {
this._stopDebugContinuousLoop();
return;
}
if (customText) {
this._spawnPill(customText, username || 'LoopTester', color || '#00ffcc');
} else {
let pool = (this.items && this.items.length > 0) ? this.items : (this._flashPool || []);
if (!pool || pool.length === 0) {
pool = this._getSampleComments();
}
if (idx >= pool.length) {
idx = 0;
pool.forEach(i => { i.fired = false; });
}
const item = pool[idx++];
if (item) {
this._spawnPill(item.text, item.username || 'Tester', item.color || null);
}
}
};
tick();
this._debugLoopTimer = setInterval(tick, Math.max(40, interval));
}
_stopDebugContinuousLoop() {
if (this._debugLoopTimer) {
clearInterval(this._debugLoopTimer);
this._debugLoopTimer = null;
}
}
clearActivePills() {
if (!this.overlay) return;
this.overlay.querySelectorAll('.danmaku-pill').forEach(p => p.remove());
}
resetTimeline() {
if (this._synthClock) {
this._loopSynth();
} else {
this._resetFiredState(this.media ? this.media.currentTime : 0);
this._lastTime = this.media ? this.media.currentTime : 0;
}
}
fireBurst(count = 10, options = {}) {
const isFlood = count > 15;
const interval = isFlood ? 100 : 160;
if (this._loopMode) {
this._startDebugContinuousLoop(interval, options.text, options.username, options.color);
return;
}
const samples = this._getSampleComments();
for (let i = 0; i < count; i++) {
setTimeout(() => {
if (this._destroyed || !this._enabled) return;
const sample = samples[i % samples.length];
const text = options.text ? `${options.text} #${i + 1}` : `${sample.text} #${i + 1}`;
const user = options.username || sample.username;
const col = options.color || sample.color;
this.fire(text, user, col);
}, i * interval);
}
}
destroy() { destroy() {
this._destroyed = true; this._destroyed = true;
this._stopDebugContinuousLoop();
this.media.removeEventListener('timeupdate', this._bound_onTime); this.media.removeEventListener('timeupdate', this._bound_onTime);
this.media.removeEventListener('seeked', this._bound_onSeek); this.media.removeEventListener('seeked', this._bound_onSeek);
this.media.removeEventListener('pause', this._bound_onPause); this.media.removeEventListener('pause', this._bound_onPause);
this.media.removeEventListener('play', this._bound_onPlay); this.media.removeEventListener('play', this._bound_onPlay);
if (this._bound_onEmojis) window.removeEventListener('f0ck:emojis_ready', this._bound_onEmojis); if (this._bound_onEmojis) window.removeEventListener('f0ck:emojis_ready', this._bound_onEmojis);
if (this._bound_onTuningChange) window.removeEventListener('f0ck:danmaku_tuning_changed', this._bound_onTuningChange);
if (this._laneGuidesTimer) clearInterval(this._laneGuidesTimer);
if (this._hudTimer) clearInterval(this._hudTimer);
if (this._rufflePoller) clearInterval(this._rufflePoller); if (this._rufflePoller) clearInterval(this._rufflePoller);
if (this._flashTimer) clearTimeout(this._flashTimer); if (this._flashTimer) clearTimeout(this._flashTimer);
if (this._synthClock) this._synthClock.destroy(); if (this._synthClock) this._synthClock.destroy();
@@ -371,22 +502,150 @@ class Danmaku {
this.player.appendChild(this.overlay); this.player.appendChild(this.overlay);
} }
_applyTuning() {
if (!this.overlay) return;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
this.overlay.style.setProperty('--danmaku-font-size', (cfg.fontSize || 35) + 'px');
this.overlay.style.setProperty('--danmaku-opacity', cfg.opacity !== undefined ? cfg.opacity : 1);
this.overlay.style.setProperty('--danmaku-font-weight', cfg.fontWeight || 700);
this.overlay.style.setProperty('--danmaku-color', Number(cfg.useCustomColor) === 1 ? (cfg.customColor || '#ffffff') : '#ffffff');
this.overlay.style.setProperty('--danmaku-media-max-h', (cfg.mediaMaxHeight || 80) + 'px');
this.overlay.classList.toggle('danmaku-bg-glass', Number(cfg.pillBackground) === 1);
this.overlay.classList.toggle('danmaku-bg-capsule', Number(cfg.pillBackground) === 2);
this.overlay.classList.toggle('danmaku-glow-none', Number(cfg.outlineStyle) === 0);
this.overlay.classList.toggle('danmaku-glow-subtle', Number(cfg.outlineStyle) === 1);
this.overlay.classList.toggle('danmaku-glow-neon', Number(cfg.outlineStyle) === 3);
this.overlay.classList.toggle('danmaku-no-greentext', Number(cfg.showGreentext) === 0);
const targetLanes = Math.max(2, Math.min(30, Number(cfg.laneCount) || 10));
if (this._laneUntil.length !== targetLanes) {
const old = this._laneUntil;
this._laneUntil = new Array(targetLanes).fill(0);
for (let i = 0; i < Math.min(old.length, targetLanes); i++) {
this._laneUntil[i] = old[i];
}
}
this._updateLaneGuides();
this._updateDebugHUD();
}
_updateLaneGuides() {
if (!this.overlay) return;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
let guides = this.overlay.querySelector('.danmaku-lane-guides-container');
if (!cfg.showLaneGuides) {
if (guides) guides.remove();
if (this._laneGuidesTimer) {
clearInterval(this._laneGuidesTimer);
this._laneGuidesTimer = null;
}
return;
}
if (!guides) {
guides = document.createElement('div');
guides.className = 'danmaku-lane-guides-container';
this.overlay.appendChild(guides);
}
const laneCount = this._laneUntil.length || 10;
const coverage = Math.min(100, Math.max(10, Number(cfg.laneCoverage) || 100)) / 100;
const laneH = (100 * coverage) / laneCount;
let html = '';
const now = Date.now();
for (let i = 0; i < laneCount; i++) {
const topPct = i * laneH;
const isOccupied = (this._laneUntil[i] || 0) > now;
const remainingSec = isOccupied ? (((this._laneUntil[i] - now) / 1000).toFixed(1) + 's') : 'FREE';
html += `
<div class="danmaku-lane-guide ${isOccupied ? 'occupied' : ''}" style="top: ${topPct}%; height: ${laneH}%;">
<span class="danmaku-lane-badge">L${i} (${topPct.toFixed(0)}%)</span>
<span class="danmaku-lane-status">${remainingSec}</span>
</div>
`;
}
guides.innerHTML = html;
if (!this._laneGuidesTimer) {
this._laneGuidesTimer = setInterval(() => {
if (this._destroyed || !this.overlay || !window.danmakuTuning?.showLaneGuides) {
if (this._laneGuidesTimer) clearInterval(this._laneGuidesTimer);
this._laneGuidesTimer = null;
return;
}
this._updateLaneGuides();
}, 300);
}
}
_updateDebugHUD() {
if (!this.overlay) return;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
let hud = this.overlay.querySelector('.danmaku-debug-hud');
if (!cfg.showDebugHUD) {
if (hud) hud.remove();
if (this._hudTimer) {
clearInterval(this._hudTimer);
this._hudTimer = null;
}
return;
}
if (!hud) {
hud = document.createElement('div');
hud.className = 'danmaku-debug-hud';
this.overlay.appendChild(hud);
}
const activePills = this.overlay.querySelectorAll('.danmaku-pill').length;
const totalItems = this.items.length || (this._flashPool ? this._flashPool.length : 0);
const firedItems = this.items.filter(i => i.fired).length;
const curTime = (this.media ? this.media.currentTime : 0).toFixed(1);
const emojiCount = Object.keys(this._emojiCache || {}).length;
hud.innerHTML = `
<div class="hud-title"><i class="fa-solid fa-bolt"></i> Danmaku Debug HUD</div>
<div class="hud-row"><span>Active Pills:</span><span class="hud-val accent">${activePills} / ${cfg.densityLimit || 35}</span></div>
<div class="hud-row"><span>Loaded Comments:</span><span class="hud-val">${totalItems} (fired: ${firedItems})</span></div>
<div class="hud-row"><span>Clock Time:</span><span class="hud-val">${curTime}s ${this._synthClock ? '(Synth)' : ''}</span></div>
<div class="hud-row"><span>Lanes:</span><span class="hud-val">${this._laneUntil.length} (${cfg.laneCoverage || 100}%)</span></div>
<div class="hud-row"><span>Speed Multiplier:</span><span class="hud-val">${cfg.speedMultiplier || 1.0}x</span></div>
<div class="hud-row"><span>Emoji Cache:</span><span class="hud-val">${emojiCount} emojis</span></div>
`;
if (!this._hudTimer) {
this._hudTimer = setInterval(() => {
if (this._destroyed || !this.overlay || !window.danmakuTuning?.showDebugHUD) {
if (this._hudTimer) clearInterval(this._hudTimer);
this._hudTimer = null;
return;
}
this._updateDebugHUD();
}, 250);
}
}
_onPause() { _onPause() {
this._paused = true; this._paused = true;
if (this._synthClock) this._synthClock.pause(); if (this._synthClock) this._synthClock.pause();
// Do NOT pause pill animations — pills already in flight always complete.
} }
_onPlay() { _onPlay() {
this._paused = false; this._paused = false;
if (this._synthClock) this._synthClock.resume(); if (this._synthClock) this._synthClock.resume();
// Nothing to do for in-flight pills — they were never paused.
} }
_checkRuffleState() { _checkRuffleState() {
const rp = document.querySelector('ruffle-player, ruffle-object'); const rp = document.querySelector('ruffle-player, ruffle-object');
if (!rp) return; if (!rp) return;
// Ruffle exposes is_playing on the element
const isPlaying = rp.is_playing !== undefined ? !!rp.is_playing : true; const isPlaying = rp.is_playing !== undefined ? !!rp.is_playing : true;
if (isPlaying && this._paused) this._onPlay(); if (isPlaying && this._paused) this._onPlay();
if (!isPlaying && !this._paused) this._onPause(); if (!isPlaying && !this._paused) this._onPause();
@@ -400,7 +659,6 @@ class Danmaku {
const prev = this._lastTime; const prev = this._lastTime;
this._lastTime = now; this._lastTime = now;
// Detect video loop (time jumped backwards) — reset so comments fire again
if (now < prev - 0.5) { if (now < prev - 0.5) {
this._resetFiredState(now); this._resetFiredState(now);
return; return;
@@ -411,22 +669,20 @@ class Danmaku {
for (const item of this.items) { for (const item of this.items) {
if (item.fired) continue; if (item.fired) continue;
if (item.video_time < from) { item.fired = true; continue; } // already passed if (item.video_time < from) { item.fired = true; continue; }
if (item.video_time > to) break; // sorted, nothing further in range if (item.video_time > to) break;
item.fired = true; item.fired = true;
this._spawnPill(item.text, item.username, item.color); this._spawnPill(item.text, item.username, item.color);
} }
// Loop for SyntheticClock (Flash/Ruffle): once all items have fired, restart
if (this._synthClock && this.items.length > 0 && this.items.every(i => i.fired)) { if (this._synthClock && this.items.length > 0 && this.items.every(i => i.fired)) {
this._loopSynth(); this._loopSynth();
} }
} }
/** Reset all fired flags and the synthetic clock for looping. */
_loopSynth() { _loopSynth() {
this.items.forEach(i => { i.fired = false; }); this.items.forEach(i => { i.fired = false; });
this._synthClock.reset(); // back to t=0 this._synthClock.reset();
this._lastTime = 0; this._lastTime = 0;
} }
@@ -443,38 +699,50 @@ class Danmaku {
_pickLane() { _pickLane() {
const now = Date.now(); const now = Date.now();
// Find the lane that will be free soonest const laneCount = this._laneUntil.length || 10;
let best = 0; let best = 0;
let bestFree = this._laneUntil[0]; let bestFree = this._laneUntil[0] || 0;
for (let i = 1; i < LANE_COUNT; i++) { for (let i = 1; i < laneCount; i++) {
if (this._laneUntil[i] < bestFree) { if ((this._laneUntil[i] || 0) < bestFree) {
bestFree = this._laneUntil[i]; bestFree = this._laneUntil[i];
best = i; best = i;
} }
} }
// Occupy the lane — use the max duration so slower pills don't get overwritten const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
this._laneUntil[best] = now + PILL_MAX_MS; const speedMult = Math.max(0.2, Number(cfg.speedMultiplier) || 1.0);
const maxMs = PILL_MAX_MS / speedMult;
this._laneUntil[best] = now + maxMs;
return best; return best;
} }
_spawnPill(text, username, color) { _spawnPill(text, username, color) {
if (!this.overlay || !this._enabled || this._paused) return; if (!this.overlay || !this._enabled || this._paused) return;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
const limit = Number(cfg.densityLimit) || 35;
const currentPills = this.overlay.querySelectorAll('.danmaku-pill');
if (currentPills.length >= limit) {
if (currentPills[0]) currentPills[0].remove();
}
const pill = document.createElement('div'); const pill = document.createElement('div');
pill.className = 'danmaku-pill'; pill.className = 'danmaku-pill';
// Lane assignment — distribute vertically to avoid full overlap
const lane = this._pickLane(); const lane = this._pickLane();
const laneH = 100 / LANE_COUNT; const laneCount = this._laneUntil.length || 10;
const topPct = lane * laneH + (laneH * 0.1); // slight inset const coverage = Math.min(100, Math.max(10, Number(cfg.laneCoverage) || 100)) / 100;
const laneH = (100 * coverage) / laneCount;
const topPct = lane * laneH + (laneH * 0.1);
pill.style.top = topPct + '%'; pill.style.top = topPct + '%';
// Message content — store raw text for deferred emoji re-render if (Number(cfg.useCustomColor) === 1 && cfg.customColor) {
pill.style.color = cfg.customColor;
}
const msg = document.createElement('span'); const msg = document.createElement('span');
msg.className = 'dpill-text'; msg.className = 'dpill-text';
msg.dataset.rawText = text; msg.dataset.rawText = text;
// Read the freshest emoji source available at spawn time
const liveCache = (this._emojiCache && Object.keys(this._emojiCache).length > 0) const liveCache = (this._emojiCache && Object.keys(this._emojiCache).length > 0)
? this._emojiCache ? this._emojiCache
: ((typeof CommentSystem !== 'undefined' && CommentSystem.emojiCache) || null); : ((typeof CommentSystem !== 'undefined' && CommentSystem.emojiCache) || null);
@@ -482,29 +750,23 @@ class Danmaku {
msg.appendChild(this._renderContent(text)); msg.appendChild(this._renderContent(text));
// Track pill for deferred re-render if emojis weren't ready yet
if (!this._emojiCache || Object.keys(this._emojiCache).length === 0) { if (!this._emojiCache || Object.keys(this._emojiCache).length === 0) {
if (!this._pendingPills) this._pendingPills = new Set(); if (!this._pendingPills) this._pendingPills = new Set();
this._pendingPills.add(msg); this._pendingPills.add(msg);
} }
pill.appendChild(msg); pill.appendChild(msg);
// Insert paused so we can measure before animation fires
this.overlay.appendChild(pill); this.overlay.appendChild(pill);
// Duration scales with text length so long comments get enough time to cross.
// Formula: 5s base + 25ms per character, clamped to [6s, 45s].
const charCount = text.length; const charCount = text.length;
const duration = Math.min(Math.max(5000 + charCount * 25, PILL_MIN_MS), 45_000); const speedMult = Math.max(0.2, Number(cfg.speedMultiplier) || 1.0);
const baseDuration = Math.min(Math.max(5000 + charCount * 25, PILL_MIN_MS), 45_000);
const duration = baseDuration / speedMult;
// Use actual scroll (content) width — wider than offsetWidth for very long lines.
// This ensures the animation pixel travel is enough for ALL content to exit left,
// not just the max-width-capped pill box.
const overlayW = this.overlay.offsetWidth || window.innerWidth || 1920; const overlayW = this.overlay.offsetWidth || window.innerWidth || 1920;
const contentW = pill.scrollWidth || pill.offsetWidth || 200; const contentW = pill.scrollWidth || pill.offsetWidth || 200;
const startX = overlayW + contentW; // off-screen right const startX = overlayW + contentW;
const endX = -(contentW + 200); // fully off-screen left, overflow included const endX = -(contentW + 200);
const anim = pill.animate( const anim = pill.animate(
[ [
@@ -514,23 +776,20 @@ class Danmaku {
{ duration, easing: 'linear', fill: 'none' } { duration, easing: 'linear', fill: 'none' }
); );
// Remove pill once animation completes
anim.addEventListener('finish', () => { anim.addEventListener('finish', () => {
if (pill.parentNode) pill.parentNode.removeChild(pill); if (pill.parentNode) pill.parentNode.removeChild(pill);
}, { once: true }); }, { once: true });
// Failsafe in case the Animations API finish event doesn't fire
pill._timeoutId = setTimeout(() => { if (pill.parentNode) pill.parentNode.removeChild(pill); }, duration + 1000); pill._timeoutId = setTimeout(() => { if (pill.parentNode) pill.parentNode.removeChild(pill); }, duration + 1000);
} }
/** Re-render pending pills once emojis are available. */ /** Re-render pending pills once emojis are available. */
_reRenderEmojis() { _reRenderEmojis() {
if (!this.overlay) return; if (!this.overlay) return;
// Prefer direct element tracking (fast, no DOM query needed)
const pending = this._pendingPills; const pending = this._pendingPills;
if (pending && pending.size > 0) { if (pending && pending.size > 0) {
pending.forEach(msg => { pending.forEach(msg => {
if (!msg.parentNode) { pending.delete(msg); return; } // already removed if (!msg.parentNode) { pending.delete(msg); return; }
const raw = msg.dataset.rawText; const raw = msg.dataset.rawText;
if (!raw) return; if (!raw) return;
msg.textContent = ''; msg.textContent = '';
@@ -538,11 +797,9 @@ class Danmaku {
}); });
pending.clear(); pending.clear();
} }
// Also sweep any pills that slipped through (belt-and-suspenders)
this.overlay.querySelectorAll('.dpill-text[data-raw-text]').forEach(msg => { this.overlay.querySelectorAll('.dpill-text[data-raw-text]').forEach(msg => {
const raw = msg.dataset.rawText; const raw = msg.dataset.rawText;
if (!raw) return; if (!raw) return;
// Only re-render if the content is still plain text (no img children)
if (!msg.querySelector('.dpill-emoji')) { if (!msg.querySelector('.dpill-emoji')) {
msg.textContent = ''; msg.textContent = '';
msg.appendChild(this._renderContent(raw)); msg.appendChild(this._renderContent(raw));
@@ -559,10 +816,8 @@ class Danmaku {
const prepared = this._prepareText(rawText); const prepared = this._prepareText(rawText);
const frag = document.createDocumentFragment(); const frag = document.createDocumentFragment();
const cache = this._emojiCache; // always use full cache in danmaku const cache = this._emojiCache;
// Process line by line — leading > lines become greentext
// Filter empty lines to avoid ghost rows from trailing newlines
const lines = prepared.split('\n').filter(l => l.trim() !== ''); const lines = prepared.split('\n').filter(l => l.trim() !== '');
lines.forEach((line) => { lines.forEach((line) => {
const isQuote = /^>\s?/.test(line); const isQuote = /^>\s?/.test(line);
@@ -579,10 +834,8 @@ class Danmaku {
/** /**
* Renders inline content (spoiler/blur/emoji) into a parent node. * Renders inline content (spoiler/blur/emoji) into a parent node.
* Prepends a space before the first text chunk for visual separation.
*/ */
_renderInline(text, parent, emojiCache) { _renderInline(text, parent, emojiCache) {
// match[1]=spoiler, match[2]=blur, match[3]=emoji, match[4]=inline-img-url
const combined = /\[spoiler\]([\s\S]*?)\[\/spoiler\]|\[blur\]([\s\S]*?)\[\/blur\]|:([a-z0-9_+\-]+):|\x04([^\x05]+)\x05/gi; const combined = /\[spoiler\]([\s\S]*?)\[\/spoiler\]|\[blur\]([\s\S]*?)\[\/blur\]|:([a-z0-9_+\-]+):|\x04([^\x05]+)\x05/gi;
let lastIndex = 0; let lastIndex = 0;
let match; let match;
@@ -597,14 +850,14 @@ class Danmaku {
span.className = 'dpill-spoiler'; span.className = 'dpill-spoiler';
span.title = 'Click to reveal spoiler'; span.title = 'Click to reveal spoiler';
span.addEventListener('click', (e) => { e.stopPropagation(); span.classList.toggle('revealed'); }); span.addEventListener('click', (e) => { e.stopPropagation(); span.classList.toggle('revealed'); });
this._renderInline(match[1], span, emojiCache); // recursive so emojis inside spoilers work this._renderInline(match[1], span, emojiCache);
parent.appendChild(span); parent.appendChild(span);
} else if (match[2] !== undefined) { } else if (match[2] !== undefined) {
const span = document.createElement('span'); const span = document.createElement('span');
span.className = 'dpill-blur'; span.className = 'dpill-blur';
span.title = 'Click to reveal'; span.title = 'Click to reveal';
span.addEventListener('click', (e) => { e.stopPropagation(); span.classList.toggle('revealed'); }); span.addEventListener('click', (e) => { e.stopPropagation(); span.classList.toggle('revealed'); });
this._renderInline(match[2], span, emojiCache); // recursive so emojis inside blur work this._renderInline(match[2], span, emojiCache);
parent.appendChild(span); parent.appendChild(span);
} else if (match[3]) { } else if (match[3]) {
const code = match[3]; const code = match[3];
@@ -634,12 +887,17 @@ class Danmaku {
} }
} else if (match[4]) { } else if (match[4]) {
const mediaUrl = match[4]; const mediaUrl = match[4];
const isConvertedGif = mediaUrl.endsWith('#gif');
const cleanUrl = mediaUrl.replace(/#gif$/, ''); const cleanUrl = mediaUrl.replace(/#gif$/, '');
const videoExts = /\.(?:mp4|webm|ogv|mov)$/i; const videoExts = /\.(?:mp4|webm|ogv|mov)$/i;
const audioExts = /\.(?:mp3|ogg|wav|flac|aac|opus|m4a)$/i; const audioExts = /\.(?:mp3|ogg|wav|flac|aac|opus|m4a)$/i;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
if (videoExts.test(cleanUrl)) { if (Number(cfg.allowMediaEmbeds) === 0) {
const span = document.createElement('span');
span.className = 'dpill-media-placeholder';
span.textContent = ' [attachment] ';
parent.appendChild(span);
} else if (videoExts.test(cleanUrl)) {
const vid = document.createElement('video'); const vid = document.createElement('video');
vid.src = cleanUrl; vid.src = cleanUrl;
vid.className = 'dpill-video'; vid.className = 'dpill-video';
@@ -674,17 +932,12 @@ class Danmaku {
_prepareText(text) { _prepareText(text) {
if (!text) return ''; if (!text) return '';
// Protect emoji codes from the bold/italic underscore regex.
// e.g. `:dance_fart: :dance_fart:` would have its underscores eaten
// when the regex pairs the _ from the first code with the _ in the second.
const emojiTokens = []; const emojiTokens = [];
let protected_ = text.replace(/:([a-z0-9_+\-]+):/gi, (match) => { let protected_ = text.replace(/:([a-z0-9_+\-]+):/gi, (match) => {
emojiTokens.push(match); emojiTokens.push(match);
return `\x02${emojiTokens.length - 1}\x03`; // private-use delimiters return `\x02${emojiTokens.length - 1}\x03`;
}); });
// Tokenize image URLs with \x04URL\x05 so they survive all regexes and reach _renderInline
// Only embed images from the allowed-images allowlist (window.f0ckAllowedImages) or same site
const allowedHosts = Array.isArray(window.f0ckAllowedImages) ? window.f0ckAllowedImages : []; const allowedHosts = Array.isArray(window.f0ckAllowedImages) ? window.f0ckAllowedImages : [];
const siteHost = window.location.hostname; const siteHost = window.location.hostname;
const isAllowedImg = (url) => { const isAllowedImg = (url) => {
@@ -695,16 +948,14 @@ class Danmaku {
}; };
const imgTokenUrls = []; const imgTokenUrls = [];
protected_ = protected_ protected_ = protected_
// Tokenize relative /c/ media URLs (comment attachments)
.replace(/\/c\/[a-f0-9]+\.(?:png|jpg|jpeg|gif|webp|svg|avif|mp4|webm|ogv|mov|mp3|ogg|wav|flac|aac|opus|m4a)(?:#gif)?/gi, (url) => { .replace(/\/c\/[a-f0-9]+\.(?:png|jpg|jpeg|gif|webp|svg|avif|mp4|webm|ogv|mov|mp3|ogg|wav|flac|aac|opus|m4a)(?:#gif)?/gi, (url) => {
imgTokenUrls.push(url); imgTokenUrls.push(url);
return `\x04${imgTokenUrls.length - 1}\x05`; return `\x04${imgTokenUrls.length - 1}\x05`;
}) })
// Stop at protocol boundaries so concatenated URLs aren't merged into one broken src.
.replace(/https?:\/\/(?:(?!https?:\/\/)\S)+\.(?:png|jpg|jpeg|gif|webp|svg|avif)(\?(?:(?!https?:\/\/)\S)*)?/gi, (url) => { .replace(/https?:\/\/(?:(?!https?:\/\/)\S)+\.(?:png|jpg|jpeg|gif|webp|svg|avif)(\?(?:(?!https?:\/\/)\S)*)?/gi, (url) => {
if (!isAllowedImg(url)) return url; // disallowed image URLs stay as plain text if (!isAllowedImg(url)) return url;
imgTokenUrls.push(url); imgTokenUrls.push(url);
return `\x04${imgTokenUrls.length - 1}\x05`; // numeric index placeholder return `\x04${imgTokenUrls.length - 1}\x05`;
}) })
.replace(/```[\s\S]*?```/g, '[code]') .replace(/```[\s\S]*?```/g, '[code]')
.replace(/`[^`]+`/g, match => match.slice(1, -1)) .replace(/`[^`]+`/g, match => match.slice(1, -1))
@@ -712,19 +963,26 @@ class Danmaku {
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
.replace(/^#{1,6}\s+/gm, '') .replace(/^#{1,6}\s+/gm, '')
.replace(/[*_]{1,3}([^*_]+)[*_]{1,3}/g, '$1') .replace(/[*_]{1,3}([^*_]+)[*_]{1,3}/g, '$1')
// Normalize \r\n → \n but keep line breaks for greentext
.replace(/\r\n?/g, '\n') .replace(/\r\n?/g, '\n')
// Collapse 3+ blank lines to 2
.replace(/\n{3,}/g, '\n\n') .replace(/\n{3,}/g, '\n\n')
.trim(); .trim();
// Restore emoji codes, then image URL tokens
return protected_ return protected_
.replace(/\x02(\d+)\x03/g, (_, i) => emojiTokens[+i] || '') .replace(/\x02(\d+)\x03/g, (_, i) => emojiTokens[+i] || '')
.replace(/\x04(\d+)\x05/g, (_, i) => imgTokenUrls[+i] ? `\x04${imgTokenUrls[+i]}\x05` : ''); .replace(/\x04(\d+)\x05/g, (_, i) => imgTokenUrls[+i] ? `\x04${imgTokenUrls[+i]}\x05` : '');
} }
} }
Danmaku.applyGlobalTuning = function(newCfg) {
if (newCfg) {
Object.assign(window.danmakuTuning, newCfg);
try {
localStorage.setItem('f0ck_danmaku_tuning', JSON.stringify(window.danmakuTuning));
} catch (e) {}
}
window.dispatchEvent(new CustomEvent('f0ck:danmaku_tuning_changed', { detail: window.danmakuTuning }));
};
window.Danmaku = Danmaku; window.Danmaku = Danmaku;
window.SyntheticClock = SyntheticClock; window.SyntheticClock = SyntheticClock;
+1131 -163
View File
File diff suppressed because it is too large Load Diff
+9 -2
View File
@@ -1229,11 +1229,18 @@
} }
return; return;
} }
// Sync count to server truth (handles race conditions) // Sync state and count to server truth (handles race conditions)
if (data.success && favBtn && data.favs) { if (data.success && favBtn) {
if (data.favorited !== undefined) {
favBtn.classList.toggle('faved', data.favorited);
const icon = favBtn.querySelector('i');
if (icon) icon.className = (data.favorited ? 'fa-solid' : 'fa-regular') + ' fa-heart';
}
if (data.favs) {
const countEl = favBtn.querySelector('.scroll-btn-count'); const countEl = favBtn.querySelector('.scroll-btn-count');
if (countEl) countEl.textContent = data.favs.length; if (countEl) countEl.textContent = data.favs.length;
} }
}
} catch { } catch {
// Rollback optimistic update on error // Rollback optimistic update on error
if (favBtn) { if (favBtn) {
+37
View File
@@ -1555,6 +1555,43 @@
}); });
} }
// Background & Onara Sliders Helper
const setupAudioTuningSlider = (sliderId, valId, tuningKey, defaultVal, formatFn, parserFn) => {
const slider = document.getElementById(sliderId);
const valSpan = document.getElementById(valId);
if (!slider) return;
let currentTuning = {};
try {
const raw = localStorage.getItem('f0ck_audio_tuning');
if (raw) currentTuning = JSON.parse(raw);
} catch (e) {}
const initialVal = currentTuning[tuningKey] !== undefined ? Number(currentTuning[tuningKey]) : defaultVal;
slider.value = initialVal;
if (valSpan) valSpan.textContent = formatFn(initialVal);
slider.addEventListener('input', () => {
const val = parserFn ? parserFn(slider.value) : parseFloat(slider.value);
if (valSpan) valSpan.textContent = formatFn(val);
if (window.audioVisualizerTuning) window.audioVisualizerTuning[tuningKey] = val;
if (window.applyBackgroundOpacitySettings) window.applyBackgroundOpacitySettings(window.audioVisualizerTuning);
try {
const raw = localStorage.getItem('f0ck_audio_tuning');
const t = raw ? JSON.parse(raw) : {};
t[tuningKey] = val;
localStorage.setItem('f0ck_audio_tuning', JSON.stringify(t));
} catch (e) {}
});
};
setupAudioTuningSlider('onara_bg_opacity_slider', 'onara_bg_opacity_val', 'onaraBgOpacity', 0.84, v => Math.round(v * 100) + '%');
setupAudioTuningSlider('onara_backdrop_blur_slider', 'onara_backdrop_blur_val', 'onaraBackdropBlur', 5, v => Math.round(v) + 'px');
setupAudioTuningSlider('onara_grid_dim_slider', 'onara_grid_dim_val', 'onaraGridDim', 0.15, v => Math.round(v * 100) + '%');
setupAudioTuningSlider('bg_canvas_opacity_slider', 'bg_canvas_opacity_val', 'bgCanvasOpacity', 1.00, v => Math.round(v * 100) + '%');
setupAudioTuningSlider('bg_canvas_blur_slider', 'bg_canvas_blur_val', 'bgCanvasBlur', 300, v => Math.round(v) + 'px');
setupAudioTuningSlider('bg_canvas_brightness_slider', 'bg_canvas_brightness_val', 'bgCanvasBrightness', 1.00, v => Math.round(v * 100) + '%');
// Quote Emojis Toggle // Quote Emojis Toggle
const quoteEmojisToggle = document.getElementById('quote_emojis_toggle'); const quoteEmojisToggle = document.getElementById('quote_emojis_toggle');
if (quoteEmojisToggle) { if (quoteEmojisToggle) {
+42 -11
View File
@@ -454,6 +454,17 @@ window.initUploadForm = (selector) => {
const statusDiv = form.querySelector('.upload-status'); const statusDiv = form.querySelector('.upload-status');
const thumbSection = form.querySelector('#custom-thumbnail-section'); const thumbSection = form.querySelector('#custom-thumbnail-section');
const thumbInput = form.querySelector('#upload-thumbnail-input'); const thumbInput = form.querySelector('#upload-thumbnail-input');
const redirectCheckbox = form.querySelector('input[name="redirect_to_item"], #upload-redirect-checkbox');
if (redirectCheckbox) {
const savedRedirect = localStorage.getItem('upload_redirect_to_item');
if (savedRedirect !== null) {
redirectCheckbox.checked = (savedRedirect === 'true' || savedRedirect === '1');
}
redirectCheckbox.addEventListener('change', () => {
localStorage.setItem('upload_redirect_to_item', redirectCheckbox.checked ? 'true' : 'false');
});
}
// Capture the SSR-translated initial button text so updateSubmitButton // Capture the SSR-translated initial button text so updateSubmitButton
// always uses the correct language regardless of window.f0ckI18n state. // always uses the correct language regardless of window.f0ckI18n state.
@@ -3061,7 +3072,14 @@ window.initUploadForm = (selector) => {
}); });
} }
const targetUrl = res.slug ? `/${res.slug}` : (res.itemid ? `/${res.itemid}` : '/'); const shouldRedirectToItem = redirectCheckbox
? redirectCheckbox.checked
: (localStorage.getItem('upload_redirect_to_item') !== 'false');
const targetUrl = shouldRedirectToItem
? (res.slug ? `/${res.slug}` : (res.itemid ? `/${res.itemid}` : '/'))
: '/';
if (typeof window.loadPageAjax === 'function') { if (typeof window.loadPageAjax === 'function') {
window.loadPageAjax(targetUrl, true, { bypassCache: true }); window.loadPageAjax(targetUrl, true, { bypassCache: true });
} else { } else {
@@ -3285,14 +3303,10 @@ window.initUploadForm = (selector) => {
} }
} }
// Seamless live injection without hard reload const shouldRedirectToItem = redirectCheckbox
if (window.location.pathname === '/upload') { ? redirectCheckbox.checked
if (typeof window.loadPageAjax === 'function') { : (localStorage.getItem('upload_redirect_to_item') !== 'false');
window.loadPageAjax('/', true, { bypassCache: true });
} else {
window.location.href = '/';
}
} else {
// Prepend items to live grid seamlessly // Prepend items to live grid seamlessly
if (window.NotificationSystemInstance && typeof window.NotificationSystemInstance.handleNewItem === 'function') { if (window.NotificationSystemInstance && typeof window.NotificationSystemInstance.handleNewItem === 'function') {
for (const up of uploadedResults) { for (const up of uploadedResults) {
@@ -3311,9 +3325,20 @@ window.initUploadForm = (selector) => {
} }
} }
} }
// Refresh grid & pagination seamlessly in background without reload
if (shouldRedirectToItem) {
const targetItem = lastData || (uploadedResults && uploadedResults[0]);
const targetUrl = targetItem ? (targetItem.slug ? `/${targetItem.slug}` : (targetItem.itemid ? `/${targetItem.itemid}` : '/')) : '/';
if (typeof window.loadPageAjax === 'function') { if (typeof window.loadPageAjax === 'function') {
window.loadPageAjax(window.location.pathname + window.location.search, true, { bypassCache: true, skipPush: true }); window.loadPageAjax(targetUrl, true, { bypassCache: true });
} else {
window.location.href = targetUrl;
}
} else {
if (typeof window.loadPageAjax === 'function') {
window.loadPageAjax('/', true, { bypassCache: true });
} else {
window.location.href = '/';
} }
} }
} }
@@ -3334,6 +3359,12 @@ window.initUploadForm = (selector) => {
reset: () => { reset: () => {
isUploading = false; isUploading = false;
form.reset(); form.reset();
if (redirectCheckbox) {
const savedRedirect = localStorage.getItem('upload_redirect_to_item');
if (savedRedirect !== null) {
redirectCheckbox.checked = (savedRedirect === 'true' || savedRedirect === '1');
}
}
tags = []; tags = [];
selectedFiles = []; selectedFiles = [];
if (albumChoiceContainer) albumChoiceContainer.style.display = 'none'; if (albumChoiceContainer) albumChoiceContainer.style.display = 'none';
+52 -10
View File
@@ -242,9 +242,9 @@
if (!ctx) return; if (!ctx) return;
const { postid } = ctx; const { postid } = ctx;
// Read state BEFORE the API call so we know which direction to toggle // Read state BEFORE the API call so we have a fallback
const favoBtn = document.querySelector("#a_favo"); const favoBtns = document.querySelectorAll("#a_favo");
const wasAlreadyFav = favoBtn && favoBtn.classList.contains('fa-solid'); const wasAlreadyFav = favoBtns.length > 0 && favoBtns[0].classList.contains('fa-solid');
try { try {
const res = await post('/api/v2/togglefav', { const res = await post('/api/v2/togglefav', {
@@ -254,22 +254,61 @@
if (window.invalidateItemCache) { if (window.invalidateItemCache) {
window.invalidateItemCache(postid); window.invalidateItemCache(postid);
} }
// New state is the logical opposite of what it was before the API call // Authoritative server state takes priority; fallback to inverting previous UI state
const isNowFav = !wasAlreadyFav; const isNowFav = (res.favorited !== undefined) ? !!res.favorited : !wasAlreadyFav;
if (favoBtn) { favoBtns.forEach(favoBtn => {
favoBtn.classList.toggle('fa-solid', isNowFav); favoBtn.classList.toggle('fa-solid', isNowFav);
favoBtn.classList.toggle('fa-regular', !isNowFav); favoBtn.classList.toggle('fa-regular', !isNowFav);
} });
// span#favs // span#favs
const favcontainer = document.querySelector('#favs'); const favcontainer = document.querySelector('#favs');
if (favcontainer) {
favcontainer.innerHTML = ""; favcontainer.innerHTML = "";
if (res.favs && res.favs.length > 0) { if (res.favs && res.favs.length > 0) {
const isAnonymized = !!(window.f0ckSession?.is_anonymized ?? (window.f0ckSession?.guest_anonymize && !window.f0ckSession?.logged_in) ?? (window.f0ckSession?.is_anon && window.f0ckSession?.anon_anonymize));
const fragment = document.createDocumentFragment();
res.favs.forEach(f => { res.favs.forEach(f => {
const isSelf = window.f0ckSession && (
(window.f0ckSession.id && f.user_id && Number(window.f0ckSession.id) === Number(f.user_id)) ||
(window.f0ckSession.user && f.user && window.f0ckSession.user.toLowerCase() === f.user.toLowerCase()) ||
(window.f0ckSession.login && f.login && window.f0ckSession.login.toLowerCase() === f.login.toLowerCase())
);
const isFavAnon = f.is_anon || f.user === 'anonymous' || (typeof f.user === 'string' && f.user.startsWith('anon_'));
if (f.hide_fav_badge && !isSelf) {
const a = document.createElement('a'); const a = document.createElement('a');
a.href = `/user/${f.user}`; a.className = 'ghost-fav';
a.setAttribute('tooltip', f.display_name || f.user); a.setAttribute('tooltip', '?');
a.setAttribute('flow', 'up');
a.style.cursor = 'default';
const img = document.createElement('img');
img.src = '/s/img/ghost_fav.svg';
img.style.height = "32px";
img.style.width = "32px";
a.appendChild(img);
fragment.appendChild(a);
} else if (isAnonymized || isFavAnon) {
const a = document.createElement('a');
a.className = 'ghost-fav';
a.setAttribute('tooltip', 'anonymous');
a.setAttribute('flow', 'up');
a.style.cursor = 'default';
const img = document.createElement('img');
img.src = '/a/default.png';
img.style.height = "32px";
img.style.width = "32px";
a.appendChild(img);
fragment.appendChild(a);
} else {
const a = document.createElement('a');
a.href = `/user/${(f.user || '').toLowerCase()}`;
a.setAttribute('tooltip', f.display_name || f.user || 'anonymous');
a.setAttribute('flow', 'up'); a.setAttribute('flow', 'up');
const img = document.createElement('img'); const img = document.createElement('img');
@@ -279,12 +318,15 @@
if (f.username_color) img.style.borderColor = f.username_color; if (f.username_color) img.style.borderColor = f.username_color;
a.appendChild(img); a.appendChild(img);
favcontainer.appendChild(a); fragment.appendChild(a);
}
}); });
favcontainer.appendChild(fragment);
favcontainer.hidden = false; favcontainer.hidden = false;
} else { } else {
favcontainer.hidden = true; favcontainer.hidden = true;
} }
}
window.flashMessage((window.f0ckI18n && (isNowFav ? window.f0ckI18n.fav_added : window.f0ckI18n.fav_removed)) || (isNowFav ? 'ADDED TO FAVORITES' : 'REMOVED FROM FAVORITES')); window.flashMessage((window.f0ckI18n && (isNowFav ? window.f0ckI18n.fav_added : window.f0ckI18n.fav_removed)) || (isNowFav ? 'ADDED TO FAVORITES' : 'REMOVED FROM FAVORITES'));
if (navigator.vibrate) navigator.vibrate(50); if (navigator.vibrate) navigator.vibrate(50);
+5 -1
View File
@@ -179,7 +179,11 @@ class v0ck {
} }
else else
return console.error("nope"); return console.error("nope");
return this.init(elem); const inst = this.init(elem);
if (elem && elem.tagName === 'AUDIO' && window.initVisualizer) {
window.initVisualizer(elem);
}
return inst;
} }
init(elem) { init(elem) {
+21 -13
View File
@@ -295,6 +295,26 @@ export default new class {
return false; return false;
}; };
userHasFavorited(session, favorites) {
if (!session || !Array.isArray(favorites) || favorites.length === 0) return false;
const sessId = session.id ? Number(session.id) : (session.user_id ? Number(session.user_id) : null);
const sessUser = (session.user || '').toLowerCase();
const sessLogin = (session.login || '').toLowerCase();
const sessAnonLogin = (session.anon_login || '').toLowerCase();
return favorites.some(f => {
const fUserId = f.user_id ? Number(f.user_id) : (f.id ? Number(f.id) : null);
if (sessId && fUserId && fUserId === sessId) return true;
const fUser = (f.user || '').toLowerCase();
const fLogin = (f.login || '').toLowerCase();
if (sessUser && sessUser !== 'anonymous' && (fUser === sessUser || fLogin === sessUser)) return true;
if (sessLogin && (fUser === sessLogin || fLogin === sessLogin)) return true;
if (sessAnonLogin && (fUser === sessAnonLogin || fLogin === sessAnonLogin)) return true;
return false;
});
}
async getTags(itemid, session = null, subf0ckId = null) { async getTags(itemid, session = null, subf0ckId = null) {
const isAnonymized = isAnonymizeSession(session); const isAnonymized = isAnonymizeSession(session);
const hasSession = !isAnonymized && !!(session && !session.is_anon && (typeof session === 'object' ? (session.id || session.user) : session)); const hasSession = !isAnonymized && !!(session && !session.is_anon && (typeof session === 'object' ? (session.id || session.user) : session));
@@ -331,19 +351,7 @@ export default new class {
where "album_items_tags_assign".album_item_id = ${+albumItemId} where "album_items_tags_assign".album_item_id = ${+albumItemId}
order by (case when "tags".id = 1 then 0 when "tags".id = 2 then 1 when "tags".normalized = 'nsfl' then 2 else 3 end) asc, "tags".id asc order by (case when "tags".id = 1 then 0 when "tags".id = 2 then 1 when "tags".normalized = 'nsfl' then 2 else 3 end) asc, "tags".id asc
`; `;
if (tags.length === 0) {
const isOrderZero = await db`SELECT order_index FROM album_items WHERE id = ${albumItemId} LIMIT 1`;
if (isOrderZero?.[0]?.order_index === 0) {
tags = await db`
select "tags".id, "tags".tag, "tags".normalized${hasSession ? db`, "user".user, uo.display_name` : db``}
from "tags_assign"
left join "tags" on "tags".id = "tags_assign".tag_id
${hasSession ? db`left join "user" on "user".id = "tags_assign".user_id left join user_options uo on uo.user_id = "user".id` : db``}
where "tags_assign".item_id = ${+itemid}
order by (case when "tags".id = 1 then 0 when "tags".id = 2 then 1 when "tags".normalized = 'nsfl' then 2 else 3 end) asc, "tags".id asc
`;
}
}
} else { } else {
tags = await db` tags = await db`
select "tags".id, "tags".tag, "tags".normalized${hasSession ? db`, "user".user, uo.display_name` : db``} select "tags".id, "tags".tag, "tags".normalized${hasSession ? db`, "user".user, uo.display_name` : db``}
+3 -1
View File
@@ -59,6 +59,7 @@
"comment_optional": "(optional)", "comment_optional": "(optional)",
"comment_placeholder": "Kommentar zum Upload hinzufügen...", "comment_placeholder": "Kommentar zum Upload hinzufügen...",
"select_file": "Datei auswählen", "select_file": "Datei auswählen",
"redirect_to_item": "Nach dem Upload zum Post weiterleiten",
"uploading": "Wird hochgeladen...", "uploading": "Wird hochgeladen...",
"pending_approval_patient": "Upload wartet auf Freigabe, bitte haben Sie etwas Geduld", "pending_approval_patient": "Upload wartet auf Freigabe, bitte haben Sie etwas Geduld",
"remove_file": "Datei entfernen", "remove_file": "Datei entfernen",
@@ -348,7 +349,8 @@
"label": "Fehler", "label": "Fehler",
"post_not_visible": "Dieser Beitrag ist derzeit leider nicht sichtbar.", "post_not_visible": "Dieser Beitrag ist derzeit leider nicht sichtbar.",
"filter_hint": "Dein aktueller Filter ist auf {mode} gesetzt.", "filter_hint": "Dein aktueller Filter ist auf {mode} gesetzt.",
"filter_hint_link": "Um diesen Inhalt zu sehen, ändere deinen Filter entsprechend." "filter_hint_link": "Um diesen Inhalt zu sehen, ändere deinen Filter entsprechend.",
"see_anyways": "Trotzdem ansehen"
}, },
"drop": { "drop": {
"drop_anywhere": "Überall ablegen zum Hochladen" "drop_anywhere": "Überall ablegen zum Hochladen"
+3 -1
View File
@@ -59,6 +59,7 @@
"comment_optional": "(optional)", "comment_optional": "(optional)",
"comment_placeholder": "Add a comment to your upload...", "comment_placeholder": "Add a comment to your upload...",
"select_file": "Select a file", "select_file": "Select a file",
"redirect_to_item": "Redirect to item after upload",
"uploading": "Uploading...", "uploading": "Uploading...",
"pending_approval_patient": "Upload awaits approval, please be patient", "pending_approval_patient": "Upload awaits approval, please be patient",
"remove_file": "Remove File", "remove_file": "Remove File",
@@ -348,7 +349,8 @@
"label": "Error", "label": "Error",
"post_not_visible": "Sorry, this post is currently not visible.", "post_not_visible": "Sorry, this post is currently not visible.",
"filter_hint": "Your current filter is set to {mode}.", "filter_hint": "Your current filter is set to {mode}.",
"filter_hint_link": "To view this content, change your filter accordingly." "filter_hint_link": "To view this content, change your filter accordingly.",
"see_anyways": "See anyways"
}, },
"drop": { "drop": {
"drop_anywhere": "Drop anywhere to upload" "drop_anywhere": "Drop anywhere to upload"
+3 -1
View File
@@ -59,6 +59,7 @@
"comment_optional": "(optioneel)", "comment_optional": "(optioneel)",
"comment_placeholder": "Voeg een opmerking toe aan je upload...", "comment_placeholder": "Voeg een opmerking toe aan je upload...",
"select_file": "Selecteer een bestand", "select_file": "Selecteer een bestand",
"redirect_to_item": "Na het uploaden naar het item doorsturen",
"uploading": "Uploaden...", "uploading": "Uploaden...",
"pending_approval_patient": "Upload wacht op goedkeuring, even geduld alstublieft", "pending_approval_patient": "Upload wacht op goedkeuring, even geduld alstublieft",
"remove_file": "Bestand Verwijderen", "remove_file": "Bestand Verwijderen",
@@ -346,7 +347,8 @@
"label": "Fout", "label": "Fout",
"post_not_visible": "Sorry, deze post is momenteel niet zichtbaar.", "post_not_visible": "Sorry, deze post is momenteel niet zichtbaar.",
"filter_hint": "Je huidige filter is ingesteld op {mode}.", "filter_hint": "Je huidige filter is ingesteld op {mode}.",
"filter_hint_link": "Om deze inhoud te bekijken, pas je filter aan." "filter_hint_link": "Om deze inhoud te bekijken, pas je filter aan.",
"see_anyways": "Toch bekijken"
}, },
"drop": { "drop": {
"drop_anywhere": "Overal slepen om te uploaden" "drop_anywhere": "Overal slepen om te uploaden"
+3 -1
View File
@@ -59,6 +59,7 @@
"comment_optional": "(optional)", "comment_optional": "(optional)",
"comment_placeholder": "Fügen Sie Ihrer Aufladierung doch einen Kommentar hinzu...", "comment_placeholder": "Fügen Sie Ihrer Aufladierung doch einen Kommentar hinzu...",
"select_file": "Datei auswählen", "select_file": "Datei auswählen",
"redirect_to_item": "Nach Pfostieren zum Pfosten weiterleiten",
"uploading": "Wird aufladiert...", "uploading": "Wird aufladiert...",
"pending_approval_patient": "Die Ladung harrt der Absegnung, bitte haben Sie Geduld", "pending_approval_patient": "Die Ladung harrt der Absegnung, bitte haben Sie Geduld",
"remove_file": "Datei entfernen", "remove_file": "Datei entfernen",
@@ -344,7 +345,8 @@
"label": "Fehler", "label": "Fehler",
"post_not_visible": "Bedauerlicher Weise ist dieser Pfosten derzeit nicht sichtbar.", "post_not_visible": "Bedauerlicher Weise ist dieser Pfosten derzeit nicht sichtbar.",
"filter_hint": "Ihr aktueller Filter ist auf {mode} eingestellt.", "filter_hint": "Ihr aktueller Filter ist auf {mode} eingestellt.",
"filter_hint_link": "Um diesen Inhalt zu betrachten, stellen Sie Ihren Filter entsprechend um." "filter_hint_link": "Um diesen Inhalt zu betrachten, stellen Sie Ihren Filter entsprechend um.",
"see_anyways": "Dennoch betrachten"
}, },
"drop": { "drop": {
"drop_anywhere": "Überall ablegen zum Aufladieren" "drop_anywhere": "Überall ablegen zum Aufladieren"
+360 -96
View File
@@ -8,9 +8,30 @@ import fs from "fs";
import path from "path"; import path from "path";
import url from "url"; import url from "url";
const getGlobalfilter = () => { const getGlobalfilter = (session) => {
if (!cfg.nsfp?.length) return null; if (!cfg.nsfp?.length) return null;
const filteredTags = cfg.websrv.public_nsfw ? cfg.nsfp.filter(id => id !== 2) : cfg.nsfp; let filteredTags = [...cfg.nsfp];
// For anonymous users, respect their allowed_modes permissions
if (session && isAnonSession(session)) {
const allowedModes = getAnonAllowedModes();
if (allowedModes.includes('nsfw')) {
filteredTags = filteredTags.filter(id => id !== 2);
}
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
if (allowedModes.includes('nsfl')) {
filteredTags = filteredTags.filter(id => id !== nsflId);
}
} else if (!session) {
// Guest (not logged in): use public_nsfw setting
if (cfg.websrv.public_nsfw) {
filteredTags = filteredTags.filter(id => id !== 2);
}
} else {
// Logged-in member: use public_nsfw setting
if (cfg.websrv.public_nsfw) {
filteredTags = filteredTags.filter(id => id !== 2);
}
}
return filteredTags.length ? filteredTags.map(n => `tag_id = ${n}`).join(" or ") : null; return filteredTags.length ? filteredTags.map(n => `tag_id = ${n}`).join(" or ") : null;
}; };
@@ -175,7 +196,7 @@ function buildCountCacheKey({ modequery, tag, user, hall, mime, fav, session, ex
hall ?? '', hall ?? '',
mime ?? '', mime ?? '',
fav ? 1 : 0, fav ? 1 : 0,
session ? 1 : 0, // guests get globalfilter applied; members don't (session && !isAnonSession(session)) ? 1 : 0, // guests and anon users get globalfilter applied; members don't
excludedTags.slice().sort().join(','), excludedTags.slice().sort().join(','),
newerThan ?? '', newerThan ?? '',
minXd, minXd,
@@ -575,7 +596,7 @@ const f0cklib = {
${mimeSQL} ${mimeSQL}
${hallFilter} ${hallFilter}
${userHallFilter} ${userHallFilter}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : 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``} ${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``} ${newerThan ? db`and items.id > ${newerThan}` : db``}
${xdFilter} ${xdFilter}
@@ -601,7 +622,7 @@ const f0cklib = {
${mimeSQL} ${mimeSQL}
${hallFilter} ${hallFilter}
${userHallFilter} ${userHallFilter}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : 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``} ${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``} ${newerThan ? db`and items.id > ${newerThan}` : db``}
${xdFilter} ${xdFilter}
@@ -685,6 +706,28 @@ const f0cklib = {
visibilityFilter visibilityFilter
} = filters; } = filters;
const effMode = Number(mode ?? 0);
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null;
let safeRatingsArr = ratingsArr;
const isGuest = !session || !session.user;
if (isGuest) {
safeRatingsArr = ['sfw'];
} else if (isAnonSession(session)) {
const allowedModes = getAnonAllowedModes();
const canFilter = canAnonDo('filter');
if (!canFilter) {
safeRatingsArr = null;
} else if (safeRatingsArr) {
safeRatingsArr = safeRatingsArr.filter(r => allowedModes.includes(r));
if (safeRatingsArr.length === 0) {
safeRatingsArr = (allowedModes.length === 1 && !allowedModes.includes('all'))
? [allowedModes[0]]
: (allowedModes.length < 5 ? [...allowedModes] : null);
}
}
}
const actPage = +(page ?? 1); const actPage = +(page ?? 1);
const eps = limit ?? cfg.websrv.eps; const eps = limit ?? cfg.websrv.eps;
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 }; 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 };
@@ -709,7 +752,7 @@ const f0cklib = {
${mimeSQL} ${mimeSQL}
${hallFilter} ${hallFilter}
${userHallFilter} ${userHallFilter}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : 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``} ${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``} ${newerThan ? db`and items.id > ${newerThan}` : db``}
${xdFilter} ${xdFilter}
@@ -753,7 +796,7 @@ const f0cklib = {
${mimeSQL} ${mimeSQL}
${hallFilter} ${hallFilter}
${userHallFilter} ${userHallFilter}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : 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``} ${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``} ${newerThan ? db`and items.id > ${newerThan}` : db``}
${xdFilter} ${xdFilter}
@@ -821,12 +864,11 @@ const f0cklib = {
row.is_audio = !!(row.mime && row.mime.startsWith('audio/')); row.is_audio = !!(row.mime && row.mime.startsWith('audio/'));
} }
if (tag && !isTitleSearch && rows.some(r => r.is_album)) { if (rows.some(r => r.is_album)) {
const albumIds = rows.filter(r => r.is_album).map(r => r.id); const albumIds = rows.filter(r => r.is_album).map(r => r.id);
const terms = tag.split(',').map(t => t.trim()).filter(Boolean); if (albumIds.length > 0) {
if (terms.length > 0 && albumIds.length > 0) {
try { try {
const matchingSubs = await db` const subItemsRows = await db`
SELECT SELECT
ai.item_id, ai.item_id,
ai.id as subf0ck_id, ai.id as subf0ck_id,
@@ -835,34 +877,111 @@ const f0cklib = {
ai.mime as subf0ck_mime, ai.mime as subf0ck_mime,
ai.order_index ai.order_index
FROM album_items ai FROM album_items ai
JOIN album_items_tags_assign aita ON aita.album_item_id = ai.id
JOIN tags t ON t.id = aita.tag_id
${tagger ? db`JOIN "user" u ON u.id = aita.user_id` : db``}
WHERE ai.item_id = ANY(${albumIds}::int[]) WHERE ai.item_id = ANY(${albumIds}::int[])
${tagger ? db`AND u.user ILIKE ${tagger}` : db``}
AND (${isStrict
? db`t.normalized = ANY(ARRAY(SELECT slugify(x) FROM unnest(${terms}::text[]) AS x))`
: db`${terms.map(term => db`t.normalized LIKE '%' || slugify(${term}) || '%'`).reduce((a, b) => db`${a} OR ${b}`)}`
})
ORDER BY ai.item_id, ai.order_index ASC ORDER BY ai.item_id, ai.order_index ASC
`; `;
const matchMap = new Map(); const subIds = subItemsRows.map(s => s.subf0ck_id);
for (const ms of matchingSubs) { const subTagsRows = subIds.length > 0 ? await db`
if (!matchMap.has(ms.item_id)) { SELECT aita.album_item_id, t.id, t.tag, t.normalized
matchMap.set(ms.item_id, { FROM album_items_tags_assign aita
first: ms, JOIN tags t ON t.id = aita.tag_id
matchingIds: new Set([ms.subf0ck_id]) WHERE aita.album_item_id = ANY(${subIds}::int[])
}); `.catch(() => []) : [];
} else {
matchMap.get(ms.item_id).matchingIds.add(ms.subf0ck_id); const tagsBySubId = new Map();
for (const st of subTagsRows) {
if (!tagsBySubId.has(st.album_item_id)) tagsBySubId.set(st.album_item_id, []);
tagsBySubId.get(st.album_item_id).push(st);
} }
const subsByItemId = new Map();
for (const si of subItemsRows) {
if (!subsByItemId.has(si.item_id)) subsByItemId.set(si.item_id, []);
subsByItemId.get(si.item_id).push(si);
} }
for (const row of rows) { for (const row of rows) {
if (matchMap.has(row.id)) { if (!row.is_album || !subsByItemId.has(row.id)) continue;
const info = matchMap.get(row.id); const subList = subsByItemId.get(row.id);
const ms = info.first; const isOwnerOrAdmin = (session && session.user && row.username && session.user.toLowerCase() === row.username.toLowerCase()) || (session && (session.admin || session.is_moderator));
const isSubVisible = (subTags) => {
if (isOwnerOrAdmin) return true;
const subIsNsfl = cfg.enable_nsfl && subTags.some(t => t.id == nsflId || t.normalized === 'nsfl');
const subIsNsfw = subTags.some(t => t.id == 2);
const subIsSfw = subTags.some(t => t.id == 1);
const subIsUntagged = !subIsSfw && !subIsNsfw && !subIsNsfl;
if (excludedTags && excludedTags.length > 0 && subTags.length > 0) {
if (subTags.some(t => excludedTags.includes(t.normalized) || excludedTags.includes(lib.slugify(t.tag)))) {
return false;
}
}
if (!session || !session.user) {
if (subIsNsfl) return false;
if (subIsNsfw && !cfg.websrv.public_nsfw) return false;
if (subIsUntagged && !cfg.websrv.public_untagged) return false;
if (effMode === 0 && (subIsNsfw || subIsNsfl || (subIsUntagged && !cfg.websrv.public_untagged))) return false;
if (effMode === 1 && !subIsNsfw) return false;
if (effMode === 2 && (!subIsUntagged || !cfg.websrv.public_untagged)) return false;
return true;
}
if (isAnonSession(session)) {
const allowedModes = getAnonAllowedModes();
if (subIsNsfl && !allowedModes.includes('nsfl')) return false;
if (subIsNsfw && !allowedModes.includes('nsfw')) return false;
if (subIsUntagged && !allowedModes.includes('untagged')) return false;
if (subIsSfw && !allowedModes.includes('sfw')) return false;
if (safeRatingsArr && safeRatingsArr.length > 0) {
const subRatingName = subIsNsfl ? 'nsfl' : (subIsNsfw ? 'nsfw' : (subIsSfw ? 'sfw' : 'untagged'));
if (!safeRatingsArr.includes(subRatingName)) return false;
} else if (effMode !== 3) {
if (effMode === 0 && (subIsNsfw || subIsNsfl || (subIsUntagged && !allowedModes.includes('untagged')))) return false;
if (effMode === 1 && !subIsNsfw) return false;
if (effMode === 2 && (!subIsUntagged || !allowedModes.includes('untagged'))) return false;
if (effMode === 4 && !subIsNsfl) return false;
}
return true;
}
if (safeRatingsArr && safeRatingsArr.length > 0) {
const subRatingName = subIsNsfl ? 'nsfl' : (subIsNsfw ? 'nsfw' : (subIsSfw ? 'sfw' : 'untagged'));
if (!safeRatingsArr.includes(subRatingName)) return false;
} else if (effMode !== 3) {
if (effMode === 0 && (subIsNsfw || subIsNsfl)) return false;
if (effMode === 1 && !subIsNsfw) return false;
if (effMode === 2 && !subIsUntagged) return false;
if (effMode === 4 && !subIsNsfl) return false;
}
return true;
};
let visibleSubs = subList.filter((si) => {
let st = tagsBySubId.get(si.subf0ck_id) || [];
return isSubVisible(st);
});
if (tag && !isTitleSearch) {
const terms = tag.split(',').map(t => t.trim()).filter(Boolean);
if (terms.length > 0) {
const tagMatchingSubs = visibleSubs.filter((si) => {
let st = tagsBySubId.get(si.subf0ck_id) || [];
if (isStrict) {
return strictParams.every(sp => st.some(t => t.normalized === sp));
}
return terms.some(term => {
const slugTerm = lib.slugify(term);
return st.some(t => t.normalized && t.normalized.includes(slugTerm));
});
});
if (tagMatchingSubs.length > 0) {
const ms = tagMatchingSubs[0];
row.target_subf0ck_slug = ms.subf0ck_slug || ms.subf0ck_id; row.target_subf0ck_slug = ms.subf0ck_slug || ms.subf0ck_id;
if (ms.subf0ck_dest) { if (ms.subf0ck_dest) {
const subBase = ms.subf0ck_dest.replace(/\.[^.]+$/, ''); const subBase = ms.subf0ck_dest.replace(/\.[^.]+$/, '');
@@ -875,15 +994,18 @@ const f0cklib = {
row.matching_sub_mime = ms.subf0ck_mime; row.matching_sub_mime = ms.subf0ck_mime;
row.mime = ms.subf0ck_mime; row.mime = ms.subf0ck_mime;
} }
const mCount = info.matchingIds.size; visibleSubs = tagMatchingSubs;
row.album_count = mCount; }
if (mCount <= 1) { }
}
row.album_count = visibleSubs.length;
if (visibleSubs.length <= 1) {
row.is_album = false; row.is_album = false;
} }
} }
}
} catch (err) { } catch (err) {
console.warn('[FEED] Error resolving matching subf0cks for tag search:', err.message); console.warn('[FEED] Error calculating visible album count for feed:', err.message);
} }
} }
} }
@@ -950,7 +1072,7 @@ const f0cklib = {
view_mode: fav ? 'favs' : 'uploads' view_mode: fav ? 'favs' : 'uploads'
}; };
}, },
getf0ck: async ({ user: rawUser, tag: rawTag, hall: rawHall, mime: rawMime, itemid: rawItemid, mode, ratings, session, strict, exclude, user_id, is_admin, fav, random, userHall: rawUserHall, userHallOwner: rawUserHallOwner, lang, ids, subf0ck } = {}) => { getf0ck: async ({ user: rawUser, tag: rawTag, hall: rawHall, mime: rawMime, itemid: rawItemid, mode, ratings, session, strict, exclude, user_id, is_admin, fav, random, userHall: rawUserHall, userHallOwner: rawUserHallOwner, lang, ids, subf0ck, bypass_filter } = {}) => {
if (fav && rawUser) { if (fav && rawUser) {
const { isPrivate, isAllowed } = await checkFavoritesAccess(rawUser, { session, user_id, is_admin }); const { isPrivate, isAllowed } = await checkFavoritesAccess(rawUser, { session, user_id, is_admin });
if (isPrivate && !isAllowed) { if (isPrivate && !isAllowed) {
@@ -1029,6 +1151,21 @@ const f0cklib = {
const effMode = Number(mode ?? 0); const effMode = Number(mode ?? 0);
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3; const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null;
let safeRatingsArr = ratingsArr;
if (!session || !session.user) {
safeRatingsArr = ['sfw'];
} else if (isAnonSession(session)) {
const allowedModes = getAnonAllowedModes();
if (safeRatingsArr) {
safeRatingsArr = safeRatingsArr.filter(r => allowedModes.includes(r));
if (safeRatingsArr.length === 0) {
safeRatingsArr = (allowedModes.length === 1 && !allowedModes.includes('all'))
? [allowedModes[0]]
: (allowedModes.length < 5 ? [...allowedModes] : null);
}
}
}
const itemModeQuery = computeBaseMode(mode, ratings, session); const itemModeQuery = computeBaseMode(mode, ratings, session);
let tagFilter = db``; let tagFilter = db``;
@@ -1089,7 +1226,7 @@ const f0cklib = {
${!fav && user ? db`and items.username ilike ${user}` : db``} ${!fav && user ? db`and items.username ilike ${user}` : db``}
${idsFilter} ${idsFilter}
${mimeSQL} ${mimeSQL}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : 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``} ${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = any(${excludedTags}::int[]))` : db``}
`; `;
}; };
@@ -1180,16 +1317,17 @@ const f0cklib = {
last_viewed = now() last_viewed = now()
`.catch(e => console.error('Failed to track view:', e)); `.catch(e => console.error('Failed to track view:', e));
} }
// Guest rating restriction check for public items (unlisted items requested by direct link/slug bypass guest rating blocks) // Public visitor / guest rating restriction check for public items (unlisted items requested by direct link/slug bypass guest rating blocks)
if (!session && (actitem.visibility || 0) === 0) { const isPublicVisitor = !session || !session.user || isAnonSession(session);
if (isPublicVisitor && !isOwnerOrAdmin && (actitem.visibility || 0) === 0) {
let blocked = false; let blocked = false;
if (getGlobalfilter()) { if (getGlobalfilter(session)) {
const filteredItem = await db` const filteredItem = await db`
select 1 from tags_assign where item_id = ${itemid} and (${db.unsafe(getGlobalfilter())}) limit 1 select 1 from tags_assign where item_id = ${itemid} and (${db.unsafe(getGlobalfilter(session))}) limit 1
`; `;
if (filteredItem.length > 0) blocked = true; if (filteredItem.length > 0) blocked = true;
} }
if (!blocked && !cfg.websrv.public_untagged) { if (!blocked && !session && !cfg.websrv.public_untagged) {
const ratingTag = await db` const ratingTag = await db`
select 1 from tags_assign where item_id = ${itemid} and tag_id in (1, 2, ${nsflId}) limit 1 select 1 from tags_assign where item_id = ${itemid} and tag_id in (1, 2, ${nsflId}) limit 1
`; `;
@@ -1217,7 +1355,7 @@ const f0cklib = {
// Determine the effective mode for optimization check (similar to Random) // Determine the effective mode for optimization check (similar to Random)
const nsfl_id = cfg.nsfl_tag_id || 3; const nsfl_id = cfg.nsfl_tag_id || 3;
const useTagsDriver = !!session && (effMode === 1 || effMode === 4) && !fav && !tag && !user && !hall && (!cleanIds || cleanIds.length === 0); const useTagsDriver = !!session && !isAnonSession(session) && (effMode === 1 || effMode === 4) && !fav && !tag && !user && !hall && (!cleanIds || cleanIds.length === 0);
const baseQuery = (whereClause, orderBy, limit = 1) => { const baseQuery = (whereClause, orderBy, limit = 1) => {
return db` return db`
@@ -1244,7 +1382,7 @@ const f0cklib = {
const useTagIdOpt = !mimeParts.includes('audio'); const useTagIdOpt = !mimeParts.includes('audio');
const nsfpIds = cfg.nsfp || []; const nsfpIds = cfg.nsfp || [];
const checkFilter = !session && nsfpIds.length > 0; const checkFilter = (!session || isAnonSession(session)) && nsfpIds.length > 0;
const query = db` const query = db`
SELECT ta.item_id as id, items.slug SELECT ta.item_id as id, items.slug
@@ -1305,13 +1443,27 @@ const f0cklib = {
link.suffix = ''; link.suffix = '';
} }
const favorites = await db` const favorites = await db`
select "user".user, "user_options".avatar, "user_options".avatar_file, "user_options".username_color, "user_options".display_name, "user_options".hide_fav_badge select "favorites".user_id, "user".user, "user".login, "user_options".avatar, "user_options".avatar_file, "user_options".username_color, "user_options".display_name, "user_options".hide_fav_badge, "anon_identities".fingerprint as anon_fingerprint
from "favorites" from "favorites"
left join "user" on "user".id = "favorites".user_id left join "user" on "user".id = "favorites".user_id
left join "user_options" on "user_options".user_id = "favorites".user_id left join "user_options" on "user_options".user_id = "favorites".user_id
left join "anon_identities" on "anon_identities".user_id = "favorites".user_id
where "favorites".item_id = ${itemid} where "favorites".item_id = ${itemid}
`; `;
for (const f of favorites) {
if (f.anon_fingerprint || f.user === 'anonymous' || (typeof f.user === 'string' && f.user.startsWith('anon_'))) {
f.is_anon = true;
f.user = 'anonymous';
f.login = 'anonymous';
f.display_name = 'Anonymous';
f.avatar = null;
f.avatar_file = null;
f.username_color = null;
f.hide_fav_badge = true;
}
}
// Detect reposts: items uploaded with bypass_duplicate_check have checksum = `{hash}_bypass_{ts}` // 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. // Find all items (including this one) that share the same base checksum.
let repostItems = []; let repostItems = [];
@@ -1355,27 +1507,21 @@ const f0cklib = {
} }
} }
let hasCoverart = false;
// Efficient coverart fallback with on-demand extraction if (actitem.mime && actitem.mime.startsWith('audio/')) {
let hasCoverart = actitem.has_coverart;
if (!hasCoverart && actitem.mime?.startsWith('audio/')) {
const caPath = path.join(cfg.paths.ca, `${actitem.id}.webp`);
try { try {
const caPath = path.join(cfg.paths.ca, `${actitem.id}.webp`);
if (fs.existsSync(caPath) && fs.statSync(caPath).size > 0) { if (fs.existsSync(caPath) && fs.statSync(caPath).size > 0) {
hasCoverart = true; hasCoverart = true;
db`UPDATE items SET has_coverart = TRUE WHERE id = ${actitem.id}`.catch(() => {});
} else { } else {
// Attempt extraction directly from audio file if embedded // On-demand cover art extraction fallback
const sourcePath = path.join(cfg.paths.b, actitem.dest); const audioFile = path.join(cfg.paths.b, actitem.dest);
if (fs.existsSync(sourcePath)) { if (fs.existsSync(audioFile)) {
await queue.spawn('ffmpeg', ['-y', '-i', sourcePath, '-an', '-vcodec', 'webp', '-frames:v', '1', caPath], { quiet: true }).catch(() => {}); await queue.spawn('ffmpeg', ['-y', '-i', audioFile, '-an', '-vcodec', 'webp', '-frames:v', '1', caPath], { quiet: true });
if (fs.existsSync(caPath) && fs.statSync(caPath).size > 0) { if (fs.existsSync(caPath) && fs.statSync(caPath).size > 0) {
hasCoverart = true; hasCoverart = true;
db`UPDATE items SET has_coverart = TRUE WHERE id = ${actitem.id}`.catch(() => {});
const tPath = path.join(cfg.paths.t, `${actitem.id}.webp`); const tPath = path.join(cfg.paths.t, `${actitem.id}.webp`);
if (!fs.existsSync(tPath) || fs.statSync(tPath).size === 0) { await queue.spawn('magick', [caPath + '[0]', '-resize', '256x256^', '-gravity', 'center', '-crop', '256x256+0+0', '+repage', tPath], { quiet: true });
await queue.spawn('magick', [caPath + '[0]', '-resize', '256x256^', '-gravity', 'center', '-crop', '256x256+0+0', '+repage', tPath], { quiet: true }).catch(() => {});
}
} else { } else {
try { fs.unlinkSync(caPath); } catch (_) {} try { fs.unlinkSync(caPath); } catch (_) {}
} }
@@ -1416,11 +1562,8 @@ const f0cklib = {
if (tag && !isTitleSearch) { if (tag && !isTitleSearch) {
const terms = tag.split(',').map(t => t.trim()).filter(Boolean); const terms = tag.split(',').map(t => t.trim()).filter(Boolean);
if (terms.length > 0 && tagsBySubId.size > 0) { if (terms.length > 0 && tagsBySubId.size > 0) {
const matching = albumRows.filter((r, idx) => { const matching = albumRows.filter((r) => {
let st = tagsBySubId.get(r.id) || []; let st = tagsBySubId.get(r.id) || [];
if (st.length === 0 && (r.order_index === 0 || idx === 0)) {
st = tags;
}
if (isStrict) { if (isStrict) {
return strictParams.every(sp => st.some(t => t.normalized === sp)); return strictParams.every(sp => st.some(t => t.normalized === sp));
} }
@@ -1435,6 +1578,88 @@ const f0cklib = {
} }
} }
const isSubVisible = (subTags) => {
if (bypass_filter) return true;
const subIsNsfl = cfg.enable_nsfl && subTags.some(t => t.id == nsfl_id || t.normalized === 'nsfl');
const subIsNsfw = subTags.some(t => t.id == 2);
const subIsSfw = subTags.some(t => t.id == 1);
const subIsUntagged = !subIsSfw && !subIsNsfw && !subIsNsfl;
// Excluded tags check
if (excludedTags && excludedTags.length > 0 && subTags.length > 0) {
if (subTags.some(t => excludedTags.includes(t.normalized) || excludedTags.includes(lib.slugify(t.tag)))) {
return false;
}
}
// Guest check
if (!session || !session.user) {
if (subIsNsfl) return false;
if (subIsNsfw && !cfg.websrv.public_nsfw) return false;
if (subIsUntagged && !cfg.websrv.public_untagged) return false;
if (effMode === 0 && (subIsNsfw || subIsNsfl || (subIsUntagged && !cfg.websrv.public_untagged))) return false;
if (effMode === 1 && !subIsNsfw) return false;
if (effMode === 2 && (!subIsUntagged || !cfg.websrv.public_untagged)) return false;
return true;
}
// Anon session check
if (isAnonSession(session)) {
const allowedModes = getAnonAllowedModes();
if (subIsNsfl && !allowedModes.includes('nsfl')) return false;
if (subIsNsfw && !allowedModes.includes('nsfw')) return false;
if (subIsUntagged && !allowedModes.includes('untagged')) return false;
if (subIsSfw && !allowedModes.includes('sfw')) return false;
if (safeRatingsArr && safeRatingsArr.length > 0) {
const subRatingName = subIsNsfl ? 'nsfl' : (subIsNsfw ? 'nsfw' : (subIsSfw ? 'sfw' : 'untagged'));
if (!safeRatingsArr.includes(subRatingName)) return false;
} else if (effMode !== 3) {
if (effMode === 0 && (subIsNsfw || subIsNsfl || (subIsUntagged && !allowedModes.includes('untagged')))) return false;
if (effMode === 1 && !subIsNsfw) return false;
if (effMode === 2 && (!subIsUntagged || !allowedModes.includes('untagged'))) return false;
if (effMode === 4 && !subIsNsfl) return false;
}
return true;
}
// Logged-in member check
if (safeRatingsArr && safeRatingsArr.length > 0) {
const subRatingName = subIsNsfl ? 'nsfl' : (subIsNsfw ? 'nsfw' : (subIsSfw ? 'sfw' : 'untagged'));
if (!safeRatingsArr.includes(subRatingName)) return false;
} else if (effMode !== 3) {
if (effMode === 0 && (subIsNsfw || subIsNsfl)) return false;
if (effMode === 1 && !subIsNsfw) return false;
if (effMode === 2 && !subIsUntagged) return false;
if (effMode === 4 && !subIsNsfl) return false;
}
return true;
};
albumRows = albumRows.filter((r) => {
let subTags = tagsBySubId.get(r.id) || [];
return isSubVisible(subTags);
});
if (albumRows.length === 0) {
const hallSlug = hall && typeof hall === 'object' ? hall.slug : hall;
return {
success: false,
message: "Sorry, this post is currently not visible.",
item: {
id: itemid,
slug: actitem.slug || null,
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`
}
};
}
album = await Promise.all(albumRows.map(async (r, idx) => { album = await Promise.all(albumRows.map(async (r, idx) => {
const order = idx; const order = idx;
const subSlug = r.slug || r.id; const subSlug = r.slug || r.id;
@@ -1503,9 +1728,6 @@ const f0cklib = {
} }
let subTags = tagsBySubId.get(r.id) || []; let subTags = tagsBySubId.get(r.id) || [];
if (subTags.length === 0 && (r.order_index === 0 || idx === 0)) {
subTags = tags;
}
return { return {
id: r.id, id: r.id,
@@ -1537,6 +1759,21 @@ const f0cklib = {
const found = album.findIndex(s => String(s.slug || '') === String(requestedSubf0ckSlug) || String(s.subf0ck_id || '') === String(requestedSubf0ckSlug) || String(s.id) === String(requestedSubf0ckSlug)); const found = album.findIndex(s => String(s.slug || '') === String(requestedSubf0ckSlug) || String(s.subf0ck_id || '') === String(requestedSubf0ckSlug) || String(s.id) === String(requestedSubf0ckSlug));
if (found !== -1) { if (found !== -1) {
reqIdx = found; reqIdx = found;
} else {
const hallSlug = hall && typeof hall === 'object' ? hall.slug : hall;
return {
success: false,
message: "Sorry, this post is currently not visible.",
item: {
id: itemid,
slug: actitem.slug || null,
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`
}
};
} }
} }
@@ -1560,12 +1797,10 @@ const f0cklib = {
} }
if (targetSub.tags && targetSub.tags.length > 0) { if (targetSub.tags && targetSub.tags.length > 0) {
effectiveItemTags = targetSub.tags; effectiveItemTags = targetSub.tags;
if (!effectiveItemTags.some(t => t.id === 1 || t.id === 2 || t.normalized === 'nsfl')) { } else if (reqIdx === 0) {
const ratingTag = tags.find(t => t.id === 1 || t.id === 2 || t.normalized === 'nsfl'); effectiveItemTags = tags;
if (ratingTag) { } else {
effectiveItemTags = [ratingTag, ...effectiveItemTags]; effectiveItemTags = [];
}
}
} }
} }
} }
@@ -1577,7 +1812,7 @@ const f0cklib = {
const duration = Date.now() - startTime; const duration = Date.now() - startTime;
console.log(`[${new Date().toISOString()}] [GETF0CK_OPT] Fetch complete in ${duration}ms`); console.log(`[${new Date().toISOString()}] [GETF0CK_OPT] Fetch complete in ${duration}ms`);
const isNsfl = cfg.enable_nsfl && effectiveItemTags.some(t => t.id == nsfl_id); const isNsfl = cfg.enable_nsfl && effectiveItemTags.some(t => t.id == nsfl_id || t.normalized === 'nsfl');
const isNsfw = effectiveItemTags.some(t => t.id == 2); const isNsfw = effectiveItemTags.some(t => t.id == 2);
const isSfw = effectiveItemTags.some(t => t.id == 1); const isSfw = effectiveItemTags.some(t => t.id == 1);
const isTagged = effectiveItemTags.length > 0; const isTagged = effectiveItemTags.length > 0;
@@ -1604,20 +1839,15 @@ const f0cklib = {
} }
}; };
} }
} } else if (isAnonSession(session) && !isOwnerOrAdmin && (actitem.visibility || 0) === 0) {
const allowedModes = getAnonAllowedModes();
let anonBlocked = false;
if (isNsfw && !allowedModes.includes('nsfw')) anonBlocked = true;
else if (isNsfl && !allowedModes.includes('nsfl')) anonBlocked = true;
else if (isUntagged && !allowedModes.includes('untagged')) anonBlocked = true;
else if (isSfw && !allowedModes.includes('sfw')) anonBlocked = true;
// Mode-mismatch visibility check: if (anonBlocked) {
// Only enforce for members (session users) with an explicit mode preference.
// Mode 0=sfw, 1=nsfw, 2=untagged, 3=all
const userMode = Number(mode ?? 0);
if (userMode !== 3) {
let modeBlocked = false;
if (userMode === 0 && (isNsfw || isNsfl || (!session && isUntagged && !cfg.websrv.public_untagged))) modeBlocked = true; // SFW mode, item is NSFW or NSFL
else if (userMode === 1 && !isNsfw) modeBlocked = true; // NSFW mode, item is not NSFW
else if (userMode === 4 && (!cfg.enable_nsfl || !isNsfl)) modeBlocked = true; // NSFL mode, item is not NSFL
else if (userMode === 2 && (isTagged || (!session && !cfg.websrv.public_untagged))) modeBlocked = true; // Untagged mode, item has tags
if (modeBlocked && !isOwnerOrAdmin && actitem.visibility !== 1) {
const hallSlug = hall && typeof hall === 'object' ? hall.slug : hall; const hallSlug = hall && typeof hall === 'object' ? hall.slug : hall;
return { return {
success: false, success: false,
@@ -1634,6 +1864,40 @@ const f0cklib = {
} }
} }
// Mode-mismatch visibility check:
// Mode 0=sfw, 1=nsfw, 2=untagged, 3=all
const userMode = Number(mode ?? 0);
if (!bypass_filter) {
let modeBlocked = false;
const untaggedDisallowed = (!session && !cfg.websrv.public_untagged) || (isAnonSession(session) && !getAnonAllowedModes().includes('untagged'));
if (safeRatingsArr && safeRatingsArr.length > 0) {
const itemRatingName = isNsfl ? 'nsfl' : (isNsfw ? 'nsfw' : (isSfw ? 'sfw' : 'untagged'));
if (!safeRatingsArr.includes(itemRatingName)) modeBlocked = true;
} else if (userMode !== 3) {
if (userMode === 0 && (isNsfw || isNsfl || (isUntagged && untaggedDisallowed))) modeBlocked = true; // SFW mode, item is NSFW or NSFL
else if (userMode === 1 && !isNsfw) modeBlocked = true; // NSFW mode, item is not NSFW
else if (userMode === 4 && (!cfg.enable_nsfl || !isNsfl)) modeBlocked = true; // NSFL mode, item is not NSFL
else if (userMode === 2 && (isTagged || untaggedDisallowed)) 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,
slug: actitem.slug || null,
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`
}
};
}
}
if (getEnableItemSlugs() && !actitem.slug) { if (getEnableItemSlugs() && !actitem.slug) {
actitem.slug = lib.generateSlug(11); actitem.slug = lib.generateSlug(11);
db`UPDATE items SET slug = ${actitem.slug} WHERE id = ${actitem.id} AND (slug IS NULL OR slug = '')`.catch(e => console.error('[AUTO_SLUG] Failed DB update:', e.message)); db`UPDATE items SET slug = ${actitem.slug} WHERE id = ${actitem.id} AND (slug IS NULL OR slug = '')`.catch(e => console.error('[AUTO_SLUG] Failed DB update:', e.message));
@@ -1796,7 +2060,7 @@ const f0cklib = {
AND items.title ILIKE ${'%' + titleQuery + '%'} AND items.title ILIKE ${'%' + titleQuery + '%'}
AND items.title IS NOT NULL AND items.title IS NOT NULL
${mimeSQL} ${mimeSQL}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : 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``} ${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() ORDER BY random()
LIMIT 1 LIMIT 1
@@ -1817,7 +2081,7 @@ const f0cklib = {
and items.active = true and items.active = true
and coalesce(items.visibility, 0) = 0 and coalesce(items.visibility, 0) = 0
${mimeSQL} ${mimeSQL}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : db``}
group by items.id group by items.id
order by random() order by random()
limit 1 limit 1
@@ -1860,7 +2124,7 @@ const f0cklib = {
${user ? db`and items.username ilike ${user}` : db``} ${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``} ${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} ${mimeSQL}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : 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``} ${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 group by items.id, tags.tag
order by random() order by random()
@@ -1880,7 +2144,7 @@ const f0cklib = {
and items.active = true and items.active = true
and coalesce(items.visibility, 0) = 0 and coalesce(items.visibility, 0) = 0
${mimeSQL} ${mimeSQL}
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``} ${(!session || isAnonSession(session)) && getGlobalfilter(session) ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))` : 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``} ${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() order by random()
limit 1 limit 1
@@ -1906,13 +2170,13 @@ const f0cklib = {
// When multi-rating SQL is active, use it directly. Otherwise use the tag-join optimisation. // When multi-rating SQL is active, use it directly. Otherwise use the tag-join optimisation.
const globalModeQuery = modequery; const globalModeQuery = modequery;
// tagId optimisation only applies for single native modes for logged-in users (not multi-rating or guest mode) // tagId optimisation only applies for single native modes for logged-in users (not multi-rating or guest mode)
const tagId = session && !multiRatingSQL && (mode === 0 || mode === 1 || mode === 4) const tagId = session && !isAnonSession(session) && !multiRatingSQL && (mode === 0 || mode === 1 || mode === 4)
? (mode === 4 ? (cfg.nsfl_tag_id || 3) : (mode === 1 ? 2 : 1)) ? (mode === 4 ? (cfg.nsfl_tag_id || 3) : (mode === 1 ? 2 : 1))
: null; : null;
// If audio is included, we avoid the strict tagId optimization to ensure audio is visible // If audio is included, we avoid the strict tagId optimization to ensure audio is visible
const useTagIdOpt = tagId && !mimeParts.includes('audio'); const useTagIdOpt = tagId && !mimeParts.includes('audio');
const nsfpIds = cfg.nsfp || []; const nsfpIds = cfg.nsfp || [];
const checkFilter = !session && nsfpIds.length > 0; const checkFilter = (!session || isAnonSession(session)) && nsfpIds.length > 0;
// Use a single uniform query with ORDER BY random() // Use a single uniform query with ORDER BY random()
// For 30k-100k items, this is performant enough and much more reliable than seeking. // For 30k-100k items, this is performant enough and much more reliable than seeking.
@@ -2452,7 +2716,7 @@ const f0cklib = {
getRandomRecommendations: async ({ limit = 20, mode, ratings, session, exclude, user_id, is_admin, mime, exclude_ids } = {}) => { getRandomRecommendations: async ({ limit = 20, mode, ratings, session, exclude, user_id, is_admin, mime, exclude_ids } = {}) => {
const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null; const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null;
const modequery = computeBaseMode(mode, ratingsArr, session); const modequery = computeBaseMode(mode, ratingsArr, session);
const globalfilter = !session ? getGlobalfilter() : null; const globalfilter = (!session || isAnonSession(session)) ? getGlobalfilter(session) : null;
const excludedTags = session && exclude ? (exclude || []) : []; const excludedTags = session && exclude ? (exclude || []) : [];
const maxLimit = Math.min(Math.max(1, Number(limit) || 20), 50); const maxLimit = Math.min(Math.max(1, Number(limit) || 20), 50);
@@ -2741,7 +3005,7 @@ const f0cklib = {
} = {}) => { } = {}) => {
const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null; const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null;
const modequery = computeBaseMode(mode, ratingsArr, session); const modequery = computeBaseMode(mode, ratingsArr, session);
const globalfilter = !session ? getGlobalfilter() : null; const globalfilter = (!session || isAnonSession(session)) ? getGlobalfilter(session) : null;
const excludedTags = session && exclude ? (exclude || []) : []; const excludedTags = session && exclude ? (exclude || []) : [];
const maxLimit = Math.min(Math.max(1, Number(limit) || 20), 50); const maxLimit = Math.min(Math.max(1, Number(limit) || 20), 50);
@@ -3059,7 +3323,7 @@ const f0cklib = {
const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null; const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null;
const modequery = computeBaseMode(mode, ratingsArr, session); const modequery = computeBaseMode(mode, ratingsArr, session);
const globalfilter = !session ? getGlobalfilter() : null; const globalfilter = (!session || isAnonSession(session)) ? getGlobalfilter(session) : null;
const excludedTags = session && exclude ? (exclude || []) : []; const excludedTags = session && exclude ? (exclude || []) : [];
const maxLimit = Math.min(Math.max(1, Number(limit) || 20), 50); const maxLimit = Math.min(Math.max(1, Number(limit) || 20), 50);
const numOffset = Math.max(0, Number(offset) || 0); const numOffset = Math.max(0, Number(offset) || 0);
+26 -3
View File
@@ -1,4 +1,5 @@
import f0cklib from "../routeinc/f0cklib.mjs"; import f0cklib from "../routeinc/f0cklib.mjs";
import lib from "../lib.mjs";
import url from "url"; import url from "url";
import cfg from "../config.mjs"; import cfg from "../config.mjs";
import { createI18n } from "../i18n.mjs"; import { createI18n } from "../i18n.mjs";
@@ -41,10 +42,12 @@ export default (router, tpl) => {
const ratingsArr = isGuest ? ['sfw'] : ((reqMode === 2 || reqMode === 3) ? null : (ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null)); const ratingsArr = isGuest ? ['sfw'] : ((reqMode === 2 || reqMode === 3) ? null : (ratingsRaw ? decodeURIComponent(ratingsRaw).split(/[|,]/).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null));
const itemid = req.params.itemid || req.url.pathname.match(/\/ajax\/item\/([a-zA-Z0-9_-]{11}|\d+)/)?.[1]; const itemid = req.params.itemid || req.url.pathname.match(/\/ajax\/item\/([a-zA-Z0-9_-]{11}|\d+)/)?.[1];
const bypassFilter = !!(query.force === '1' || query.force === 'true' || query.allow === '1' || query.allow === 'true' || query.bypass === '1' || query.bypass === 'true' || query.see_anyways === '1');
const data = await f0cklib.getf0ck({ const data = await f0cklib.getf0ck({
itemid: itemid, itemid: itemid,
mode: reqMode, mode: reqMode,
ratings: ratingsArr, ratings: ratingsArr,
bypass_filter: bypassFilter,
session: req.session, session: req.session,
url: contextUrl, url: contextUrl,
user: query.user, user: query.user,
@@ -67,15 +70,18 @@ export default (router, tpl) => {
if (!data.success) { if (!data.success) {
const reqMode = (query.mode !== undefined ? +query.mode : req.mode) ?? 0; const reqMode = (query.mode !== undefined ? +query.mode : req.mode) ?? 0;
const modeLabels = { 0: 'SFW', 1: 'NSFW', 2: 'Untagged', 4: 'NSFL' }; const modeLabels = { 0: 'SFW', 1: 'NSFW', 2: 'Untagged', 4: 'NSFL' };
const errorModeLabel = (req.session && reqMode !== 3) ? (modeLabels[reqMode] || null) : null; const errorModeLabel = reqMode !== 3 ? (modeLabels[reqMode] || 'SFW') : null;
const { t: tErr } = createI18n(req.session?.language || req.lang || 'en'); const { t: tErr } = createI18n(req.session?.language || req.lang || 'en');
const errorHtml = tpl.render('error-partial', { const errorHtml = tpl.render('error-partial', {
message: tErr('error.post_not_visible'), message: tErr('error.post_not_visible'),
tmp: null, tmp: null,
session: req.session ? { ...req.session } : false, session: req.session ? { ...req.session } : false,
item_id: data.item?.id || itemid,
item_slug: data.item?.slug || (typeof itemid === 'string' ? itemid : null),
error_mode_label: errorModeLabel, error_mode_label: errorModeLabel,
error_filter_hint: errorModeLabel ? tErr('error.filter_hint', { mode: `<strong>${errorModeLabel}</strong>` }) : null, error_filter_hint: errorModeLabel ? tErr('error.filter_hint', { mode: `<strong>${errorModeLabel}</strong>` }) : null,
error_filter_hint_link: tErr('error.filter_hint_link') error_filter_hint_link: tErr('error.filter_hint_link'),
error_see_anyways: tErr('error.see_anyways')
}, req); }, req);
return res.reply({ return res.reply({
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -161,12 +167,29 @@ export default (router, tpl) => {
data.uploader.id = null; data.uploader.id = null;
data.uploader.color = null; data.uploader.color = null;
} }
if (Array.isArray(item.favorites)) {
item.favorites = item.favorites.map(f => {
const isSelf = session && session.id && f.user_id && Number(f.user_id) === Number(session.id);
if (isSelf) return f;
return {
user_id: null,
user: 'anonymous',
login: 'anonymous',
display_name: 'Anonymous',
avatar: null,
avatar_file: null,
username_color: null,
hide_fav_badge: f.hide_fav_badge,
is_anon: true
};
});
}
} }
const isAnon = !!(session && (session.is_anon || (session.user && (session.user === 'anonymous' || session.user.startsWith('anon_'))))); const isAnon = !!(session && (session.is_anon || (session.user && (session.user === 'anonymous' || session.user.startsWith('anon_')))));
data.is_mod_or_admin = !!(session && (session.admin || session.is_moderator)); data.is_mod_or_admin = !!(session && (session.admin || session.is_moderator));
data.can_manage_item = !isAnon && !!(session && (session.admin || session.is_moderator || (session.user && item.username && session.user.toLowerCase() === item.username.toLowerCase()))); data.can_manage_item = !isAnon && !!(session && (session.admin || session.is_moderator || (session.user && item.username && session.user.toLowerCase() === item.username.toLowerCase())));
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.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.user_has_favorited = lib.userHasFavorited(session, item.favorites);
data.halls_slugs = Array.isArray(item.halls) ? item.halls.map(h => h.slug).join(',') : ''; 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(',') : ''; data.user_halls_slugs = Array.isArray(item.user_halls) ? item.user_halls.map(h => h.slug).join(',') : '';
// Precomputed for template engine compatibility (avoids nested { } inside {{ }}) // Precomputed for template engine compatibility (avoids nested { } inside {{ }})
+102 -17
View File
@@ -2,7 +2,7 @@ import { promises as fs } from "fs";
import db from '../../sql.mjs'; import db from '../../sql.mjs';
import lib from '../../lib.mjs'; import lib from '../../lib.mjs';
import cfg from '../../config.mjs'; import cfg from '../../config.mjs';
import { getEnableItemSlugs, canAnonDo, isAnonSession, isAnonymizeSession } from '../../settings.mjs'; import { getEnableItemSlugs, canAnonDo, getAnonAllowedModes, isAnonSession, isAnonymizeSession } from '../../settings.mjs';
import queue from '../../queue.mjs'; import queue from '../../queue.mjs';
import search from '../../routeinc/search.mjs'; import search from '../../routeinc/search.mjs';
import path from "path"; import path from "path";
@@ -15,9 +15,27 @@ import { addPrivateItem, removePrivateItem, addUnavailableItem, removeUnavailabl
import { logAnonActivity } from '../../anon_auth.mjs'; import { logAnonActivity } from '../../anon_auth.mjs';
const allowedMimes = ["audio", "image", "video", "%"]; const allowedMimes = ["audio", "image", "video", "%"];
const getGlobalfilter = () => { const getGlobalfilter = (session) => {
if (!cfg.nsfp?.length) return null; if (!cfg.nsfp?.length) return null;
const filteredTags = cfg.websrv.public_nsfw ? cfg.nsfp.filter(id => id !== 2) : cfg.nsfp; let filteredTags = [...cfg.nsfp];
if (session && isAnonSession(session)) {
const allowedModes = getAnonAllowedModes();
if (allowedModes.includes('nsfw')) {
filteredTags = filteredTags.filter(id => id !== 2);
}
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
if (allowedModes.includes('nsfl')) {
filteredTags = filteredTags.filter(id => id !== nsflId);
}
} else if (!session) {
if (cfg.websrv.public_nsfw) {
filteredTags = filteredTags.filter(id => id !== 2);
}
} else {
if (cfg.websrv.public_nsfw) {
filteredTags = filteredTags.filter(id => id !== 2);
}
}
return filteredTags.length ? filteredTags.map(n => `tag_id = ${n}`).join(' or ') : null; return filteredTags.length ? filteredTags.map(n => `tag_id = ${n}`).join(' or ') : null;
}; };
const metaCache = new Map(); const metaCache = new Map();
@@ -385,11 +403,10 @@ export default router => {
originalFilename = rows[0].original_filename || ''; originalFilename = rows[0].original_filename || '';
} else { } else {
const subRows = isNumeric const subRows = isNumeric
? await db`SELECT dest, original_filename FROM sub_items WHERE id = ${itemId}` ? await db`SELECT dest FROM album_items WHERE id = ${+itemId}`
: await db`SELECT dest, original_filename FROM sub_items WHERE slug = ${itemId}`; : await db`SELECT dest FROM album_items WHERE slug = ${itemId}`;
if (subRows && subRows[0]) { if (subRows && subRows[0]) {
if (!fullPath) fullPath = path.join(cfg.paths.b, subRows[0].dest); if (!fullPath) fullPath = path.join(cfg.paths.b, subRows[0].dest);
originalFilename = subRows[0].original_filename || '';
} }
} }
} }
@@ -1156,6 +1173,7 @@ export default router => {
${db.unsafe(modequery)} and ${db.unsafe(modequery)} and
active = true active = true
${visibilityFilter} ${visibilityFilter}
${(!req.session || isAnonSession(req.session)) && getGlobalfilter(req.session) ? db`and not exists (select 1 from tags_assign where item_id = "items".id and (${db.unsafe(getGlobalfilter(req.session))}))` : 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``} ${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = "items".id and tag_id = any(${excludedTags}::int[]))` : db``}
${opt.older ${opt.older
? db`and id <= ${opt.older}` ? db`and id <= ${opt.older}`
@@ -1175,7 +1193,7 @@ export default router => {
atStart: rows.length > 0 && rows[rows.length - 1].id === oldest, atStart: rows.length > 0 && rows[rows.length - 1].id === oldest,
success: true, success: true,
items: rows items: rows
}, 200); });
}); });
group.get(/\/item\/(?<id>[a-zA-Z0-9_-]{11}|\d+)$/, async (req, res) => { group.get(/\/item\/(?<id>[a-zA-Z0-9_-]{11}|\d+)$/, async (req, res) => {
@@ -1216,20 +1234,42 @@ export default router => {
}); });
} }
const isPublicVisitor = !session || !session.user || isAnonSession(session);
if (isPublicVisitor && !isOwnerOrAdmin && (actitem.visibility || 0) === 0 && getGlobalfilter(session)) {
const filteredItem = await db`
select 1 from tags_assign where item_id = ${id} and (${db.unsafe(getGlobalfilter(session))}) limit 1
`;
if (filteredItem.length > 0) {
return res.json({
success: false,
msg: 'no items found'
});
}
}
const effMode = req.query.mode !== undefined ? +req.query.mode : (req.mode ?? 3); const effMode = req.query.mode !== undefined ? +req.query.mode : (req.mode ?? 3);
const ratingsRaw = req.cookies?.ratings || req.query.ratings; const ratingsRaw = req.cookies?.ratings || req.query.ratings;
const ratingsArr = (effMode === 3 || effMode === 2) ? null : (ratingsRaw ? (Array.isArray(ratingsRaw) ? ratingsRaw : decodeURIComponent(ratingsRaw).split(/[|,]/)).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null); const ratingsArr = (effMode === 3 || effMode === 2) ? null : (ratingsRaw ? (Array.isArray(ratingsRaw) ? ratingsRaw : decodeURIComponent(ratingsRaw).split(/[|,]/)).filter(r => ['sfw','nsfw','nsfl','untagged'].includes(r)) : null);
let guestTagFilter = db``; let guestTagFilter = db``;
if (!session) { if (isPublicVisitor) {
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3; const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
if (cfg.websrv.public_nsfw) { const isAnon = session && isAnonSession(session);
guestTagFilter = db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = ${nsflId})`; const anonModes = isAnon ? getAnonAllowedModes() : [];
} else { const allowNsfw = isAnon ? anonModes.includes('nsfw') : cfg.websrv.public_nsfw;
guestTagFilter = db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id in (2, ${nsflId}))`; const allowNsfl = isAnon ? anonModes.includes('nsfl') : false;
const blockedTags = [];
if (!allowNsfw) blockedTags.push(2);
if (!allowNsfl) blockedTags.push(nsflId);
if (blockedTags.length > 0) {
guestTagFilter = db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id in ${db(blockedTags)})`;
} }
} }
const globalFilterCondition = isPublicVisitor && getGlobalfilter(session)
? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter(session))}))`
: db``;
let modeCondition = db``; let modeCondition = db``;
if (effMode === 2) { if (effMode === 2) {
modeCondition = db`and not exists (select 1 from tags_assign where item_id = items.id)`; modeCondition = db`and not exists (select 1 from tags_assign where item_id = items.id)`;
@@ -1252,14 +1292,14 @@ export default router => {
const next = await db` const next = await db`
select id select id
from "items" from "items"
where id > ${id} and active = true ${visibilityFilter} ${guestTagFilter} ${modeCondition} where id > ${id} and active = true ${visibilityFilter} ${guestTagFilter} ${globalFilterCondition} ${modeCondition}
order by id order by id
limit 1 limit 1
`; `;
const prev = await db` const prev = await db`
select id select id
from "items" from "items"
where id < ${id} and active = true ${visibilityFilter} ${guestTagFilter} ${modeCondition} where id < ${id} and active = true ${visibilityFilter} ${guestTagFilter} ${globalFilterCondition} ${modeCondition}
order by id desc order by id desc
limit 1 limit 1
`; `;
@@ -1581,6 +1621,7 @@ export default router => {
limit 1 limit 1
`; `;
let favorited = false;
if (existing.length > 0) { if (existing.length > 0) {
// del fav // del fav
await db` await db`
@@ -1588,6 +1629,7 @@ export default router => {
where user_id = ${+req.session.id} where user_id = ${+req.session.id}
and item_id = ${+postid} and item_id = ${+postid}
`; `;
favorited = false;
f0cklib.updateUserAffinity({ user_id: req.session.id, item_id: +postid, scoreDelta: -5.0 }).catch(() => {}); f0cklib.updateUserAffinity({ user_id: req.session.id, item_id: +postid, scoreDelta: -5.0 }).catch(() => {});
if (req.session?.is_anon) { if (req.session?.is_anon) {
await logAnonActivity(req, { action: 'unfavorite', targetId: postid }); await logAnonActivity(req, { action: 'unfavorite', targetId: postid });
@@ -1601,6 +1643,7 @@ export default router => {
}, 'item_id', 'user_id')} }, 'item_id', 'user_id')}
on conflict do nothing on conflict do nothing
`; `;
favorited = true;
f0cklib.updateUserAffinity({ user_id: req.session.id, item_id: +postid, scoreDelta: 5.0 }).catch(() => {}); f0cklib.updateUserAffinity({ user_id: req.session.id, item_id: +postid, scoreDelta: 5.0 }).catch(() => {});
if (req.session?.is_anon) { if (req.session?.is_anon) {
await logAnonActivity(req, { action: 'favorite', targetId: postid }); await logAnonActivity(req, { action: 'favorite', targetId: postid });
@@ -1608,23 +1651,65 @@ export default router => {
} }
const favs = await db` const favs = await db`
select "user".user, "user_options".avatar, "user_options".avatar_file, "user_options".display_name, "user_options".username_color, "user_options".hide_fav_badge select "favorites".user_id, "user".user, "user".login, "user_options".avatar, "user_options".avatar_file, "user_options".display_name, "user_options".username_color, "user_options".hide_fav_badge, "anon_identities".fingerprint as anon_fingerprint
from "favorites" from "favorites"
left join "user" on "user".id = "favorites".user_id left join "user" on "user".id = "favorites".user_id
left join "user_options" on "user_options".user_id = "favorites".user_id left join "user_options" on "user_options".user_id = "favorites".user_id
left join "anon_identities" on "anon_identities".user_id = "favorites".user_id
where "favorites".item_id = ${+postid} where "favorites".item_id = ${+postid}
`; `;
// Sanitize shadow anonymous accounts in favs list
const sanitizedFavs = favs.map(f => {
if (f.anon_fingerprint || f.user === 'anonymous' || (typeof f.user === 'string' && f.user.startsWith('anon_'))) {
return {
user_id: null,
user: 'anonymous',
login: 'anonymous',
display_name: 'Anonymous',
avatar: null,
avatar_file: null,
username_color: null,
hide_fav_badge: true,
is_anon: true
};
}
return f;
});
// Notify for live update // Notify for live update
db.notify('favorites', JSON.stringify({ db.notify('favorites', JSON.stringify({
item_id: postid, item_id: postid,
favs: favs user_id: req.session.id,
favorited: favorited,
favs: sanitizedFavs
})); }));
// If the caller is in anonymous mode, strip other users' identities
const isCallerAnonymized = isAnonymizeSession(req.session);
const clientFavs = isCallerAnonymized
? sanitizedFavs.map(f => {
const isSelf = req.session && req.session.id && f.user_id && Number(f.user_id) === Number(req.session.id);
if (isSelf) return f;
return {
user_id: null,
user: 'anonymous',
login: 'anonymous',
display_name: 'Anonymous',
avatar: null,
avatar_file: null,
username_color: null,
hide_fav_badge: f.hide_fav_badge,
is_anon: true
};
})
: sanitizedFavs;
return res.json({ return res.json({
success: true, success: true,
itemid: postid, itemid: postid,
favs favorited: favorited,
favs: clientFavs
}); });
}); });
+21 -5
View File
@@ -8,7 +8,7 @@ import { promises as fs } from "fs";
import { applyWordFilter } from "../wordfilter.mjs"; import { applyWordFilter } from "../wordfilter.mjs";
import path from "path"; import path from "path";
import { parseOpenSshPubkey, verifySignature, getOrCreateAnonUser, resolveAuditIP, logAnonActivity } from "../anon_auth.mjs"; import { parseOpenSshPubkey, verifySignature, getOrCreateAnonUser, resolveAuditIP, logAnonActivity } from "../anon_auth.mjs";
import { getEnableAnonymousAccess, canAnonDo, isAnonSession, isAnonymizeSession } from "../settings.mjs"; import { getEnableAnonymousAccess, canAnonDo, getAnonAllowedModes, isAnonSession, isAnonymizeSession } from "../settings.mjs";
export default (router, tpl) => { export default (router, tpl) => {
@@ -172,7 +172,15 @@ export default (router, tpl) => {
} }
const globalfilterTags = cfg.websrv.public_nsfw ? (cfg.nsfp || []).filter(id => id !== 2) : (cfg.nsfp || []); let globalfilterTags = [...(cfg.nsfp || [])];
if (req.session && isAnonSession(req.session)) {
const allowedModes = getAnonAllowedModes();
if (allowedModes.includes('nsfw')) globalfilterTags = globalfilterTags.filter(id => id !== 2);
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
if (allowedModes.includes('nsfl')) globalfilterTags = globalfilterTags.filter(id => id !== nsflId);
} else if (cfg.websrv.public_nsfw) {
globalfilterTags = globalfilterTags.filter(id => id !== 2);
}
const globalfilter = globalfilterTags.length ? globalfilterTags.map(n => `tag_id = ${n}`).join(' or ') : null; const globalfilter = globalfilterTags.length ? globalfilterTags.map(n => `tag_id = ${n}`).join(' or ') : null;
const excludedTags = req.session ? (req.session.excluded_tags || []) : []; const excludedTags = req.session ? (req.session.excluded_tags || []) : [];
/* <mode-override> */ /* <mode-override> */
@@ -198,7 +206,7 @@ export default (router, tpl) => {
WHERE c.user_id = ${userId} AND c.is_deleted = false WHERE c.user_id = ${userId} AND c.is_deleted = false
AND i.active = true AND i.is_deleted = false AND i.active = true AND i.is_deleted = false
AND ${db.unsafe(modequery)} AND ${db.unsafe(modequery)}
${!req.session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = i.id and (${db.unsafe(globalfilter)}))` : db``} ${(!req.session || isAnonSession(req.session)) && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = i.id and (${db.unsafe(globalfilter)}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = i.id and tag_id = any(${excludedTags}::int[]))` : db``} ${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = i.id and tag_id = any(${excludedTags}::int[]))` : db``}
ORDER BY c.created_at DESC ORDER BY c.created_at DESC
LIMIT ${limit} OFFSET ${offset} LIMIT ${limit} OFFSET ${offset}
@@ -1088,7 +1096,15 @@ export default (router, tpl) => {
// Build mode SQL — replace items.id alias with i.id used in the activity query // Build mode SQL — replace items.id alias with i.id used in the activity query
const modequery = f0cklib.computeBaseMode(mode, ratingsArr, req.session).replace(/items\.id/g, 'i.id'); const modequery = f0cklib.computeBaseMode(mode, ratingsArr, req.session).replace(/items\.id/g, 'i.id');
const globalfilterTags = cfg.websrv.public_nsfw ? (cfg.nsfp || []).filter(id => id !== 2) : (cfg.nsfp || []); let globalfilterTags = [...(cfg.nsfp || [])];
if (req.session && isAnonSession(req.session)) {
const allowedModes = getAnonAllowedModes();
if (allowedModes.includes('nsfw')) globalfilterTags = globalfilterTags.filter(id => id !== 2);
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
if (allowedModes.includes('nsfl')) globalfilterTags = globalfilterTags.filter(id => id !== nsflId);
} else if (cfg.websrv.public_nsfw) {
globalfilterTags = globalfilterTags.filter(id => id !== 2);
}
const globalfilter = globalfilterTags.length ? globalfilterTags.map(n => `tag_id = ${n}`).join(' or ') : null; const globalfilter = globalfilterTags.length ? globalfilterTags.map(n => `tag_id = ${n}`).join(' or ') : null;
const excludedTags = req.session ? (req.session.excluded_tags || []) : []; const excludedTags = req.session ? (req.session.excluded_tags || []) : [];
@@ -1134,7 +1150,7 @@ export default (router, tpl) => {
${activityMimeSQL} ${activityMimeSQL}
${visibilityFilter} ${visibilityFilter}
AND ${db.unsafe(modequery)} AND ${db.unsafe(modequery)}
${!req.session && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = i.id and (${db.unsafe(globalfilter)}))` : db``} ${(!req.session || isAnonSession(req.session)) && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = i.id and (${db.unsafe(globalfilter)}))` : db``}
${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = i.id and tag_id = any(${excludedTags}::int[]))` : db``} ${excludedTags.length > 0 ? db`and not exists (select 1 from tags_assign where item_id = i.id and tag_id = any(${excludedTags}::int[]))` : db``}
ORDER BY c.created_at DESC ORDER BY c.created_at DESC
+26 -3
View File
@@ -265,6 +265,8 @@ export default (router, tpl) => {
f0cklib.updateUserTagAffinity({ user_id: req.session.id, tag: reqTag, scoreDelta: 2.0 }).catch(() => {}); f0cklib.updateUserTagAffinity({ user_id: req.session.id, tag: reqTag, scoreDelta: 2.0 }).catch(() => {});
} }
const bypassFilter = !!(req.query?.force === '1' || req.query?.allow === '1' || req.query?.bypass === '1' || req.url.qs?.force === '1' || req.url.qs?.allow === '1' || req.url.qs?.bypass === '1' || req.query?.see_anyways === '1' || req.url.qs?.see_anyways === '1');
const data = await (req.params.itemid ? f0cklib.getf0ck : f0cklib.getf0cks)({ const data = await (req.params.itemid ? f0cklib.getf0ck : f0cklib.getf0cks)({
user: req.params.user, user: req.params.user,
tag: reqTag, tag: reqTag,
@@ -274,6 +276,7 @@ export default (router, tpl) => {
hall: req.params.hall, hall: req.params.hall,
fav: req.params.mode == 'favs', fav: req.params.mode == 'favs',
mode: req.mode, mode: req.mode,
bypass_filter: bypassFilter,
ratings: (() => { if (req.mode === 2 || req.mode === 3) return null; const r = req.cookies.ratings; return r ? decodeURIComponent(r).split(/[|,]/).filter(x => ['sfw','nsfw','nsfl','untagged'].includes(x)) : null; })(), ratings: (() => { if (req.mode === 2 || req.mode === 3) return null; const r = req.cookies.ratings; return r ? decodeURIComponent(r).split(/[|,]/).filter(x => ['sfw','nsfw','nsfl','untagged'].includes(x)) : null; })(),
session: req.session, session: req.session,
user_id: req.session?.id, user_id: req.session?.id,
@@ -333,19 +336,22 @@ export default (router, tpl) => {
const statusCode = data.item ? 200 : 404; const statusCode = data.item ? 200 : 404;
const reqMode = req.mode ?? 0; const reqMode = req.mode ?? 0;
const modeLabels = { 0: 'SFW', 1: 'NSFW', 2: 'Untagged', 4: 'NSFL' }; const modeLabels = { 0: 'SFW', 1: 'NSFW', 2: 'Untagged', 4: 'NSFL' };
const errorModeLabel = (req.session && reqMode !== 3) ? (modeLabels[reqMode] || null) : null; const errorModeLabel = reqMode !== 3 ? (modeLabels[reqMode] || 'SFW') : null;
const { t: tErr } = createI18n(req.session?.language || req.lang || 'en'); const { t: tErr } = createI18n(req.session?.language || req.lang || 'en');
return res.reply({ return res.reply({
code: statusCode, code: statusCode,
body: tpl.render('error', { body: tpl.render('error', {
message: tErr('error.post_not_visible'), message: tErr('error.post_not_visible'),
item: data.item, // For OG meta tags on filtered NSFW items item: data.item, // For OG meta tags on filtered NSFW items
item_id: data.item?.id || req.params.itemid,
item_slug: data.item?.slug || (typeof req.params.itemid === 'string' ? req.params.itemid : null),
domain: cfg.main.url.domain, domain: cfg.main.url.domain,
tmp: null, tmp: null,
session: req.session ? { ...req.session } : false, session: req.session ? { ...req.session } : false,
error_mode_label: errorModeLabel, error_mode_label: errorModeLabel,
error_filter_hint: errorModeLabel ? tErr('error.filter_hint', { mode: `<strong>${errorModeLabel}</strong>` }) : null, error_filter_hint: errorModeLabel ? tErr('error.filter_hint', { mode: `<strong>${errorModeLabel}</strong>` }) : null,
error_filter_hint_link: tErr('error.filter_hint_link') error_filter_hint_link: tErr('error.filter_hint_link'),
error_see_anyways: tErr('error.see_anyways')
}, req) }, req)
}); });
} }
@@ -420,7 +426,7 @@ export default (router, tpl) => {
// YouTube items use oEmbed via /meta/fetch; all non-flash MIME types are eligible. // 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]))); 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? // Has the current user favorited this item?
data.user_has_favorited = !!(session && Array.isArray(item.favorites) && item.favorites.some(f => f.user === session.user)); data.user_has_favorited = lib.userHasFavorited(session, item.favorites);
// Hall columns for display // Hall columns for display
data.halls_slugs = Array.isArray(item.halls) ? item.halls.map(h => h.slug).join(',') : ''; 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(',') : ''; data.user_halls_slugs = Array.isArray(item.user_halls) ? item.user_halls.map(h => h.slug).join(',') : '';
@@ -442,6 +448,23 @@ export default (router, tpl) => {
data.uploader.id = null; data.uploader.id = null;
data.uploader.color = null; data.uploader.color = null;
} }
if (Array.isArray(item.favorites)) {
item.favorites = item.favorites.map(f => {
const isSelf = session && session.id && f.user_id && Number(f.user_id) === Number(session.id);
if (isSelf) return f;
return {
user_id: null,
user: 'anonymous',
login: 'anonymous',
display_name: 'Anonymous',
avatar: null,
avatar_file: null,
username_color: null,
hide_fav_badge: f.hide_fav_badge,
is_anon: true
};
});
}
} }
// Precomputed for template engine compatibility (avoids nested { } inside {{ }}) // Precomputed for template engine compatibility (avoids nested { } inside {{ }})
data.item_rating_class = item.is_nsfl ? 'is-nsfl' : (item.is_nsfw ? 'is-nsfw' : (item.is_sfw ? 'is-sfw' : 'is-untagged')); data.item_rating_class = item.is_nsfl ? 'is-nsfl' : (item.is_nsfw ? 'is-nsfw' : (item.is_sfw ? 'is-sfw' : 'is-untagged'));
+5
View File
@@ -141,6 +141,9 @@ export default (router, tpl) => {
const result = await db`update "items" set active = true, is_deleted = false where id = ${id} and active = false`; const result = await db`update "items" set active = true, is_deleted = false where id = ${id} and active = false`;
if (result.count === 1) { if (result.count === 1) {
// Mark pending upload notifications as read for staff
await db`UPDATE notifications SET is_read = true WHERE type = 'admin_pending' AND item_id = ${id}`.catch(() => {});
await audit.log(req.session.id, 'approve_item', 'item', id, { filename: f0ck[0].dest, ...uploaderInfo }); await audit.log(req.session.id, 'approve_item', 'item', id, { filename: f0ck[0].dest, ...uploaderInfo });
// Notify User (WebSocket/Internal) // Notify User (WebSocket/Internal)
@@ -375,6 +378,7 @@ export default (router, tpl) => {
const reason = req.post?.reason || "Denied by moderator"; const reason = req.post?.reason || "Denied by moderator";
await db`update "items" set is_deleted = true, active = false where id = ${id}`; await db`update "items" set is_deleted = true, active = false where id = ${id}`;
await db`UPDATE notifications SET is_read = true WHERE type = 'admin_pending' AND item_id = ${id}`.catch(() => {});
// Fetch uploader details for audit log and notification // Fetch uploader details for audit log and notification
let uploaderId = null; let uploaderId = null;
@@ -550,6 +554,7 @@ export default (router, tpl) => {
await fs.unlink(path.join(cfg.paths.ca, `${item.id}.webp`)).catch(() => { }); await fs.unlink(path.join(cfg.paths.ca, `${item.id}.webp`)).catch(() => { });
} }
await db`update "items" set is_deleted = true, active = false where id = ${+id}`; await db`update "items" set is_deleted = true, active = false where id = ${+id}`;
await db`UPDATE notifications SET is_read = true WHERE type = 'admin_pending' AND item_id = ${+id}`.catch(() => {});
// Fetch uploader details for audit log // Fetch uploader details for audit log
let uploaderInfo = {}; let uploaderInfo = {};
try { try {
+39 -2
View File
@@ -1,7 +1,7 @@
import db from "../sql.mjs"; import db from "../sql.mjs";
import f0cklib from "../routeinc/f0cklib.mjs"; import f0cklib from "../routeinc/f0cklib.mjs";
import cfg from "../config.mjs"; import cfg from "../config.mjs";
import { getEnableItemSlugs } from "../settings.mjs"; import { getEnableItemSlugs, isAnonymizeSession } from "../settings.mjs";
import { setMotd } from "../motd.mjs"; import { setMotd } from "../motd.mjs";
import security from "../security.mjs"; import security from "../security.mjs";
@@ -268,10 +268,38 @@ db.listen('favorites', async (payload) => {
try { try {
const data = JSON.parse(payload); const data = JSON.parse(payload);
console.log(`[SSE] Broadcasting favorite update for item ${data.item_id} to ${clients.size} clients`); console.log(`[SSE] Broadcasting favorite update for item ${data.item_id} to ${clients.size} clients`);
// Broadcast to ALL connected clients // Broadcast to ALL connected clients with per-client anonymization
for (const client of clients) { for (const client of clients) {
const isAnonClient = client.session ? isAnonymizeSession(client.session) : (client.isAnonymized ?? isAnonymizeSession(null));
if (isAnonClient) {
const anonymizedFavs = Array.isArray(data.favs) ? data.favs.map(f => {
const isSelf = client.userId && f.user_id && Number(f.user_id) === Number(client.userId);
if (isSelf) return f;
return {
user_id: null,
user: 'anonymous',
login: 'anonymous',
display_name: 'Anonymous',
avatar: null,
avatar_file: null,
username_color: null,
hide_fav_badge: f.hide_fav_badge,
is_anon: true
};
}) : [];
client.send({
type: 'favorites',
data: {
item_id: data.item_id,
user_id: (client.userId && data.user_id && Number(client.userId) === Number(data.user_id)) ? data.user_id : null,
favorited: data.favorited,
favs: anonymizedFavs
}
});
} else {
client.send({ type: 'favorites', data }); client.send({ type: 'favorites', data });
} }
}
} catch (e) { } catch (e) {
console.error('Favorite broadcast error:', e); console.error('Favorite broadcast error:', e);
} }
@@ -445,6 +473,10 @@ db.listen('global_chat_topic', (payload) => {
export default (router, tpl) => { export default (router, tpl) => {
// Cleanup any orphaned or obsolete unread notifications on startup
db`UPDATE notifications SET is_read = true WHERE type = 'report' AND reference_id IN (SELECT id FROM reports WHERE status != 'pending') AND is_read = false`.catch(err => console.error('[NOTIF CLEANUP] Failed to cleanup report notifications:', err));
db`UPDATE notifications SET is_read = true WHERE type = 'admin_pending' AND item_id IN (SELECT id FROM items WHERE active = true OR is_deleted = true) AND is_read = false`.catch(err => console.error('[NOTIF CLEANUP] Failed to cleanup admin_pending notifications:', err));
const USER_TYPES = ['comment_reply', 'subscription', 'mention', 'upload_comment']; const USER_TYPES = ['comment_reply', 'subscription', 'mention', 'upload_comment'];
const SYSTEM_TYPES = ['approve', 'deny', 'item_deleted', 'upload_success', 'upload_error', 'admin_pending', 'report', 'warning']; const SYSTEM_TYPES = ['approve', 'deny', 'item_deleted', 'upload_success', 'upload_error', 'admin_pending', 'report', 'warning'];
@@ -548,6 +580,7 @@ export default (router, tpl) => {
LEFT JOIN "user" u ON c.user_id = u.id LEFT JOIN "user" u ON c.user_id = u.id
LEFT JOIN user_options uo ON u.id = uo.user_id LEFT JOIN user_options uo ON u.id = uo.user_id
LEFT JOIN items i ON n.item_id = i.id LEFT JOIN items i ON n.item_id = i.id
LEFT JOIN reports r ON n.type = 'report' AND n.reference_id = r.id
WHERE n.user_id = ${req.session.id} AND n.is_read = false WHERE n.user_id = ${req.session.id} AND n.is_read = false
AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report', 'approve', 'warning') AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report', 'approve', 'warning')
OR ( OR (
@@ -558,6 +591,8 @@ 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', 'warning')) 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'))
AND (n.type != 'report' OR r.status = 'pending')
AND (n.type != 'admin_pending' OR (i.active = false AND i.is_deleted = false))
ORDER BY n.created_at DESC ORDER BY n.created_at DESC
LIMIT 1000 LIMIT 1000
`; `;
@@ -677,6 +712,8 @@ export default (router, tpl) => {
const client = { const client = {
userId: clientUserId, userId: clientUserId,
session: req.session || null,
isAnonymized: isAnonymizeSession(req.session),
fingerprint: clientFp, fingerprint: clientFp,
hwFingerprint: clientHw, hwFingerprint: clientHw,
username: req.session?.user || null, username: req.session?.user || null,
+7
View File
@@ -188,6 +188,13 @@ export default (router, tpl) => {
return res.json({ success: false, msg: "Report not found." }, 404); return res.json({ success: false, msg: "Report not found." }, 404);
} }
// Mark all notifications for this report as read across all moderators
await db`
UPDATE notifications
SET is_read = true
WHERE type = 'report' AND reference_id = ${id}
`;
await audit.log(req.session.id, 'resolve_report', 'report', id, { status: action }); await audit.log(req.session.id, 'resolve_report', 'report', id, { status: action });
return res.json({ success: true, msg: `Report marked as ${action}.` }); return res.json({ success: true, msg: `Report marked as ${action}.` });
+4 -4
View File
@@ -2,7 +2,7 @@ import cfg from "../config.mjs";
import db from "../sql.mjs"; import db from "../sql.mjs";
import lib from "../lib.mjs"; import lib from "../lib.mjs";
import f0cklib from "../routeinc/f0cklib.mjs"; import f0cklib from "../routeinc/f0cklib.mjs";
import { isAnonymizeSession } from "../settings.mjs"; import { isAnonymizeSession, isAnonSession } from "../settings.mjs";
export default (router, tpl) => { export default (router, tpl) => {
// Serve the scroller page // Serve the scroller page
@@ -265,7 +265,7 @@ export default (router, tpl) => {
${excludeSwfSQL} ${excludeSwfSQL}
${excludePdfSQL} ${excludePdfSQL}
${excludeArchiveSQL} ${excludeArchiveSQL}
${!req.session && nsfp ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND (${db.unsafe(nsfp)}))` : db``} ${(!req.session || isAnonSession(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. // If the anchor item doesn't pass the rating filter, it's inaccessible to this user.
// Return empty so the frontend shows "This post is currently unavailable". // Return empty so the frontend shows "This post is currently unavailable".
@@ -288,7 +288,7 @@ export default (router, tpl) => {
${excludeSQL} ${excludeSQL}
${mimeSQL} ${mimeSQL}
${tagSQL} ${tagSQL}
${!req.session && nsfp ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND (${db.unsafe(nsfp)}))` : db``} ${(!req.session || isAnonSession(req.session)) && nsfp ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND (${db.unsafe(nsfp)}))` : 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``} ${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() ORDER BY random()
LIMIT ${limit - 1} LIMIT ${limit - 1}
@@ -313,7 +313,7 @@ export default (router, tpl) => {
${excludeSQL} ${excludeSQL}
${mimeSQL} ${mimeSQL}
${tagSQL} ${tagSQL}
${!req.session && nsfp ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND (${db.unsafe(nsfp)}))` : db``} ${(!req.session || isAnonSession(req.session)) && nsfp ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND (${db.unsafe(nsfp)}))` : 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``} ${excludedTags.length > 0 ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND tag_id = ANY(${excludedTags}::int[]))` : db``}
${orderSQL} ${orderSQL}
LIMIT ${limit} LIMIT ${limit}
+16 -3
View File
@@ -1,6 +1,7 @@
import db from "../../inc/sql.mjs"; import db from "../../inc/sql.mjs";
import lib from "../../inc/lib.mjs"; import lib from "../../inc/lib.mjs";
import cfg from "../../inc/config.mjs"; import cfg from "../../inc/config.mjs";
import { isAnonSession, getAnonAllowedModes } from "../settings.mjs";
import url from "url"; import url from "url";
const TAGS_PER_PAGE = 50; // Smaller chunks for better infinite scroll const TAGS_PER_PAGE = 50; // Smaller chunks for better infinite scroll
@@ -9,6 +10,7 @@ export default (router, tpl) => {
const getTagsQuery = async (mode, offset, limit, sessionObj = false, strict = false) => { const getTagsQuery = async (mode, offset, limit, sessionObj = false, strict = false) => {
const excludedTags = sessionObj ? (sessionObj.excluded_tags || []) : []; const excludedTags = sessionObj ? (sessionObj.excluded_tags || []) : [];
const isGuest = !sessionObj; const isGuest = !sessionObj;
const isPublicVisitor = !sessionObj || isAnonSession(sessionObj);
let baseMode = lib.getMode(mode); let baseMode = lib.getMode(mode);
if (isGuest) { if (isGuest) {
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3; const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
@@ -29,16 +31,27 @@ export default (router, tpl) => {
const modequery = baseMode; const modequery = baseMode;
let restrictedFilter = db``; let restrictedFilter = db``;
if (isGuest && cfg.nsfp && cfg.nsfp.length > 0) { if (isPublicVisitor && cfg.nsfp && cfg.nsfp.length > 0) {
let effectiveNsfp = [...cfg.nsfp];
if (sessionObj && isAnonSession(sessionObj)) {
const allowedModes = getAnonAllowedModes();
if (allowedModes.includes('nsfw')) effectiveNsfp = effectiveNsfp.filter(id => id !== 2);
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
if (allowedModes.includes('nsfl')) effectiveNsfp = effectiveNsfp.filter(id => id !== nsflId);
} else if (cfg.websrv.public_nsfw) {
effectiveNsfp = effectiveNsfp.filter(id => id !== 2);
}
if (effectiveNsfp.length > 0) {
restrictedFilter = db` restrictedFilter = db`
AND t.id NOT IN ${db(cfg.nsfp)} AND t.id NOT IN ${db(effectiveNsfp)}
AND NOT EXISTS ( AND NOT EXISTS (
SELECT 1 FROM tags_assign ta_res SELECT 1 FROM tags_assign ta_res
WHERE ta_res.item_id = items.id WHERE ta_res.item_id = items.id
AND ta_res.tag_id IN ${db(cfg.nsfp)} AND ta_res.tag_id IN ${db(effectiveNsfp)}
) )
`; `;
} }
}
const userExcludeFilter = excludedTags.length > 0 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`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[]))`
+19 -1
View File
@@ -1,5 +1,6 @@
import db from "../sql.mjs"; import db from "../sql.mjs";
import cfg from "../config.mjs"; import cfg from "../config.mjs";
import lib from "../lib.mjs";
import { isAnonymizeSession } from "../settings.mjs"; import { isAnonymizeSession } from "../settings.mjs";
import f0cklib from "../routeinc/f0cklib.mjs"; import f0cklib from "../routeinc/f0cklib.mjs";
import fs from "fs/promises"; import fs from "fs/promises";
@@ -174,7 +175,7 @@ export default (router, tpl) => {
data.is_mod_or_admin = !!(session && (session.admin || session.is_moderator)); data.is_mod_or_admin = !!(session && (session.admin || session.is_moderator));
data.can_manage_item = !isAnon && !!(session && (session.admin || session.is_moderator || (session.user && item.username && session.user.toLowerCase() === item.username.toLowerCase()))); data.can_manage_item = !isAnon && !!(session && (session.admin || session.is_moderator || (session.user && item.username && session.user.toLowerCase() === item.username.toLowerCase())));
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.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.user_has_favorited = lib.userHasFavorited(session, item.favorites);
data.halls_slugs = Array.isArray(item.halls) ? item.halls.map(h => h.slug).join(',') : ''; 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(',') : ''; data.user_halls_slugs = Array.isArray(item.user_halls) ? item.user_halls.map(h => h.slug).join(',') : '';
data.item_rating_class = item.is_nsfl ? 'is-nsfl' : (item.is_nsfw ? 'is-nsfw' : (item.is_sfw ? 'is-sfw' : 'is-untagged')); data.item_rating_class = item.is_nsfl ? 'is-nsfl' : (item.is_nsfw ? 'is-nsfw' : (item.is_sfw ? 'is-sfw' : 'is-untagged'));
@@ -204,6 +205,23 @@ export default (router, tpl) => {
data.uploader.id = null; data.uploader.id = null;
data.uploader.color = null; data.uploader.color = null;
} }
if (Array.isArray(item.favorites)) {
item.favorites = item.favorites.map(f => {
const isSelf = session && session.id && f.user_id && Number(f.user_id) === Number(session.id);
if (isSelf) return f;
return {
user_id: null,
user: 'anonymous',
login: 'anonymous',
display_name: 'Anonymous',
avatar: null,
avatar_file: null,
username_color: null,
hide_fav_badge: f.hide_fav_badge,
is_anon: true
};
});
}
} }
} }
+16 -4
View File
@@ -1,7 +1,7 @@
import db from "../../inc/sql.mjs"; import db from "../../inc/sql.mjs";
import lib from "../../inc/lib.mjs"; import lib from "../../inc/lib.mjs";
import cfg from "../../inc/config.mjs"; import cfg from "../../inc/config.mjs";
import { isAnonymizeSession } from "../settings.mjs"; import { isAnonymizeSession, isAnonSession, getAnonAllowedModes } from "../settings.mjs";
import url from "url"; import url from "url";
const TAGS_PER_PAGE = 50; // Smaller chunks for better infinite scroll const TAGS_PER_PAGE = 50; // Smaller chunks for better infinite scroll
@@ -10,6 +10,7 @@ export default (router, tpl) => {
const getTagsQuery = async (userId, mode, offset, limit, sessionObj = false, strict = false) => { const getTagsQuery = async (userId, mode, offset, limit, sessionObj = false, strict = false) => {
const excludedTags = sessionObj ? (sessionObj.excluded_tags || []) : []; const excludedTags = sessionObj ? (sessionObj.excluded_tags || []) : [];
const isGuest = !sessionObj; const isGuest = !sessionObj;
const isPublicVisitor = !sessionObj || isAnonSession(sessionObj);
let baseMode = lib.getMode(mode); let baseMode = lib.getMode(mode);
if (isGuest) { if (isGuest) {
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3; const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
@@ -30,16 +31,27 @@ export default (router, tpl) => {
const modequery = baseMode; const modequery = baseMode;
let restrictedFilter = db``; let restrictedFilter = db``;
if (isGuest && cfg.nsfp && cfg.nsfp.length > 0) { if (isPublicVisitor && cfg.nsfp && cfg.nsfp.length > 0) {
let effectiveNsfp = [...cfg.nsfp];
if (sessionObj && isAnonSession(sessionObj)) {
const allowedModes = getAnonAllowedModes();
if (allowedModes.includes('nsfw')) effectiveNsfp = effectiveNsfp.filter(id => id !== 2);
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
if (allowedModes.includes('nsfl')) effectiveNsfp = effectiveNsfp.filter(id => id !== nsflId);
} else if (cfg.websrv.public_nsfw) {
effectiveNsfp = effectiveNsfp.filter(id => id !== 2);
}
if (effectiveNsfp.length > 0) {
restrictedFilter = db` restrictedFilter = db`
AND t.id NOT IN ${db(cfg.nsfp)} AND t.id NOT IN ${db(effectiveNsfp)}
AND NOT EXISTS ( AND NOT EXISTS (
SELECT 1 FROM tags_assign ta_res SELECT 1 FROM tags_assign ta_res
WHERE ta_res.item_id = items.id WHERE ta_res.item_id = items.id
AND ta_res.tag_id IN ${db(cfg.nsfp)} AND ta_res.tag_id IN ${db(effectiveNsfp)}
) )
`; `;
} }
}
const userExcludeFilter = excludedTags.length > 0 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`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[]))`
+3
View File
@@ -649,6 +649,9 @@ process.on('uncaughtException', err => {
app.use(async (req, res) => { app.use(async (req, res) => {
const p = req.url?.pathname; const p = req.url?.pathname;
if (!p) return; if (!p) return;
if (p.startsWith('/t/') || p.startsWith('/ca/') || p.startsWith('/b/') || p.startsWith('/s/') || p.startsWith('/a/') || p.startsWith('/c/')) {
res.setHeader('Access-Control-Allow-Origin', '*');
}
if (getProtectFiles() || isPrivateItemPath(p)) return; // Protect-files or private item — don't cache if (getProtectFiles() || isPrivateItemPath(p)) return; // Protect-files or private item — don't cache
if (p.startsWith('/t/') || p.startsWith('/ca/') || p.startsWith('/b/')) { if (p.startsWith('/t/') || p.startsWith('/ca/') || p.startsWith('/b/')) {
// Thumbnails, covers, and source blobs: 1-year cache. // Thumbnails, covers, and source blobs: 1-year cache.
+1 -1
View File
@@ -930,7 +930,7 @@ export const handleUpload = async (req, res, self) => {
console.warn(`[UPLOAD] Error assigning tag "${sTag}" to subf0ck ${subItemId}:`, stErr.message); console.warn(`[UPLOAD] Error assigning tag "${sTag}" to subf0ck ${subItemId}:`, stErr.message);
} }
} }
} else if (subItemId && i === 0 && tags && tags.length > 0) { } else if (subItemId && tags && tags.length > 0) {
// Backfill initial post tags to cover subf0ck // Backfill initial post tags to cover subf0ck
for (const sTag of tags) { for (const sTag of tags) {
try { try {
+9 -4
View File
@@ -181,9 +181,6 @@
if (data.success) { if (data.success) {
addChip(data.added); addChip(data.added);
showStatus(addStatus, '"' + escapeHtml(data.added.tag) + '" (#' + data.added.id + ') added.', true); showStatus(addStatus, '"' + escapeHtml(data.added.tag) + '" (#' + data.added.id + ') added.', true);
document.getElementById('nsfp-search').value = '';
document.getElementById('search-dropdown').style.display = 'none';
lastResults = [];
} else { } else {
showStatus(addStatus, 'Error: ' + (data.msg || 'Add failed'), false); showStatus(addStatus, 'Error: ' + (data.msg || 'Add failed'), false);
} }
@@ -230,7 +227,8 @@
} }
var searchTimer = null; var searchTimer = null;
document.getElementById('nsfp-search').addEventListener('input', function () { var searchInput = document.getElementById('nsfp-search');
searchInput.addEventListener('input', function () {
clearTimeout(searchTimer); clearTimeout(searchTimer);
var q = this.value.trim(); var q = this.value.trim();
if (!q) { lastResults = []; document.getElementById('search-dropdown').style.display = 'none'; return; } if (!q) { lastResults = []; document.getElementById('search-dropdown').style.display = 'none'; return; }
@@ -245,6 +243,13 @@
}, 250); }, 250);
}); });
searchInput.addEventListener('focus', function () {
var q = this.value.trim();
if (q && lastResults.length) {
rebuildDropdown(q);
}
});
document.addEventListener('click', function (e) { document.addEventListener('click', function (e) {
if (!e.target.closest('.nsfp-search-wrap')) { if (!e.target.closest('.nsfp-search-wrap')) {
document.getElementById('search-dropdown').style.display = 'none'; document.getElementById('search-dropdown').style.display = 'none';
+8 -3
View File
@@ -11,10 +11,15 @@
<span>{{ t('error.label') }}</span> <span>{{ t('error.label') }}</span>
<code>{{ message }}</code> <code>{{ message }}</code>
</div> </div>
@if(session && error_filter_hint) @if(error_filter_hint)
<div class="_error_filter_hint"> <div class="_error_filter_hint">
{{ error_filter_hint }} <br> <div class="_error_filter_hint_text">{{ error_filter_hint }}</div>
<a href="#" data-action="open-filter-modal">{{ error_filter_hint_link }}</a> <a href="#" data-action="open-filter-modal" class="_error_filter_hint_link">{{ error_filter_hint_link }}</a>
<div class="_error_filter_actions">
<button type="button" class="btn _error_see_anyways_btn" data-action="see-anyways" data-item-id="{{ item_id || '' }}" data-item-slug="{{ item_slug || '' }}">
<i class="fa fa-eye"></i> {{ error_see_anyways }}
</button>
</div>
</div> </div>
@endif @endif
</div> </div>
+8 -3
View File
@@ -14,10 +14,15 @@
<span>{{ t('error.label') }}</span> <span>{{ t('error.label') }}</span>
<code>{{ message }}</code> <code>{{ message }}</code>
</div> </div>
@if(session && error_filter_hint) @if(error_filter_hint)
<div class="_error_filter_hint"> <div class="_error_filter_hint">
{{ error_filter_hint }} <br> <div class="_error_filter_hint_text">{{ error_filter_hint }}</div>
<a href="#" data-action="open-filter-modal">{{ error_filter_hint_link }}</a> <a href="#" data-action="open-filter-modal" class="_error_filter_hint_link">{{ error_filter_hint_link }}</a>
<div class="_error_filter_actions">
<button type="button" class="btn _error_see_anyways_btn" data-action="see-anyways" data-item-id="{{ item_id || '' }}" data-item-slug="{{ item_slug || '' }}">
<i class="fa fa-eye"></i> {{ error_see_anyways }}
</button>
</div>
</div> </div>
@endif @endif
</div> </div>
+1 -1
View File
@@ -20,7 +20,7 @@
<span class="thumb-xd-indicator xd-tier-{{ item.xd_tier }}" title="xD Score: {{ item.xd_score }}">xD</span> <span class="thumb-xd-indicator xd-tier-{{ item.xd_tier }}" title="xD Score: {{ item.xd_score }}">xD</span>
@endif @endif
@if(item.is_album && item.album_count > 1) @if(item.is_album && item.album_count > 1)
<span class="album-indicator anim" title="Album: {{ item.album_count }} images"><i class="fa-solid fa-images"></i> {{ item.album_count }}</span> <span class="album-indicator" title="Album: {{ item.album_count }} images"><i class="fa-solid fa-images"></i> {{ item.album_count }}</span>
@endif @endif
</div> </div>
<div class="thumb-select-check"><i class="fa-solid fa-check"></i></div> <div class="thumb-select-check"><i class="fa-solid fa-check"></i></div>
+1 -1
View File
@@ -227,7 +227,7 @@
@each(item.favorites as fav) @each(item.favorites as fav)
@if(fav.hide_fav_badge && (!session || session.user !== fav.user)) @if(fav.hide_fav_badge && (!session || session.user !== fav.user))
<a class="ghost-fav" tooltip="?" flow="up" style="cursor: default;"><img src="/s/img/ghost_fav.svg" style="height: 32px; width: 32px;" loading="lazy" /></a> <a class="ghost-fav" tooltip="?" flow="up" style="cursor: default;"><img src="/s/img/ghost_fav.svg" style="height: 32px; width: 32px;" loading="lazy" /></a>
@elseif(is_anonymized) @elseif(is_anonymized || fav.is_anon)
<a class="ghost-fav" tooltip="anonymous" flow="up" style="cursor: default;"><img src="/a/default.png" style="height: 32px; width: 32px;" loading="lazy" /></a> <a class="ghost-fav" tooltip="anonymous" flow="up" style="cursor: default;"><img src="/a/default.png" style="height: 32px; width: 32px;" loading="lazy" /></a>
@else @else
<a href="/user/{{ fav.user.toLowerCase() }}" tooltip="{!! fav.display_name || fav.user !!}" flow="up"><img src="@if(fav.avatar_file)/a/{{ fav.avatar_file }}@elseif(fav.avatar)/t/{{ fav.avatar }}.webp@else/a/default.png@endif" style="height: 32px; width: 32px@if(fav.username_color); border-color: {{ fav.username_color }}@endif" loading="lazy" /></a> <a href="/user/{{ fav.user.toLowerCase() }}" tooltip="{!! fav.display_name || fav.user !!}" flow="up"><img src="@if(fav.avatar_file)/a/{{ fav.avatar_file }}@elseif(fav.avatar)/t/{{ fav.avatar }}.webp@else/a/default.png@endif" style="height: 32px; width: 32px@if(fav.username_color); border-color: {{ fav.username_color }}@endif" loading="lazy" /></a>
+3 -2
View File
@@ -139,6 +139,7 @@
</div> </div>
</div> </div>
<div class="blahlol"> <div class="blahlol">
<div class="blahlol-meta">
<span class="badge badge-dark"> <span class="badge badge-dark">
<a href="/{{ (enable_item_slugs && item.slug) ? item.slug : item.id }}" class="id-link" data-item-id="{{ item.id }}">{{ (enable_item_slugs && item.slug) ? item.slug : item.id }}</a> — [@if(!is_anonymized)<a id="a_username" data-username="{{ item.username || '' }}" @if(session && !session.is_anon) data-author-id="{{ item.author_id || '' }}" @endif href="/user/{{ item_username_lower }}" @if(session && !session.is_anon && item.author_id) tooltip="ID: {{ item.author_id }}" @endif @if(item.author_color) style="color: {{ item.author_color }}" @endif>{!! item.author_display_name || item.username || 'unknown' !!}</a>@else<span>anonymous</span>@endif] <span id="oc-badge-container">@if(item.is_oc) — <span class="oc-badge" tooltip="Original Content">OC</span>@endif</span> <a href="/{{ (enable_item_slugs && item.slug) ? item.slug : item.id }}" class="id-link" data-item-id="{{ item.id }}">{{ (enable_item_slugs && item.slug) ? item.slug : item.id }}</a> — [@if(!is_anonymized)<a id="a_username" data-username="{{ item.username || '' }}" @if(session && !session.is_anon) data-author-id="{{ item.author_id || '' }}" @endif href="/user/{{ item_username_lower }}" @if(session && !session.is_anon && item.author_id) tooltip="ID: {{ item.author_id }}" @endif @if(item.author_color) style="color: {{ item.author_color }}" @endif>{!! item.author_display_name || item.username || 'unknown' !!}</a>@else<span>anonymous</span>@endif] <span id="oc-badge-container">@if(item.is_oc) — <span class="oc-badge" tooltip="Original Content">OC</span>@endif</span>
</span> </span>
@@ -149,7 +150,7 @@
@if(item.expires_at) @if(item.expires_at)
<span class="badge badge-warning" style="background: rgba(255, 170, 0, 0.2); color: #ffaa00; border: 1px solid rgba(255, 170, 0, 0.4);" tooltip="Self-destructs {{ item.expires_in }}" flow="up"><i class="fa-solid fa-clock"></i> Expiring ({{ item.expires_in }})</span> <span class="badge badge-warning" style="background: rgba(255, 170, 0, 0.2); color: #ffaa00; border: 1px solid rgba(255, 170, 0, 0.4);" tooltip="Self-destructs {{ item.expires_in }}" flow="up"><i class="fa-solid fa-clock"></i> Expiring ({{ item.expires_in }})</span>
@endif @endif
</div>
<div class="gapRight"> <div class="gapRight">
@if(session) @if(session)
@@ -187,7 +188,7 @@
@each(item.favorites as fav) @each(item.favorites as fav)
@if(fav.hide_fav_badge && (!session || session.user !== fav.user)) @if(fav.hide_fav_badge && (!session || session.user !== fav.user))
<a class="ghost-fav" tooltip="?" flow="up" style="cursor: default;"><img src="/s/img/ghost_fav.svg" style="height: 32px; width: 32px;" loading="lazy" /></a> <a class="ghost-fav" tooltip="?" flow="up" style="cursor: default;"><img src="/s/img/ghost_fav.svg" style="height: 32px; width: 32px;" loading="lazy" /></a>
@elseif(is_anonymized) @elseif(is_anonymized || fav.is_anon)
<a class="ghost-fav" tooltip="anonymous" flow="up" style="cursor: default;"><img src="/a/default.png" style="height: 32px; width: 32px;" loading="lazy" /></a> <a class="ghost-fav" tooltip="anonymous" flow="up" style="cursor: default;"><img src="/a/default.png" style="height: 32px; width: 32px;" loading="lazy" /></a>
@else @else
<a href="/user/{{ fav.user.toLowerCase() }}" tooltip="{!! fav.display_name || fav.user !!}" flow="up"><img src="@if(fav.avatar_file)/a/{{ fav.avatar_file }}@elseif(fav.avatar)/t/{{ fav.avatar }}.webp@else/a/default.png@endif" style="height: 32px; width: 32px@if(fav.username_color); border-color: {{ fav.username_color }}@endif" loading="lazy" /></a> <a href="/user/{{ fav.user.toLowerCase() }}" tooltip="{!! fav.display_name || fav.user !!}" flow="up"><img src="@if(fav.avatar_file)/a/{{ fav.avatar_file }}@elseif(fav.avatar)/t/{{ fav.avatar }}.webp@else/a/default.png@endif" style="height: 32px; width: 32px@if(fav.username_color); border-color: {{ fav.username_color }}@endif" loading="lazy" /></a>
+3
View File
@@ -187,6 +187,9 @@ window.resolveReport = async function(id, action) {
const data = await res.json(); const data = await res.json();
if (data.success) { if (data.success) {
window.loadReports(window.currentPage); window.loadReports(window.currentPage);
if (window.NotificationSystemInstance && typeof window.NotificationSystemInstance.pollDebounced === 'function') {
window.NotificationSystemInstance.pollDebounced();
}
} else { } else {
alert('Error: ' + data.msg); alert('Error: ' + data.msg);
} }
+54
View File
@@ -252,6 +252,60 @@
<small class="text-muted" style="margin-left: 25px;">{{ t('settings.enable_bg_blur_hint') }}</small> <small class="text-muted" style="margin-left: 25px;">{{ t('settings.enable_bg_blur_hint') }}</small>
</div> </div>
<div class="setting-item" style="margin-top: 15px; padding-left: 25px;">
<div style="display: flex; align-items: center; justify-content: space-between; max-width: 380px;">
<label for="onara_bg_opacity_slider" style="font-size: 0.9em; margin-bottom: 0; font-weight: bold;">Onara Backdrop Darkness</label>
<span id="onara_bg_opacity_val" style="font-size: 0.85em; opacity: 0.8;">84%</span>
</div>
<input type="range" id="onara_bg_opacity_slider" min="0" max="1" step="0.01" value="0.84" style="max-width: 380px; width: 100%; margin-top: 4px;">
<small class="text-muted" style="display: block;">Overlay darkness in Onara mode (lower values allow background canvas to shine through).</small>
</div>
<div class="setting-item" style="margin-top: 15px; padding-left: 25px;">
<div style="display: flex; align-items: center; justify-content: space-between; max-width: 380px;">
<label for="onara_backdrop_blur_slider" style="font-size: 0.9em; margin-bottom: 0; font-weight: bold;">Onara Backdrop Blur</label>
<span id="onara_backdrop_blur_val" style="font-size: 0.85em; opacity: 0.8;">5px</span>
</div>
<input type="range" id="onara_backdrop_blur_slider" min="0" max="50" step="1" value="5" style="max-width: 380px; width: 100%; margin-top: 4px;">
<small class="text-muted" style="display: block;">Backdrop blur applied behind the Onara media modal.</small>
</div>
<div class="setting-item" style="margin-top: 15px; padding-left: 25px;">
<div style="display: flex; align-items: center; justify-content: space-between; max-width: 380px;">
<label for="onara_grid_dim_slider" style="font-size: 0.9em; margin-bottom: 0; font-weight: bold;">Onara Background Grid Opacity</label>
<span id="onara_grid_dim_val" style="font-size: 0.85em; opacity: 0.8;">15%</span>
</div>
<input type="range" id="onara_grid_dim_slider" min="0" max="1" step="0.01" value="0.15" style="max-width: 380px; width: 100%; margin-top: 4px;">
<small class="text-muted" style="display: block;">Control how clearly the background thumbnail grid shines through over the ambient canvas in Onara mode.</small>
</div>
<div class="setting-item" style="margin-top: 15px; padding-left: 25px;">
<div style="display: flex; align-items: center; justify-content: space-between; max-width: 380px;">
<label for="bg_canvas_opacity_slider" style="font-size: 0.9em; margin-bottom: 0; font-weight: bold;">Background Canvas Opacity</label>
<span id="bg_canvas_opacity_val" style="font-size: 0.85em; opacity: 0.8;">100%</span>
</div>
<input type="range" id="bg_canvas_opacity_slider" min="0" max="1" step="0.01" value="1.00" style="max-width: 380px; width: 100%; margin-top: 4px;">
<small class="text-muted" style="display: block;">Control the visibility and brightness of the ambient background canvas & audio visualizer.</small>
</div>
<div class="setting-item" style="margin-top: 15px; padding-left: 25px;">
<div style="display: flex; align-items: center; justify-content: space-between; max-width: 380px;">
<label for="bg_canvas_blur_slider" style="font-size: 0.9em; margin-bottom: 0; font-weight: bold;">Background Canvas Blur</label>
<span id="bg_canvas_blur_val" style="font-size: 0.85em; opacity: 0.8;">300px</span>
</div>
<input type="range" id="bg_canvas_blur_slider" min="0" max="300" step="1" value="300" style="max-width: 380px; width: 100%; margin-top: 4px;">
<small class="text-muted" style="display: block;">Adjust the ambient blur of the background canvas (higher values create a soft, dreamy ambient glow).</small>
</div>
<div class="setting-item" style="margin-top: 15px; padding-left: 25px;">
<div style="display: flex; align-items: center; justify-content: space-between; max-width: 380px;">
<label for="bg_canvas_brightness_slider" style="font-size: 0.9em; margin-bottom: 0; font-weight: bold;">Background Brightness Boost</label>
<span id="bg_canvas_brightness_val" style="font-size: 0.85em; opacity: 0.8;">100%</span>
</div>
<input type="range" id="bg_canvas_brightness_slider" min="0.5" max="2.5" step="0.05" value="1.00" style="max-width: 380px; width: 100%; margin-top: 4px;">
<small class="text-muted" style="display: block;">Boost background canvas brightness so visuals pop through clearly.</small>
</div>
<div class="setting-item" style="margin-top: 15px;"> <div class="setting-item" style="margin-top: 15px;">
<label for="show_motd_toggle" style="cursor: pointer; display: flex; align-items: center; gap: 10px;"> <label for="show_motd_toggle" style="cursor: pointer; display: flex; align-items: center; gap: 10px;">
<input type="checkbox" id="show_motd_toggle" @if(session.show_motd !==false) checked @endif> <input type="checkbox" id="show_motd_toggle" @if(session.show_motd !==false) checked @endif>
+1 -1
View File
@@ -131,7 +131,7 @@
<button type="button" class="sidebar-tab" id="sidebar-tab-tag" data-tab="tag" title="Tag Feed" aria-label="Tag Feed" style="display: none;"> <button type="button" class="sidebar-tab" id="sidebar-tab-tag" data-tab="tag" title="Tag Feed" aria-label="Tag Feed" style="display: none;">
<i class="fa-solid fa-hashtag"></i> <i class="fa-solid fa-hashtag"></i>
</button> </button>
<button type="button" class="sidebar-tab" id="sidebar-tab-tuner" data-tab="tuner" title="Audio Reactivity Tuner" aria-label="Audio Reactivity Tuner"> <button type="button" class="sidebar-tab" id="sidebar-tab-tuner" data-tab="tuner" title="Tuner & Debug (Audio & Danmaku)" aria-label="Tuner & Debug (Audio & Danmaku)">
<i class="fa-solid fa-sliders"></i> <i class="fa-solid fa-sliders"></i>
</button> </button>
</div> </div>
+1 -1
View File
@@ -79,7 +79,7 @@
<i class="fa-solid fa-music"></i> <i class="fa-solid fa-music"></i>
</div> </div>
</div> </div>
<audio id="my-video" class="embed-responsive-item" preload="auto" loop src="{{ item.dest }}" data-setup="{}" data-size="{{ item.size }}" @if(item.coverart)poster="{{ item.coverart }}"@endif type="{{ item.mime }}"></audio> <audio id="my-video" class="embed-responsive-item" preload="auto" loop crossorigin="anonymous" src="{{ item.dest }}" data-setup="{}" data-size="{{ item.size }}" @if(item.coverart)poster="{{ item.coverart }}"@endif type="{{ item.mime }}"></audio>
<img id="f0ck-audio-cover" @if(item.coverart)src="{{ item.coverart }}"@endif style="display: none;"> <img id="f0ck-audio-cover" @if(item.coverart)src="{{ item.coverart }}"@endif style="display: none;">
</div> </div>
@elseif(item.mime.startsWith("image")) @elseif(item.mime.startsWith("image"))
+1 -1
View File
@@ -16,7 +16,7 @@
<span class="thumb-xd-indicator xd-tier-{{ item.xd_tier }}" title="xD Score: {{ item.xd_score }}">xD</span> <span class="thumb-xd-indicator xd-tier-{{ item.xd_tier }}" title="xD Score: {{ item.xd_score }}">xD</span>
@endif @endif
@if(item.is_album && item.album_count > 1) @if(item.is_album && item.album_count > 1)
<span class="album-indicator anim" title="Album: {{ item.album_count }} images"><i class="fa-solid fa-images"></i> {{ item.album_count }}</span> <span class="album-indicator" title="Album: {{ item.album_count }} images"><i class="fa-solid fa-images"></i> {{ item.album_count }}</span>
@endif @endif
</div> </div>
<div class="thumb-select-check"><i class="fa-solid fa-check"></i></div> <div class="thumb-select-check"><i class="fa-solid fa-check"></i></div>
+7
View File
@@ -173,6 +173,13 @@
</div> </div>
</div> </div>
<div class="form-section global-redirect-section">
<label class="checkbox-container upload-checkbox-label" style="display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: 0.9em; user-select: none; margin: 0;">
<input type="checkbox" id="upload-redirect-checkbox" name="redirect_to_item" class="upload-redirect-checkbox" checked>
<span><i class="fa-solid fa-arrow-up-right-from-square" style="opacity: 0.8; margin-right: 2px;"></i> {{ t('upload.redirect_to_item') }}</span>
</label>
</div>
<div class="form-actions"> <div class="form-actions">
<button type="submit" class="btn-upload" disabled> <button type="submit" class="btn-upload" disabled>
<span class="btn-text">{{ t('upload.select_file') }}</span> <span class="btn-text">{{ t('upload.select_file') }}</span>