fdsfsda
This commit is contained in:
+21
-13
@@ -295,6 +295,26 @@ export default new class {
|
||||
|
||||
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) {
|
||||
const isAnonymized = isAnonymizeSession(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}
|
||||
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 {
|
||||
tags = await db`
|
||||
select "tags".id, "tags".tag, "tags".normalized${hasSession ? db`, "user".user, uo.display_name` : db``}
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"comment_optional": "(optional)",
|
||||
"comment_placeholder": "Kommentar zum Upload hinzufügen...",
|
||||
"select_file": "Datei auswählen",
|
||||
"redirect_to_item": "Nach dem Upload zum Post weiterleiten",
|
||||
"uploading": "Wird hochgeladen...",
|
||||
"pending_approval_patient": "Upload wartet auf Freigabe, bitte haben Sie etwas Geduld",
|
||||
"remove_file": "Datei entfernen",
|
||||
@@ -348,7 +349,8 @@
|
||||
"label": "Fehler",
|
||||
"post_not_visible": "Dieser Beitrag ist derzeit leider nicht sichtbar.",
|
||||
"filter_hint": "Dein aktueller Filter ist auf {mode} gesetzt.",
|
||||
"filter_hint_link": "Um diesen Inhalt zu sehen, ändere deinen Filter entsprechend."
|
||||
"filter_hint_link": "Um diesen Inhalt zu sehen, ändere deinen Filter entsprechend.",
|
||||
"see_anyways": "Trotzdem ansehen"
|
||||
},
|
||||
"drop": {
|
||||
"drop_anywhere": "Überall ablegen zum Hochladen"
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"comment_optional": "(optional)",
|
||||
"comment_placeholder": "Add a comment to your upload...",
|
||||
"select_file": "Select a file",
|
||||
"redirect_to_item": "Redirect to item after upload",
|
||||
"uploading": "Uploading...",
|
||||
"pending_approval_patient": "Upload awaits approval, please be patient",
|
||||
"remove_file": "Remove File",
|
||||
@@ -348,7 +349,8 @@
|
||||
"label": "Error",
|
||||
"post_not_visible": "Sorry, this post is currently not visible.",
|
||||
"filter_hint": "Your current filter is set to {mode}.",
|
||||
"filter_hint_link": "To view this content, change your filter accordingly."
|
||||
"filter_hint_link": "To view this content, change your filter accordingly.",
|
||||
"see_anyways": "See anyways"
|
||||
},
|
||||
"drop": {
|
||||
"drop_anywhere": "Drop anywhere to upload"
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"comment_optional": "(optioneel)",
|
||||
"comment_placeholder": "Voeg een opmerking toe aan je upload...",
|
||||
"select_file": "Selecteer een bestand",
|
||||
"redirect_to_item": "Na het uploaden naar het item doorsturen",
|
||||
"uploading": "Uploaden...",
|
||||
"pending_approval_patient": "Upload wacht op goedkeuring, even geduld alstublieft",
|
||||
"remove_file": "Bestand Verwijderen",
|
||||
@@ -346,7 +347,8 @@
|
||||
"label": "Fout",
|
||||
"post_not_visible": "Sorry, deze post is momenteel niet zichtbaar.",
|
||||
"filter_hint": "Je huidige filter is ingesteld op {mode}.",
|
||||
"filter_hint_link": "Om deze inhoud te bekijken, pas je filter aan."
|
||||
"filter_hint_link": "Om deze inhoud te bekijken, pas je filter aan.",
|
||||
"see_anyways": "Toch bekijken"
|
||||
},
|
||||
"drop": {
|
||||
"drop_anywhere": "Overal slepen om te uploaden"
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"comment_optional": "(optional)",
|
||||
"comment_placeholder": "Fügen Sie Ihrer Aufladierung doch einen Kommentar hinzu...",
|
||||
"select_file": "Datei auswählen",
|
||||
"redirect_to_item": "Nach Pfostieren zum Pfosten weiterleiten",
|
||||
"uploading": "Wird aufladiert...",
|
||||
"pending_approval_patient": "Die Ladung harrt der Absegnung, bitte haben Sie Geduld",
|
||||
"remove_file": "Datei entfernen",
|
||||
@@ -344,7 +345,8 @@
|
||||
"label": "Fehler",
|
||||
"post_not_visible": "Bedauerlicher Weise ist dieser Pfosten derzeit nicht sichtbar.",
|
||||
"filter_hint": "Ihr aktueller Filter ist auf {mode} eingestellt.",
|
||||
"filter_hint_link": "Um diesen Inhalt zu betrachten, stellen Sie Ihren Filter entsprechend um."
|
||||
"filter_hint_link": "Um diesen Inhalt zu betrachten, stellen Sie Ihren Filter entsprechend um.",
|
||||
"see_anyways": "Dennoch betrachten"
|
||||
},
|
||||
"drop": {
|
||||
"drop_anywhere": "Überall ablegen zum Aufladieren"
|
||||
|
||||
+371
-107
@@ -8,9 +8,30 @@ import fs from "fs";
|
||||
import path from "path";
|
||||
import url from "url";
|
||||
|
||||
const getGlobalfilter = () => {
|
||||
const getGlobalfilter = (session) => {
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -175,7 +196,7 @@ function buildCountCacheKey({ modequery, tag, user, hall, mime, fav, session, ex
|
||||
hall ?? '',
|
||||
mime ?? '',
|
||||
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(','),
|
||||
newerThan ?? '',
|
||||
minXd,
|
||||
@@ -575,7 +596,7 @@ const f0cklib = {
|
||||
${mimeSQL}
|
||||
${hallFilter}
|
||||
${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``}
|
||||
${newerThan ? db`and items.id > ${newerThan}` : db``}
|
||||
${xdFilter}
|
||||
@@ -601,7 +622,7 @@ const f0cklib = {
|
||||
${mimeSQL}
|
||||
${hallFilter}
|
||||
${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``}
|
||||
${newerThan ? db`and items.id > ${newerThan}` : db``}
|
||||
${xdFilter}
|
||||
@@ -685,6 +706,28 @@ const f0cklib = {
|
||||
visibilityFilter
|
||||
} = 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 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 };
|
||||
@@ -709,7 +752,7 @@ const f0cklib = {
|
||||
${mimeSQL}
|
||||
${hallFilter}
|
||||
${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``}
|
||||
${newerThan ? db`and items.id > ${newerThan}` : db``}
|
||||
${xdFilter}
|
||||
@@ -753,7 +796,7 @@ const f0cklib = {
|
||||
${mimeSQL}
|
||||
${hallFilter}
|
||||
${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``}
|
||||
${newerThan ? db`and items.id > ${newerThan}` : db``}
|
||||
${xdFilter}
|
||||
@@ -821,12 +864,11 @@ const f0cklib = {
|
||||
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 terms = tag.split(',').map(t => t.trim()).filter(Boolean);
|
||||
if (terms.length > 0 && albumIds.length > 0) {
|
||||
if (albumIds.length > 0) {
|
||||
try {
|
||||
const matchingSubs = await db`
|
||||
const subItemsRows = await db`
|
||||
SELECT
|
||||
ai.item_id,
|
||||
ai.id as subf0ck_id,
|
||||
@@ -835,55 +877,135 @@ const f0cklib = {
|
||||
ai.mime as subf0ck_mime,
|
||||
ai.order_index
|
||||
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[])
|
||||
${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
|
||||
`;
|
||||
|
||||
const matchMap = new Map();
|
||||
for (const ms of matchingSubs) {
|
||||
if (!matchMap.has(ms.item_id)) {
|
||||
matchMap.set(ms.item_id, {
|
||||
first: ms,
|
||||
matchingIds: new Set([ms.subf0ck_id])
|
||||
});
|
||||
} else {
|
||||
matchMap.get(ms.item_id).matchingIds.add(ms.subf0ck_id);
|
||||
}
|
||||
const subIds = subItemsRows.map(s => s.subf0ck_id);
|
||||
const subTagsRows = subIds.length > 0 ? await db`
|
||||
SELECT aita.album_item_id, t.id, t.tag, t.normalized
|
||||
FROM album_items_tags_assign aita
|
||||
JOIN tags t ON t.id = aita.tag_id
|
||||
WHERE aita.album_item_id = ANY(${subIds}::int[])
|
||||
`.catch(() => []) : [];
|
||||
|
||||
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) {
|
||||
if (matchMap.has(row.id)) {
|
||||
const info = matchMap.get(row.id);
|
||||
const ms = info.first;
|
||||
row.target_subf0ck_slug = ms.subf0ck_slug || ms.subf0ck_id;
|
||||
if (ms.subf0ck_dest) {
|
||||
const subBase = ms.subf0ck_dest.replace(/\.[^.]+$/, '');
|
||||
row.thumb = `/t/${subBase}.webp`;
|
||||
row.matching_sub_thumb = `/t/${subBase}.webp`;
|
||||
row.matching_sub_dest = ms.subf0ck_dest;
|
||||
row.dest = ms.subf0ck_dest;
|
||||
if (!row.is_album || !subsByItemId.has(row.id)) continue;
|
||||
const subList = subsByItemId.get(row.id);
|
||||
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 (ms.subf0ck_mime) {
|
||||
row.matching_sub_mime = ms.subf0ck_mime;
|
||||
row.mime = ms.subf0ck_mime;
|
||||
|
||||
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;
|
||||
}
|
||||
const mCount = info.matchingIds.size;
|
||||
row.album_count = mCount;
|
||||
if (mCount <= 1) {
|
||||
row.is_album = false;
|
||||
|
||||
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;
|
||||
if (ms.subf0ck_dest) {
|
||||
const subBase = ms.subf0ck_dest.replace(/\.[^.]+$/, '');
|
||||
row.thumb = `/t/${subBase}.webp`;
|
||||
row.matching_sub_thumb = `/t/${subBase}.webp`;
|
||||
row.matching_sub_dest = ms.subf0ck_dest;
|
||||
row.dest = ms.subf0ck_dest;
|
||||
}
|
||||
if (ms.subf0ck_mime) {
|
||||
row.matching_sub_mime = ms.subf0ck_mime;
|
||||
row.mime = ms.subf0ck_mime;
|
||||
}
|
||||
visibleSubs = tagMatchingSubs;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
row.album_count = visibleSubs.length;
|
||||
if (visibleSubs.length <= 1) {
|
||||
row.is_album = false;
|
||||
}
|
||||
}
|
||||
} 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'
|
||||
};
|
||||
},
|
||||
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) {
|
||||
const { isPrivate, isAllowed } = await checkFavoritesAccess(rawUser, { session, user_id, is_admin });
|
||||
if (isPrivate && !isAllowed) {
|
||||
@@ -1029,6 +1151,21 @@ const f0cklib = {
|
||||
|
||||
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;
|
||||
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);
|
||||
|
||||
let tagFilter = db``;
|
||||
@@ -1089,7 +1226,7 @@ const f0cklib = {
|
||||
${!fav && user ? db`and items.username ilike ${user}` : db``}
|
||||
${idsFilter}
|
||||
${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``}
|
||||
`;
|
||||
};
|
||||
@@ -1180,16 +1317,17 @@ const f0cklib = {
|
||||
last_viewed = now()
|
||||
`.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)
|
||||
if (!session && (actitem.visibility || 0) === 0) {
|
||||
// Public visitor / guest rating restriction check for public items (unlisted items requested by direct link/slug bypass guest rating blocks)
|
||||
const isPublicVisitor = !session || !session.user || isAnonSession(session);
|
||||
if (isPublicVisitor && !isOwnerOrAdmin && (actitem.visibility || 0) === 0) {
|
||||
let blocked = false;
|
||||
if (getGlobalfilter()) {
|
||||
if (getGlobalfilter(session)) {
|
||||
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 (!blocked && !cfg.websrv.public_untagged) {
|
||||
if (!blocked && !session && !cfg.websrv.public_untagged) {
|
||||
const ratingTag = await db`
|
||||
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)
|
||||
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) => {
|
||||
return db`
|
||||
@@ -1244,7 +1382,7 @@ const f0cklib = {
|
||||
const useTagIdOpt = !mimeParts.includes('audio');
|
||||
|
||||
const nsfpIds = cfg.nsfp || [];
|
||||
const checkFilter = !session && nsfpIds.length > 0;
|
||||
const checkFilter = (!session || isAnonSession(session)) && nsfpIds.length > 0;
|
||||
|
||||
const query = db`
|
||||
SELECT ta.item_id as id, items.slug
|
||||
@@ -1305,13 +1443,27 @@ const f0cklib = {
|
||||
link.suffix = '';
|
||||
}
|
||||
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"
|
||||
left join "user" on "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}
|
||||
`;
|
||||
|
||||
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}`
|
||||
// Find all items (including this one) that share the same base checksum.
|
||||
let repostItems = [];
|
||||
@@ -1355,27 +1507,21 @@ const f0cklib = {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Efficient coverart fallback with on-demand extraction
|
||||
let hasCoverart = actitem.has_coverart;
|
||||
if (!hasCoverart && actitem.mime?.startsWith('audio/')) {
|
||||
const caPath = path.join(cfg.paths.ca, `${actitem.id}.webp`);
|
||||
let hasCoverart = false;
|
||||
if (actitem.mime && actitem.mime.startsWith('audio/')) {
|
||||
try {
|
||||
const caPath = path.join(cfg.paths.ca, `${actitem.id}.webp`);
|
||||
if (fs.existsSync(caPath) && fs.statSync(caPath).size > 0) {
|
||||
hasCoverart = true;
|
||||
db`UPDATE items SET has_coverart = TRUE WHERE id = ${actitem.id}`.catch(() => {});
|
||||
} else {
|
||||
// Attempt extraction directly from audio file if embedded
|
||||
const sourcePath = path.join(cfg.paths.b, actitem.dest);
|
||||
if (fs.existsSync(sourcePath)) {
|
||||
await queue.spawn('ffmpeg', ['-y', '-i', sourcePath, '-an', '-vcodec', 'webp', '-frames:v', '1', caPath], { quiet: true }).catch(() => {});
|
||||
// On-demand cover art extraction fallback
|
||||
const audioFile = path.join(cfg.paths.b, actitem.dest);
|
||||
if (fs.existsSync(audioFile)) {
|
||||
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) {
|
||||
hasCoverart = true;
|
||||
db`UPDATE items SET has_coverart = TRUE WHERE id = ${actitem.id}`.catch(() => {});
|
||||
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 }).catch(() => {});
|
||||
}
|
||||
await queue.spawn('magick', [caPath + '[0]', '-resize', '256x256^', '-gravity', 'center', '-crop', '256x256+0+0', '+repage', tPath], { quiet: true });
|
||||
} else {
|
||||
try { fs.unlinkSync(caPath); } catch (_) {}
|
||||
}
|
||||
@@ -1416,11 +1562,8 @@ const f0cklib = {
|
||||
if (tag && !isTitleSearch) {
|
||||
const terms = tag.split(',').map(t => t.trim()).filter(Boolean);
|
||||
if (terms.length > 0 && tagsBySubId.size > 0) {
|
||||
const matching = albumRows.filter((r, idx) => {
|
||||
const matching = albumRows.filter((r) => {
|
||||
let st = tagsBySubId.get(r.id) || [];
|
||||
if (st.length === 0 && (r.order_index === 0 || idx === 0)) {
|
||||
st = tags;
|
||||
}
|
||||
if (isStrict) {
|
||||
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) => {
|
||||
const order = idx;
|
||||
const subSlug = r.slug || r.id;
|
||||
@@ -1503,9 +1728,6 @@ const f0cklib = {
|
||||
}
|
||||
|
||||
let subTags = tagsBySubId.get(r.id) || [];
|
||||
if (subTags.length === 0 && (r.order_index === 0 || idx === 0)) {
|
||||
subTags = tags;
|
||||
}
|
||||
|
||||
return {
|
||||
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));
|
||||
if (found !== -1) {
|
||||
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) {
|
||||
effectiveItemTags = targetSub.tags;
|
||||
if (!effectiveItemTags.some(t => t.id === 1 || t.id === 2 || t.normalized === 'nsfl')) {
|
||||
const ratingTag = tags.find(t => t.id === 1 || t.id === 2 || t.normalized === 'nsfl');
|
||||
if (ratingTag) {
|
||||
effectiveItemTags = [ratingTag, ...effectiveItemTags];
|
||||
}
|
||||
}
|
||||
} else if (reqIdx === 0) {
|
||||
effectiveItemTags = tags;
|
||||
} else {
|
||||
effectiveItemTags = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1577,7 +1812,7 @@ const f0cklib = {
|
||||
const duration = Date.now() - startTime;
|
||||
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 isSfw = effectiveItemTags.some(t => t.id == 1);
|
||||
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:
|
||||
// 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) {
|
||||
if (anonBlocked) {
|
||||
const hallSlug = hall && typeof hall === 'object' ? hall.slug : hall;
|
||||
return {
|
||||
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) {
|
||||
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));
|
||||
@@ -1796,7 +2060,7 @@ const f0cklib = {
|
||||
AND items.title ILIKE ${'%' + titleQuery + '%'}
|
||||
AND items.title IS NOT NULL
|
||||
${mimeSQL}
|
||||
${!session && getGlobalfilter() ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(getGlobalfilter())}))` : db``}
|
||||
${(!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``}
|
||||
ORDER BY random()
|
||||
LIMIT 1
|
||||
@@ -1817,7 +2081,7 @@ const f0cklib = {
|
||||
and items.active = true
|
||||
and coalesce(items.visibility, 0) = 0
|
||||
${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
|
||||
order by random()
|
||||
limit 1
|
||||
@@ -1860,7 +2124,7 @@ const f0cklib = {
|
||||
${user ? db`and items.username ilike ${user}` : db``}
|
||||
${hall ? db`and items.id in (select item_id from halls_assign ha join halls h on h.id = ha.hall_id where h.slug = ${hall})` : db``}
|
||||
${mimeSQL}
|
||||
${!session && 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``}
|
||||
group by items.id, tags.tag
|
||||
order by random()
|
||||
@@ -1880,7 +2144,7 @@ const f0cklib = {
|
||||
and items.active = true
|
||||
and coalesce(items.visibility, 0) = 0
|
||||
${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``}
|
||||
order by random()
|
||||
limit 1
|
||||
@@ -1906,13 +2170,13 @@ const f0cklib = {
|
||||
// When multi-rating SQL is active, use it directly. Otherwise use the tag-join optimisation.
|
||||
const globalModeQuery = modequery;
|
||||
// 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))
|
||||
: null;
|
||||
// If audio is included, we avoid the strict tagId optimization to ensure audio is visible
|
||||
const useTagIdOpt = tagId && !mimeParts.includes('audio');
|
||||
const nsfpIds = cfg.nsfp || [];
|
||||
const checkFilter = !session && nsfpIds.length > 0;
|
||||
const checkFilter = (!session || isAnonSession(session)) && nsfpIds.length > 0;
|
||||
|
||||
// Use a single uniform query with ORDER BY random()
|
||||
// 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 } = {}) => {
|
||||
const ratingsArr = (Array.isArray(ratings) && ratings.length > 0) ? ratings : null;
|
||||
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 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 modequery = computeBaseMode(mode, ratingsArr, session);
|
||||
const globalfilter = !session ? getGlobalfilter() : null;
|
||||
const globalfilter = (!session || isAnonSession(session)) ? getGlobalfilter(session) : null;
|
||||
const excludedTags = session && exclude ? (exclude || []) : [];
|
||||
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 modequery = computeBaseMode(mode, ratingsArr, session);
|
||||
const globalfilter = !session ? getGlobalfilter() : null;
|
||||
const globalfilter = (!session || isAnonSession(session)) ? getGlobalfilter(session) : null;
|
||||
const excludedTags = session && exclude ? (exclude || []) : [];
|
||||
const maxLimit = Math.min(Math.max(1, Number(limit) || 20), 50);
|
||||
const numOffset = Math.max(0, Number(offset) || 0);
|
||||
|
||||
+26
-3
@@ -1,4 +1,5 @@
|
||||
import f0cklib from "../routeinc/f0cklib.mjs";
|
||||
import lib from "../lib.mjs";
|
||||
import url from "url";
|
||||
import cfg from "../config.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 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({
|
||||
itemid: itemid,
|
||||
mode: reqMode,
|
||||
ratings: ratingsArr,
|
||||
bypass_filter: bypassFilter,
|
||||
session: req.session,
|
||||
url: contextUrl,
|
||||
user: query.user,
|
||||
@@ -67,15 +70,18 @@ export default (router, tpl) => {
|
||||
if (!data.success) {
|
||||
const reqMode = (query.mode !== undefined ? +query.mode : req.mode) ?? 0;
|
||||
const modeLabels = { 0: 'SFW', 1: 'NSFW', 2: 'Untagged', 4: 'NSFL' };
|
||||
const errorModeLabel = (req.session && reqMode !== 3) ? (modeLabels[reqMode] || null) : null;
|
||||
const errorModeLabel = reqMode !== 3 ? (modeLabels[reqMode] || 'SFW') : null;
|
||||
const { t: tErr } = createI18n(req.session?.language || req.lang || 'en');
|
||||
const errorHtml = tpl.render('error-partial', {
|
||||
message: tErr('error.post_not_visible'),
|
||||
tmp: null,
|
||||
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_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);
|
||||
return res.reply({
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -161,12 +167,29 @@ export default (router, tpl) => {
|
||||
data.uploader.id = 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_')))));
|
||||
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_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.user_halls_slugs = Array.isArray(item.user_halls) ? item.user_halls.map(h => h.slug).join(',') : '';
|
||||
// Precomputed for template engine compatibility (avoids nested { } inside {{ }})
|
||||
|
||||
+102
-17
@@ -2,7 +2,7 @@ import { promises as fs } from "fs";
|
||||
import db from '../../sql.mjs';
|
||||
import lib from '../../lib.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 search from '../../routeinc/search.mjs';
|
||||
import path from "path";
|
||||
@@ -15,9 +15,27 @@ import { addPrivateItem, removePrivateItem, addUnavailableItem, removeUnavailabl
|
||||
import { logAnonActivity } from '../../anon_auth.mjs';
|
||||
|
||||
const allowedMimes = ["audio", "image", "video", "%"];
|
||||
const getGlobalfilter = () => {
|
||||
const getGlobalfilter = (session) => {
|
||||
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;
|
||||
};
|
||||
const metaCache = new Map();
|
||||
@@ -385,11 +403,10 @@ export default router => {
|
||||
originalFilename = rows[0].original_filename || '';
|
||||
} else {
|
||||
const subRows = isNumeric
|
||||
? await db`SELECT dest, original_filename FROM sub_items WHERE id = ${itemId}`
|
||||
: await db`SELECT dest, original_filename FROM sub_items WHERE slug = ${itemId}`;
|
||||
? await db`SELECT dest FROM album_items WHERE id = ${+itemId}`
|
||||
: await db`SELECT dest FROM album_items WHERE slug = ${itemId}`;
|
||||
if (subRows && subRows[0]) {
|
||||
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
|
||||
active = true
|
||||
${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``}
|
||||
${opt.older
|
||||
? db`and id <= ${opt.older}`
|
||||
@@ -1175,7 +1193,7 @@ export default router => {
|
||||
atStart: rows.length > 0 && rows[rows.length - 1].id === oldest,
|
||||
success: true,
|
||||
items: rows
|
||||
}, 200);
|
||||
});
|
||||
});
|
||||
|
||||
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 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);
|
||||
|
||||
let guestTagFilter = db``;
|
||||
if (!session) {
|
||||
if (isPublicVisitor) {
|
||||
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
|
||||
if (cfg.websrv.public_nsfw) {
|
||||
guestTagFilter = db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id = ${nsflId})`;
|
||||
} else {
|
||||
guestTagFilter = db`and not exists (select 1 from tags_assign where item_id = items.id and tag_id in (2, ${nsflId}))`;
|
||||
const isAnon = session && isAnonSession(session);
|
||||
const anonModes = isAnon ? getAnonAllowedModes() : [];
|
||||
const allowNsfw = isAnon ? anonModes.includes('nsfw') : cfg.websrv.public_nsfw;
|
||||
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``;
|
||||
if (effMode === 2) {
|
||||
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`
|
||||
select id
|
||||
from "items"
|
||||
where id > ${id} and active = true ${visibilityFilter} ${guestTagFilter} ${modeCondition}
|
||||
where id > ${id} and active = true ${visibilityFilter} ${guestTagFilter} ${globalFilterCondition} ${modeCondition}
|
||||
order by id
|
||||
limit 1
|
||||
`;
|
||||
const prev = await db`
|
||||
select id
|
||||
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
|
||||
limit 1
|
||||
`;
|
||||
@@ -1581,6 +1621,7 @@ export default router => {
|
||||
limit 1
|
||||
`;
|
||||
|
||||
let favorited = false;
|
||||
if (existing.length > 0) {
|
||||
// del fav
|
||||
await db`
|
||||
@@ -1588,6 +1629,7 @@ export default router => {
|
||||
where user_id = ${+req.session.id}
|
||||
and item_id = ${+postid}
|
||||
`;
|
||||
favorited = false;
|
||||
f0cklib.updateUserAffinity({ user_id: req.session.id, item_id: +postid, scoreDelta: -5.0 }).catch(() => {});
|
||||
if (req.session?.is_anon) {
|
||||
await logAnonActivity(req, { action: 'unfavorite', targetId: postid });
|
||||
@@ -1601,6 +1643,7 @@ export default router => {
|
||||
}, 'item_id', 'user_id')}
|
||||
on conflict do nothing
|
||||
`;
|
||||
favorited = true;
|
||||
f0cklib.updateUserAffinity({ user_id: req.session.id, item_id: +postid, scoreDelta: 5.0 }).catch(() => {});
|
||||
if (req.session?.is_anon) {
|
||||
await logAnonActivity(req, { action: 'favorite', targetId: postid });
|
||||
@@ -1608,23 +1651,65 @@ export default router => {
|
||||
}
|
||||
|
||||
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"
|
||||
left join "user" on "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}
|
||||
`;
|
||||
|
||||
// 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
|
||||
db.notify('favorites', JSON.stringify({
|
||||
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({
|
||||
success: true,
|
||||
itemid: postid,
|
||||
favs
|
||||
favorited: favorited,
|
||||
favs: clientFavs
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { promises as fs } from "fs";
|
||||
import { applyWordFilter } from "../wordfilter.mjs";
|
||||
import path from "path";
|
||||
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) => {
|
||||
|
||||
@@ -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 excludedTags = req.session ? (req.session.excluded_tags || []) : [];
|
||||
/* <mode-override> */
|
||||
@@ -198,7 +206,7 @@ export default (router, tpl) => {
|
||||
WHERE c.user_id = ${userId} AND c.is_deleted = false
|
||||
AND i.active = true AND i.is_deleted = false
|
||||
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``}
|
||||
ORDER BY c.created_at DESC
|
||||
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
|
||||
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 excludedTags = req.session ? (req.session.excluded_tags || []) : [];
|
||||
|
||||
@@ -1134,7 +1150,7 @@ export default (router, tpl) => {
|
||||
${activityMimeSQL}
|
||||
${visibilityFilter}
|
||||
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``}
|
||||
|
||||
ORDER BY c.created_at DESC
|
||||
|
||||
@@ -265,6 +265,8 @@ export default (router, tpl) => {
|
||||
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)({
|
||||
user: req.params.user,
|
||||
tag: reqTag,
|
||||
@@ -274,6 +276,7 @@ export default (router, tpl) => {
|
||||
hall: req.params.hall,
|
||||
fav: req.params.mode == 'favs',
|
||||
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; })(),
|
||||
session: req.session,
|
||||
user_id: req.session?.id,
|
||||
@@ -333,19 +336,22 @@ export default (router, tpl) => {
|
||||
const statusCode = data.item ? 200 : 404;
|
||||
const reqMode = req.mode ?? 0;
|
||||
const modeLabels = { 0: 'SFW', 1: 'NSFW', 2: 'Untagged', 4: 'NSFL' };
|
||||
const errorModeLabel = (req.session && reqMode !== 3) ? (modeLabels[reqMode] || null) : null;
|
||||
const errorModeLabel = reqMode !== 3 ? (modeLabels[reqMode] || 'SFW') : null;
|
||||
const { t: tErr } = createI18n(req.session?.language || req.lang || 'en');
|
||||
return res.reply({
|
||||
code: statusCode,
|
||||
body: tpl.render('error', {
|
||||
message: tErr('error.post_not_visible'),
|
||||
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,
|
||||
tmp: null,
|
||||
session: req.session ? { ...req.session } : false,
|
||||
error_mode_label: errorModeLabel,
|
||||
error_filter_hint: errorModeLabel ? tErr('error.filter_hint', { mode: `<strong>${errorModeLabel}</strong>` }) : null,
|
||||
error_filter_hint_link: tErr('error.filter_hint_link')
|
||||
error_filter_hint_link: tErr('error.filter_hint_link'),
|
||||
error_see_anyways: tErr('error.see_anyways')
|
||||
}, req)
|
||||
});
|
||||
}
|
||||
@@ -420,7 +426,7 @@ export default (router, tpl) => {
|
||||
// YouTube items use oEmbed via /meta/fetch; all non-flash MIME types are eligible.
|
||||
data.can_extract_meta = !!(item.mime && item.mime.indexOf('flash') === -1 && !(item.mime.startsWith('application/') && cfg.mimes[item.mime] && !['swf', 'pdf'].includes(cfg.mimes[item.mime])));
|
||||
// Has the current user favorited this item?
|
||||
data.user_has_favorited = !!(session && Array.isArray(item.favorites) && item.favorites.some(f => f.user === session.user));
|
||||
data.user_has_favorited = lib.userHasFavorited(session, item.favorites);
|
||||
// Hall columns for display
|
||||
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(',') : '';
|
||||
@@ -442,6 +448,23 @@ export default (router, tpl) => {
|
||||
data.uploader.id = 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 {{ }})
|
||||
data.item_rating_class = item.is_nsfl ? 'is-nsfl' : (item.is_nsfw ? 'is-nsfw' : (item.is_sfw ? 'is-sfw' : 'is-untagged'));
|
||||
|
||||
@@ -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`;
|
||||
|
||||
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 });
|
||||
|
||||
// Notify User (WebSocket/Internal)
|
||||
@@ -375,6 +378,7 @@ export default (router, tpl) => {
|
||||
const reason = req.post?.reason || "Denied by moderator";
|
||||
|
||||
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
|
||||
let uploaderId = null;
|
||||
@@ -550,6 +554,7 @@ export default (router, tpl) => {
|
||||
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 notifications SET is_read = true WHERE type = 'admin_pending' AND item_id = ${+id}`.catch(() => {});
|
||||
// Fetch uploader details for audit log
|
||||
let uploaderInfo = {};
|
||||
try {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import db from "../sql.mjs";
|
||||
import f0cklib from "../routeinc/f0cklib.mjs";
|
||||
import cfg from "../config.mjs";
|
||||
import { getEnableItemSlugs } from "../settings.mjs";
|
||||
import { getEnableItemSlugs, isAnonymizeSession } from "../settings.mjs";
|
||||
import { setMotd } from "../motd.mjs";
|
||||
import security from "../security.mjs";
|
||||
|
||||
@@ -268,9 +268,37 @@ db.listen('favorites', async (payload) => {
|
||||
try {
|
||||
const data = JSON.parse(payload);
|
||||
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) {
|
||||
client.send({ type: 'favorites', data });
|
||||
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 });
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Favorite broadcast error:', e);
|
||||
@@ -445,6 +473,10 @@ db.listen('global_chat_topic', (payload) => {
|
||||
|
||||
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 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_options uo ON u.id = uo.user_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
|
||||
AND (n.type IN ('admin_pending', 'deny', 'item_deleted', 'report', 'approve', 'warning')
|
||||
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.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
|
||||
LIMIT 1000
|
||||
`;
|
||||
@@ -677,6 +712,8 @@ export default (router, tpl) => {
|
||||
|
||||
const client = {
|
||||
userId: clientUserId,
|
||||
session: req.session || null,
|
||||
isAnonymized: isAnonymizeSession(req.session),
|
||||
fingerprint: clientFp,
|
||||
hwFingerprint: clientHw,
|
||||
username: req.session?.user || null,
|
||||
|
||||
@@ -188,6 +188,13 @@ export default (router, tpl) => {
|
||||
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 });
|
||||
|
||||
return res.json({ success: true, msg: `Report marked as ${action}.` });
|
||||
|
||||
@@ -2,7 +2,7 @@ import cfg from "../config.mjs";
|
||||
import db from "../sql.mjs";
|
||||
import lib from "../lib.mjs";
|
||||
import f0cklib from "../routeinc/f0cklib.mjs";
|
||||
import { isAnonymizeSession } from "../settings.mjs";
|
||||
import { isAnonymizeSession, isAnonSession } from "../settings.mjs";
|
||||
|
||||
export default (router, tpl) => {
|
||||
// Serve the scroller page
|
||||
@@ -265,7 +265,7 @@ export default (router, tpl) => {
|
||||
${excludeSwfSQL}
|
||||
${excludePdfSQL}
|
||||
${excludeArchiveSQL}
|
||||
${!req.session && nsfp ? db`AND NOT EXISTS (SELECT 1 FROM tags_assign WHERE item_id = items.id AND (${db.unsafe(nsfp)}))` : db``}
|
||||
${(!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.
|
||||
// Return empty so the frontend shows "This post is currently unavailable".
|
||||
@@ -288,7 +288,7 @@ export default (router, tpl) => {
|
||||
${excludeSQL}
|
||||
${mimeSQL}
|
||||
${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``}
|
||||
ORDER BY random()
|
||||
LIMIT ${limit - 1}
|
||||
@@ -313,7 +313,7 @@ export default (router, tpl) => {
|
||||
${excludeSQL}
|
||||
${mimeSQL}
|
||||
${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``}
|
||||
${orderSQL}
|
||||
LIMIT ${limit}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import db from "../../inc/sql.mjs";
|
||||
import lib from "../../inc/lib.mjs";
|
||||
import cfg from "../../inc/config.mjs";
|
||||
import { isAnonSession, getAnonAllowedModes } from "../settings.mjs";
|
||||
import url from "url";
|
||||
|
||||
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 excludedTags = sessionObj ? (sessionObj.excluded_tags || []) : [];
|
||||
const isGuest = !sessionObj;
|
||||
const isPublicVisitor = !sessionObj || isAnonSession(sessionObj);
|
||||
let baseMode = lib.getMode(mode);
|
||||
if (isGuest) {
|
||||
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
|
||||
@@ -29,15 +31,26 @@ export default (router, tpl) => {
|
||||
const modequery = baseMode;
|
||||
|
||||
let restrictedFilter = db``;
|
||||
if (isGuest && cfg.nsfp && cfg.nsfp.length > 0) {
|
||||
restrictedFilter = db`
|
||||
AND t.id NOT IN ${db(cfg.nsfp)}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM tags_assign ta_res
|
||||
WHERE ta_res.item_id = items.id
|
||||
AND ta_res.tag_id IN ${db(cfg.nsfp)}
|
||||
)
|
||||
`;
|
||||
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`
|
||||
AND t.id NOT IN ${db(effectiveNsfp)}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM tags_assign ta_res
|
||||
WHERE ta_res.item_id = items.id
|
||||
AND ta_res.tag_id IN ${db(effectiveNsfp)}
|
||||
)
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const userExcludeFilter = excludedTags.length > 0
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import db from "../sql.mjs";
|
||||
import cfg from "../config.mjs";
|
||||
import lib from "../lib.mjs";
|
||||
import { isAnonymizeSession } from "../settings.mjs";
|
||||
import f0cklib from "../routeinc/f0cklib.mjs";
|
||||
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.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.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.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'));
|
||||
@@ -204,6 +205,23 @@ export default (router, tpl) => {
|
||||
data.uploader.id = 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
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import db from "../../inc/sql.mjs";
|
||||
import lib from "../../inc/lib.mjs";
|
||||
import cfg from "../../inc/config.mjs";
|
||||
import { isAnonymizeSession } from "../settings.mjs";
|
||||
import { isAnonymizeSession, isAnonSession, getAnonAllowedModes } from "../settings.mjs";
|
||||
import url from "url";
|
||||
|
||||
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 excludedTags = sessionObj ? (sessionObj.excluded_tags || []) : [];
|
||||
const isGuest = !sessionObj;
|
||||
const isPublicVisitor = !sessionObj || isAnonSession(sessionObj);
|
||||
let baseMode = lib.getMode(mode);
|
||||
if (isGuest) {
|
||||
const nsflId = parseInt(cfg.nsfl_tag_id, 10) || 3;
|
||||
@@ -30,15 +31,26 @@ export default (router, tpl) => {
|
||||
const modequery = baseMode;
|
||||
|
||||
let restrictedFilter = db``;
|
||||
if (isGuest && cfg.nsfp && cfg.nsfp.length > 0) {
|
||||
restrictedFilter = db`
|
||||
AND t.id NOT IN ${db(cfg.nsfp)}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM tags_assign ta_res
|
||||
WHERE ta_res.item_id = items.id
|
||||
AND ta_res.tag_id IN ${db(cfg.nsfp)}
|
||||
)
|
||||
`;
|
||||
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`
|
||||
AND t.id NOT IN ${db(effectiveNsfp)}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM tags_assign ta_res
|
||||
WHERE ta_res.item_id = items.id
|
||||
AND ta_res.tag_id IN ${db(effectiveNsfp)}
|
||||
)
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const userExcludeFilter = excludedTags.length > 0
|
||||
|
||||
Reference in New Issue
Block a user