feat: 新增用户屏蔽功能
屏蔽为单向关系:A 屏蔽 B 之后 - B 不能再给 A 发私信(含已有会话,以及发起新会话) - A 在帖子列表、帖子搜索、帖子详情回复中不再看到 B 的内容 - A 的用户搜索中不再出现 B - B 不会收到任何提示,仍可正常浏览 A 的公开内容 取消屏蔽后全部恢复。 数据层(迁移 006) - 新增 user_blocks 表,唯一约束 (blocker_id, blocked_id),并加 CHECK 禁止屏蔽自己;两个方向各建索引(正向用于过滤内容, 反向用于判断能否发私信)。 后端 - 新增 POST / DELETE /api/users/:id/block、GET /api/blocks、 GET /api/users/:id/block-status。block-status 返回双向关系, 便于界面准确提示。 - 新增 optionalAuth 中间件:公开接口(帖子列表、搜索、详情、回复) 在已登录时解析出 req.user 并应用屏蔽过滤,未登录或令牌无效时 直接放行。这样未登录访客看到全部内容,登录用户则按自己的屏蔽 列表过滤。 - 帖子列表的 count 与主查询改为共用同一套 WHERE 条件——此前两者 分别拼装,加上过滤后若不一致会导致分页总数与实际结果对不上。 - 帖子搜索的关键词条件补上括号:它与屏蔽过滤之间是 AND 关系, 而 AND 优先级高于 OR,不加括号会让过滤失效。 - 私信发送与会话创建均校验对方是否屏蔽了自己,返回中性提示 「无法向该用户发送消息」,不透露被屏蔽的事实。 前端 - 用户主页新增屏蔽按钮,按当前状态显示「屏蔽」或「解除屏蔽」; 已屏蔽时隐藏发私信入口(避免必然失败的尝试),并显示状态说明。 - 私信面板新增「会话 / 已屏蔽」切换,已屏蔽列表可逐个解除。 - 私信搜索结果行新增屏蔽按钮,点击时阻止冒泡以免进入聊天。 - 屏蔽与解除都需要二次确认,文案说明后果。 实测: - 屏蔽前后对比:对方帖子由可见 1 条变为 0 条,用户搜索由 1 个 变为 0 个,对方发起会话被拒 - 解除屏蔽后帖子恢复可见 - 不能屏蔽自己 - 界面:用户主页按钮文案与提示随状态变化,私信面板两个 Tab 正常, 已屏蔽列表显示用户与屏蔽时间 完整测试套件 25/25 通过。
This commit is contained in:
1 parent
5995efc7a0
commit
7c66cb931a
9 files changed
+550
-35
No files matched your search
@@ -492,6 +492,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="dm-view-switch">
|
||||
<button type="button" id="dmTabConversations" class="active">会话</button>
|
||||
<button type="button" id="dmTabBlocked">已屏蔽</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
|
||||
@@ -281,6 +281,33 @@ const API = {
|
||||
return data.data || [];
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 用户屏蔽
|
||||
// ============================================================
|
||||
async blockUser(userId) {
|
||||
const data = await apiFetch('/users/' + userId + '/block', { method: 'POST' });
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async unblockUser(userId) {
|
||||
const data = await apiFetch('/users/' + userId + '/block', { method: 'DELETE' });
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async getBlockedUsers() {
|
||||
const data = await apiFetch('/blocks');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data.data || [];
|
||||
},
|
||||
|
||||
async getBlockStatus(userId) {
|
||||
const data = await apiFetch('/users/' + userId + '/block-status');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async getOrCreateConversation(other_user_id) {
|
||||
const data = await apiFetch('/conversations', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -440,10 +440,14 @@ async function updateUnreadBadge() {
|
||||
|
||||
function openMessageList() {
|
||||
document.getElementById('messageListModal').classList.add('active');
|
||||
// 每次打开都回到会话列表状态,避免上次的搜索词残留
|
||||
// 每次打开都回到会话列表状态,避免上次的搜索词或「已屏蔽」视图残留
|
||||
const searchInput = document.getElementById('dmUserSearchInput');
|
||||
if (searchInput) searchInput.value = '';
|
||||
syncDmSearchClear();
|
||||
const tabConv = document.getElementById('dmTabConversations');
|
||||
const tabBlocked = document.getElementById('dmTabBlocked');
|
||||
if (tabConv) tabConv.classList.add('active');
|
||||
if (tabBlocked) tabBlocked.classList.remove('active');
|
||||
renderMessageList();
|
||||
}
|
||||
|
||||
@@ -491,12 +495,38 @@ async function renderDmUserSearch(keyword) {
|
||||
<div class="dm-user-name">${escapeHTML(u.username)}</div>
|
||||
<div class="dm-user-hint">${escapeHTML(u.signature || '点击发送私信')}</div>
|
||||
</div>
|
||||
<button type="button" class="dm-user-block" data-user-id="${escapeHTML(u.id)}"
|
||||
data-username="${escapeHTML(u.username)}" title="屏蔽该用户">屏蔽</button>
|
||||
<span class="dm-user-action">私信</span>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
container.innerHTML = sanitizeHTML(html);
|
||||
|
||||
// 屏蔽按钮:需与行点击区分开,因此阻止冒泡
|
||||
container.querySelectorAll('.dm-user-block').forEach(btn => {
|
||||
btn.addEventListener('click', async function(e) {
|
||||
e.stopPropagation();
|
||||
const userId = this.dataset.userId;
|
||||
const username = this.dataset.username;
|
||||
|
||||
const ok = await showConfirm(
|
||||
`确定屏蔽「${username}」?屏蔽后你不再看到 TA 的帖子和回复,TA 也无法给你发私信。`,
|
||||
{ title: '屏蔽用户', confirmText: '屏蔽', danger: true }
|
||||
);
|
||||
if (!ok) return;
|
||||
|
||||
try {
|
||||
await API.blockUser(userId);
|
||||
showToast('已屏蔽该用户', 'success');
|
||||
// 屏蔽后该用户不应再出现于搜索结果中,重新执行一次搜索
|
||||
renderDmUserSearch(document.getElementById('dmUserSearchInput').value);
|
||||
} catch (err) {
|
||||
showToast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
container.querySelectorAll('.dm-user-row').forEach(row => {
|
||||
row.addEventListener('click', async function() {
|
||||
const userId = this.dataset.userId;
|
||||
@@ -558,6 +588,86 @@ async function renderDmUserSearch(keyword) {
|
||||
}
|
||||
})();
|
||||
|
||||
// 渲染「已屏蔽」列表
|
||||
async function renderBlockedUsers() {
|
||||
const container = document.getElementById('messageListContent');
|
||||
container.innerHTML = '<div class="dm-search-status">加载中…</div>';
|
||||
|
||||
try {
|
||||
const users = await API.getBlockedUsers();
|
||||
if (users.length === 0) {
|
||||
container.innerHTML = '<div class="dm-search-status">还没有屏蔽任何人</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
users.forEach(u => {
|
||||
const avatar = u.avatar_url ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64';
|
||||
html += `
|
||||
<div class="dm-user-row" style="cursor:default;">
|
||||
<img src="${escapeHTML(safeURL(avatar, { image: true }))}" alt="" />
|
||||
<div class="dm-user-info">
|
||||
<div class="dm-user-name">${escapeHTML(u.username)}</div>
|
||||
<div class="dm-user-hint">屏蔽于 ${u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '未知'}</div>
|
||||
</div>
|
||||
<button type="button" class="dm-user-unblock"
|
||||
data-user-id="${escapeHTML(u.id)}" data-username="${escapeHTML(u.username)}">解除屏蔽</button>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
container.innerHTML = sanitizeHTML(html);
|
||||
|
||||
container.querySelectorAll('.dm-user-unblock').forEach(btn => {
|
||||
btn.addEventListener('click', async function() {
|
||||
const userId = this.dataset.userId;
|
||||
const username = this.dataset.username;
|
||||
|
||||
const ok = await showConfirm(
|
||||
`解除对「${username}」的屏蔽?解除后你将继续看到 TA 的帖子和回复,TA 也能再次给你发私信。`,
|
||||
{ title: '解除屏蔽', confirmText: '解除屏蔽' }
|
||||
);
|
||||
if (!ok) return;
|
||||
|
||||
try {
|
||||
await API.unblockUser(userId);
|
||||
showToast('已解除屏蔽', 'success');
|
||||
renderBlockedUsers();
|
||||
} catch (err) {
|
||||
showToast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
container.innerHTML = '<div class="dm-search-status">加载失败</div>';
|
||||
}
|
||||
}
|
||||
|
||||
// 视图切换:会话 / 已屏蔽
|
||||
function switchDmView(view) {
|
||||
const tabConv = document.getElementById('dmTabConversations');
|
||||
const tabBlocked = document.getElementById('dmTabBlocked');
|
||||
if (tabConv) tabConv.classList.toggle('active', view === 'conversations');
|
||||
if (tabBlocked) tabBlocked.classList.toggle('active', view === 'blocked');
|
||||
|
||||
// 切到已屏蔽时清空搜索框,避免搜索状态与列表视图混淆
|
||||
const input = document.getElementById('dmUserSearchInput');
|
||||
if (view === 'blocked' && input) {
|
||||
input.value = '';
|
||||
syncDmSearchClear();
|
||||
}
|
||||
|
||||
if (view === 'blocked') renderBlockedUsers();
|
||||
else renderMessageList();
|
||||
}
|
||||
|
||||
(function initDmTabs() {
|
||||
const tabConv = document.getElementById('dmTabConversations');
|
||||
const tabBlocked = document.getElementById('dmTabBlocked');
|
||||
if (tabConv) tabConv.addEventListener('click', () => switchDmView('conversations'));
|
||||
if (tabBlocked) tabBlocked.addEventListener('click', () => switchDmView('blocked'));
|
||||
})();
|
||||
|
||||
function closeMessageList() {
|
||||
closeModal(document.getElementById('messageListModal'));
|
||||
if (messagePollInterval) {
|
||||
|
||||
+24
@@ -372,6 +372,18 @@ const TRANSLATIONS = {
|
||||
'重新生成恢复码': '重新生成恢复码',
|
||||
'退出登录': '退出登录',
|
||||
|
||||
// ===== 用户屏蔽 =====
|
||||
'屏蔽': '屏蔽',
|
||||
'解除屏蔽': '解除屏蔽',
|
||||
'已屏蔽': '已屏蔽',
|
||||
'会话': '会话',
|
||||
'屏蔽用户': '屏蔽用户',
|
||||
'已屏蔽该用户': '已屏蔽该用户',
|
||||
'已解除屏蔽': '已解除屏蔽',
|
||||
'还没有屏蔽任何人': '还没有屏蔽任何人',
|
||||
'加载中…': '加载中…',
|
||||
'加载失败': '加载失败',
|
||||
|
||||
// ===== 私信用户搜索 =====
|
||||
'搜索用户名开始私信…': '搜索用户名开始私信…',
|
||||
'搜索用户': '搜索用户',
|
||||
@@ -803,6 +815,18 @@ const TRANSLATIONS = {
|
||||
'重新生成恢复码': 'Regenerate Recovery Codes',
|
||||
'退出登录': 'Logout',
|
||||
|
||||
// ===== 用户屏蔽 =====
|
||||
'屏蔽': 'Block',
|
||||
'解除屏蔽': 'Unblock',
|
||||
'已屏蔽': 'Blocked',
|
||||
'会话': 'Chats',
|
||||
'屏蔽用户': 'Block User',
|
||||
'已屏蔽该用户': 'User blocked',
|
||||
'已解除屏蔽': 'User unblocked',
|
||||
'还没有屏蔽任何人': 'You have not blocked anyone',
|
||||
'加载中…': 'Loading…',
|
||||
'加载失败': 'Failed to load',
|
||||
|
||||
// ===== 私信用户搜索 =====
|
||||
'搜索用户名开始私信…': 'Search users to start a chat…',
|
||||
'搜索用户': 'Search users',
|
||||
|
||||
+67
-4
@@ -22,6 +22,16 @@ async function renderUserProfile(username) {
|
||||
|
||||
const avatar = user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128';
|
||||
|
||||
// 已登录且不是本人时,查一次屏蔽关系,用于决定按钮文案
|
||||
let blockStatus = { blocked_by_me: false, blocked_me: false };
|
||||
if (currentUser && currentUser.id !== user.id) {
|
||||
try {
|
||||
blockStatus = await API.getBlockStatus(user.id);
|
||||
} catch (err) {
|
||||
// 查询失败时按未屏蔽处理,不阻断页面渲染
|
||||
}
|
||||
}
|
||||
|
||||
let html = `
|
||||
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;">
|
||||
<img src="${escapeHTML(safeURL(avatar, { image: true }))}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
|
||||
@@ -33,10 +43,26 @@ async function renderUserProfile(username) {
|
||||
${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''}
|
||||
</div>
|
||||
${currentUser && currentUser.id !== user.id ? `
|
||||
<button id="dmBtn" class="btn-primary" style="margin-top:16px;padding:8px 24px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;margin-right:6px;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
发私信
|
||||
</button>
|
||||
<div style="display:flex;justify-content:center;gap:10px;margin-top:16px;flex-wrap:wrap;">
|
||||
<!-- 被我屏蔽时不给出发私信入口,避免必然失败的尝试 -->
|
||||
${blockStatus.blocked_by_me ? '' : `
|
||||
<button id="dmBtn" class="btn-primary" style="padding:8px 24px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;margin-right:6px;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
发私信
|
||||
</button>
|
||||
`}
|
||||
<button id="blockBtn" class="btn-secondary ${blockStatus.blocked_by_me ? 'is-blocked' : ''}"
|
||||
data-userid="${escapeHTML(user.id)}" data-username="${escapeHTML(user.username)}"
|
||||
data-blocked="${blockStatus.blocked_by_me ? '1' : '0'}"
|
||||
style="padding:8px 20px;">
|
||||
${blockStatus.blocked_by_me ? '解除屏蔽' : '屏蔽'}
|
||||
</button>
|
||||
</div>
|
||||
${blockStatus.blocked_by_me ? `
|
||||
<p style="margin-top:10px;font-size:12px;color:var(--text-light);">
|
||||
已屏蔽该用户:你不再看到 TA 的帖子与回复,TA 也无法给你发私信
|
||||
</p>
|
||||
` : ''}
|
||||
` : ''}
|
||||
</div>
|
||||
<h3 style="margin:24px 0 16px;font-size:18px;">📝 发布的帖子</h3>
|
||||
@@ -72,6 +98,43 @@ async function renderUserProfile(username) {
|
||||
});
|
||||
}
|
||||
|
||||
// 屏蔽 / 解除屏蔽。两者都需要确认——屏蔽会影响双方的内容可见性,
|
||||
// 属于不容易察觉后果的操作。
|
||||
const blockBtn = document.getElementById('blockBtn');
|
||||
if (blockBtn) {
|
||||
blockBtn.addEventListener('click', async function() {
|
||||
const targetId = this.dataset.userid;
|
||||
const targetName = this.dataset.username;
|
||||
const isBlocked = this.dataset.blocked === '1';
|
||||
|
||||
const ok = await showConfirm(
|
||||
isBlocked
|
||||
? `解除对「${targetName}」的屏蔽?解除后你将继续看到 TA 的帖子和回复,TA 也能再次给你发私信。`
|
||||
: `确定屏蔽「${targetName}」?屏蔽后你不再看到 TA 的帖子和回复,TA 也无法给你发私信。`,
|
||||
{
|
||||
title: isBlocked ? '解除屏蔽' : '屏蔽用户',
|
||||
confirmText: isBlocked ? '解除屏蔽' : '屏蔽',
|
||||
danger: !isBlocked,
|
||||
}
|
||||
);
|
||||
if (!ok) return;
|
||||
|
||||
try {
|
||||
if (isBlocked) {
|
||||
await API.unblockUser(targetId);
|
||||
showToast('已解除屏蔽', 'success');
|
||||
} else {
|
||||
await API.blockUser(targetId);
|
||||
showToast('已屏蔽该用户', 'success');
|
||||
}
|
||||
// 重新渲染以更新按钮状态与提示
|
||||
renderUserProfile(user.username);
|
||||
} catch (err) {
|
||||
showToast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) + '</div>';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
-- ============================================================
|
||||
-- 用户屏蔽
|
||||
-- ------------------------------------------------------------
|
||||
-- 单向关系:blocker 屏蔽 blocked 之后
|
||||
-- - blocked 不能再给 blocker 发私信(已有的会话也发不了)
|
||||
-- - blocker 在帖子列表、详情与回复中不再看到 blocked 的内容
|
||||
-- - blocked 仍可正常浏览 blocker 的公开内容(不通知、不暴露)
|
||||
--
|
||||
-- 之所以是单向而非互斥:屏蔽应当是「我选择不看某人的内容、也不让
|
||||
-- 对方打扰我」,而不是让双方互相消失。被屏蔽方不会收到任何提示。
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_blocks (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
-- 发起屏蔽的人
|
||||
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
-- 被屏蔽的人
|
||||
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
-- 同一对关系只能有一条
|
||||
UNIQUE (blocker_id, blocked_id),
|
||||
-- 不允许屏蔽自己
|
||||
CHECK (blocker_id <> blocked_id)
|
||||
);
|
||||
|
||||
-- 主查询方向:某人屏蔽了谁(用于过滤内容)
|
||||
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id);
|
||||
|
||||
-- 反向查询:某人被谁屏蔽(用于判断能否发私信)
|
||||
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id);
|
||||
+20
@@ -360,3 +360,23 @@ BEGIN
|
||||
ON posts USING gin (content gin_trgm_ops);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ============================================================
|
||||
-- 用户屏蔽(对应 migrations/006_user_blocks.sql)
|
||||
-- ------------------------------------------------------------
|
||||
-- 单向关系:blocker 屏蔽 blocked 之后,blocked 不能给 blocker 发私信,
|
||||
-- 且 blocker 在帖子与回复中不再看到 blocked 的内容。
|
||||
-- 被屏蔽方不会收到任何提示。
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_blocks (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (blocker_id, blocked_id),
|
||||
CHECK (blocker_id <> blocked_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id);
|
||||
@@ -298,6 +298,40 @@ const admin = async (req, res, next) => {
|
||||
}
|
||||
};
|
||||
|
||||
// 可选认证:用于公开接口。已登录则解析出 req.user,未登录或令牌无效
|
||||
// 都直接放行(不报错)。帖子列表等公开接口借此在登录时应用屏蔽过滤,
|
||||
// 未登录访客则看到全部内容。
|
||||
const optionalAuth = async (req, res, next) => {
|
||||
const header = req.headers.authorization;
|
||||
const token = header && header.split(' ')[1];
|
||||
if (!token) return next();
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET);
|
||||
const current = await pool.query(
|
||||
'SELECT token_version FROM users WHERE id = $1',
|
||||
[decoded.id]
|
||||
);
|
||||
const tokenVersion = decoded.token_version ?? 0;
|
||||
if (current.rows[0] && tokenVersion === current.rows[0].token_version) {
|
||||
req.user = decoded;
|
||||
}
|
||||
} catch (err) {
|
||||
// 令牌无效时按未登录处理,不打断公开接口
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
// 拼装「排除被我屏蔽的用户」这一 SQL 片段。
|
||||
// 未登录时返回空条件,不影响公开访问。
|
||||
function blockedUserFilter(req, params, column = 'p.user_id') {
|
||||
if (!req.user) return '';
|
||||
params.push(req.user.id);
|
||||
return ` AND ${column} NOT IN (
|
||||
SELECT blocked_id FROM user_blocks WHERE blocker_id = $${params.length}
|
||||
)`;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 创建通知(内部函数)
|
||||
// ============================================================
|
||||
@@ -1113,7 +1147,7 @@ app.put('/api/users/:id/email', validateUuidId, auth, async (req, res) => {
|
||||
// ============================================================
|
||||
|
||||
// 获取帖子列表(支持分页和用户筛选,置顶优先)
|
||||
app.get('/api/posts', async (req, res) => {
|
||||
app.get('/api/posts', optionalAuth, async (req, res) => {
|
||||
const sort = req.query.sort === 'hot' ? 'updated_at' : 'created_at';
|
||||
const pagination = parsePagination(req.query);
|
||||
if (!pagination) return res.status(400).json({ error: '分页参数无效' });
|
||||
@@ -1123,6 +1157,22 @@ app.get('/api/posts', async (req, res) => {
|
||||
}
|
||||
|
||||
try {
|
||||
// 条件统一构造,保证 count 与主查询用同一套过滤,
|
||||
// 否则分页总数会与实际结果对不上。
|
||||
const params = [];
|
||||
const conditions = [];
|
||||
|
||||
if (req.query.user_id) {
|
||||
params.push(req.query.user_id);
|
||||
conditions.push(`p.user_id = $${params.length}`);
|
||||
}
|
||||
|
||||
// 登录状态下排除被我屏蔽的用户的内容
|
||||
const blockFilter = blockedUserFilter(req, params, 'p.user_id');
|
||||
if (blockFilter) conditions.push(blockFilter.replace(/^\s*AND\s*/, ''));
|
||||
|
||||
const whereClause = conditions.length ? ' WHERE ' + conditions.join(' AND ') : '';
|
||||
|
||||
let query = `
|
||||
SELECT
|
||||
p.*,
|
||||
@@ -1132,21 +1182,13 @@ app.get('/api/posts', async (req, res) => {
|
||||
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count
|
||||
FROM posts p
|
||||
JOIN users u ON p.user_id = u.id
|
||||
${whereClause}
|
||||
`;
|
||||
const params = [];
|
||||
|
||||
if (req.query.user_id) {
|
||||
query += ' WHERE p.user_id = $1';
|
||||
params.push(req.query.user_id);
|
||||
}
|
||||
|
||||
let countQuery = `
|
||||
SELECT COUNT(*) as total FROM posts p
|
||||
`;
|
||||
if (req.query.user_id) {
|
||||
countQuery += ' WHERE p.user_id = $1';
|
||||
}
|
||||
const countResult = await pool.query(countQuery, req.query.user_id ? [req.query.user_id] : []);
|
||||
const countResult = await pool.query(
|
||||
`SELECT COUNT(*) as total FROM posts p${whereClause}`,
|
||||
params
|
||||
);
|
||||
const total = parseInt(countResult.rows[0]?.total || 0);
|
||||
|
||||
query += ` ORDER BY p.is_pinned DESC, p.pinned_at DESC NULLS LAST, ${sort} DESC LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
|
||||
@@ -1179,7 +1221,7 @@ function escapeLikePattern(value) {
|
||||
}
|
||||
|
||||
// 注意:本路由必须声明在 /api/posts/:id 之前,否则 search 会被当作 id
|
||||
app.get('/api/posts/search', async (req, res) => {
|
||||
app.get('/api/posts/search', optionalAuth, async (req, res) => {
|
||||
const raw = typeof req.query.q === 'string' ? req.query.q.trim() : '';
|
||||
|
||||
if (raw.length === 0) {
|
||||
@@ -1196,10 +1238,19 @@ app.get('/api/posts/search', async (req, res) => {
|
||||
const pattern = '%' + escapeLikePattern(raw) + '%';
|
||||
|
||||
try {
|
||||
// 关键词条件必须用括号包住:它与屏蔽过滤之间是 AND 关系,
|
||||
// 若不加括号会因为 AND 优先级高于 OR 而导致过滤失效。
|
||||
const params = [pattern];
|
||||
const conditions = ['(p.title ILIKE $1 OR p.content ILIKE $1)'];
|
||||
|
||||
const blockFilter = blockedUserFilter(req, params, 'p.user_id');
|
||||
if (blockFilter) conditions.push(blockFilter.replace(/^\s*AND\s*/, ''));
|
||||
|
||||
const whereClause = ' WHERE ' + conditions.join(' AND ');
|
||||
|
||||
const countResult = await pool.query(
|
||||
`SELECT COUNT(*) AS total FROM posts p
|
||||
WHERE p.title ILIKE $1 OR p.content ILIKE $1`,
|
||||
[pattern]
|
||||
`SELECT COUNT(*) AS total FROM posts p${whereClause}`,
|
||||
params
|
||||
);
|
||||
const total = parseInt(countResult.rows[0]?.total || 0);
|
||||
|
||||
@@ -1212,10 +1263,10 @@ app.get('/api/posts/search', async (req, res) => {
|
||||
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) AS reply_count
|
||||
FROM posts p
|
||||
JOIN users u ON p.user_id = u.id
|
||||
WHERE p.title ILIKE $1 OR p.content ILIKE $1
|
||||
${whereClause}
|
||||
ORDER BY p.created_at DESC
|
||||
LIMIT $2 OFFSET $3`,
|
||||
[pattern, limit, offset]
|
||||
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
|
||||
[...params, limit, offset]
|
||||
);
|
||||
|
||||
res.json({
|
||||
@@ -1234,7 +1285,7 @@ app.get('/api/posts/search', async (req, res) => {
|
||||
});
|
||||
|
||||
// 获取单个帖子
|
||||
app.get('/api/posts/:id', validateUuidId, async (req, res) => {
|
||||
app.get('/api/posts/:id', optionalAuth, validateUuidId, async (req, res) => {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`SELECT p.*, u.username, u.avatar_url, u.signature
|
||||
@@ -1380,15 +1431,19 @@ app.put('/api/posts/:id/pin', validateUuidId, auth, admin, async (req, res) => {
|
||||
// ============================================================
|
||||
|
||||
// 获取帖子回复列表
|
||||
app.get('/api/posts/:id/replies', validateUuidId, async (req, res) => {
|
||||
app.get('/api/posts/:id/replies', optionalAuth, validateUuidId, async (req, res) => {
|
||||
try {
|
||||
// 登录状态下隐藏被我屏蔽的用户的回复
|
||||
const params = [req.params.id];
|
||||
const blockFilter = blockedUserFilter(req, params, 'r.user_id');
|
||||
|
||||
const r = await pool.query(
|
||||
`SELECT r.*, u.username, u.avatar_url
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1
|
||||
WHERE r.post_id = $1${blockFilter}
|
||||
ORDER BY r.created_at ASC`,
|
||||
[req.params.id]
|
||||
params
|
||||
);
|
||||
res.json(r.rows);
|
||||
} catch (err) {
|
||||
@@ -1786,8 +1841,83 @@ app.delete('/api/admin/custom-css', auth, admin, async (req, res) => {
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 私信系统
|
||||
// 用户屏蔽
|
||||
// ============================================================
|
||||
// 单向关系。屏蔽后:
|
||||
// - 被屏蔽方不能再给屏蔽方发私信(含已有会话)
|
||||
// - 屏蔽方在帖子列表、详情与回复中不再看到被屏蔽方的内容
|
||||
// 被屏蔽方不会收到任何提示,也不影响其浏览屏蔽方的公开内容。
|
||||
|
||||
app.post('/api/users/:id/block', validateUuidId, auth, async (req, res) => {
|
||||
const targetId = req.params.id;
|
||||
|
||||
if (targetId === req.user.id) {
|
||||
return res.status(400).json({ error: '不能屏蔽自己' });
|
||||
}
|
||||
|
||||
try {
|
||||
const target = await pool.query('SELECT id FROM users WHERE id = $1', [targetId]);
|
||||
if (target.rows.length === 0) {
|
||||
return res.status(404).json({ error: '用户不存在' });
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO user_blocks (blocker_id, blocked_id) VALUES ($1, $2)
|
||||
ON CONFLICT (blocker_id, blocked_id) DO NOTHING`,
|
||||
[req.user.id, targetId]
|
||||
);
|
||||
res.json({ success: true, blocked: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '操作失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/users/:id/block', validateUuidId, auth, async (req, res) => {
|
||||
try {
|
||||
await pool.query(
|
||||
'DELETE FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2',
|
||||
[req.user.id, req.params.id]
|
||||
);
|
||||
res.json({ success: true, blocked: false });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '操作失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// 我屏蔽了谁
|
||||
app.get('/api/blocks', auth, async (req, res) => {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`SELECT u.id, u.username, u.avatar_url, b.created_at
|
||||
FROM user_blocks b
|
||||
JOIN users u ON u.id = b.blocked_id
|
||||
WHERE b.blocker_id = $1
|
||||
ORDER BY b.created_at DESC`,
|
||||
[req.user.id]
|
||||
);
|
||||
res.json({ data: r.rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 查询与某用户的屏蔽关系(双向)。后者用于在私信界面给出准确原因。
|
||||
app.get('/api/users/:id/block-status', validateUuidId, auth, async (req, res) => {
|
||||
if (req.params.id === req.user.id) {
|
||||
return res.json({ blocked_by_me: false, blocked_me: false, self: true });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`SELECT
|
||||
EXISTS(SELECT 1 FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2) AS blocked_by_me,
|
||||
EXISTS(SELECT 1 FROM user_blocks WHERE blocker_id = $2 AND blocked_id = $1) AS blocked_me`,
|
||||
[req.user.id, req.params.id]
|
||||
);
|
||||
res.json(r.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 私信系统
|
||||
@@ -1800,7 +1930,8 @@ const NEW_CONVERSATION_MESSAGE_LIMIT = 3;
|
||||
|
||||
// 搜索用户以便发起私信(公开信息:用户名与头像)
|
||||
// 仅返回用户名/头像/角色,不暴露邮箱等隐私字段。
|
||||
app.get('/api/users/search', async (req, res) => {
|
||||
// 未登录时也能搜索(用于浏览用户),登录时会排除自己已屏蔽的人。
|
||||
app.get('/api/users/search', optionalAuth, async (req, res) => {
|
||||
const raw = typeof req.query.q === 'string' ? req.query.q.trim() : '';
|
||||
|
||||
if (raw.length === 0) {
|
||||
@@ -1812,19 +1943,32 @@ app.get('/api/users/search', async (req, res) => {
|
||||
|
||||
const limit = Math.min(Number(req.query.limit) || 10, 20);
|
||||
const pattern = '%' + escapeLikePattern(raw) + '%';
|
||||
const params = [pattern, escapeLikePattern(raw) + '%'];
|
||||
|
||||
// 已屏蔽的用户不再出现在搜索结果里——否则屏蔽后仍能从私信面板
|
||||
// 找到对方,与「不再看到 TA 的内容」相矛盾。
|
||||
let blockFilter = '';
|
||||
if (req.user) {
|
||||
params.push(req.user.id);
|
||||
blockFilter = ` AND id NOT IN (
|
||||
SELECT blocked_id FROM user_blocks WHERE blocker_id = $${params.length}
|
||||
)`;
|
||||
}
|
||||
|
||||
params.push(limit);
|
||||
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`SELECT id, username, avatar_url, role, signature
|
||||
FROM users
|
||||
WHERE username ILIKE $1
|
||||
WHERE username ILIKE $1${blockFilter}
|
||||
ORDER BY
|
||||
-- 前缀匹配优先,其次按名字长度(更接近精确匹配)
|
||||
CASE WHEN username ILIKE $2 THEN 0 ELSE 1 END,
|
||||
LENGTH(username),
|
||||
username
|
||||
LIMIT $3`,
|
||||
[pattern, escapeLikePattern(raw) + '%', limit]
|
||||
LIMIT $${params.length}`,
|
||||
params
|
||||
);
|
||||
res.json({ data: r.rows, query: raw });
|
||||
} catch (err) {
|
||||
@@ -1875,6 +2019,15 @@ app.post('/api/conversations', auth, async (req, res) => {
|
||||
return res.status(404).json({ error: '用户不存在' });
|
||||
}
|
||||
|
||||
// 对方屏蔽了我则不允许发起会话。提示保持中性。
|
||||
const blocked = await pool.query(
|
||||
'SELECT 1 FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2',
|
||||
[other_user_id, req.user.id]
|
||||
);
|
||||
if (blocked.rows.length > 0) {
|
||||
return res.status(403).json({ error: '无法向该用户发起私信' });
|
||||
}
|
||||
|
||||
const r = await pool.query(`
|
||||
INSERT INTO conversations (user1_id, user2_id)
|
||||
SELECT LEAST($1::uuid, $2::uuid), GREATEST($1::uuid, $2::uuid)
|
||||
@@ -1957,6 +2110,17 @@ app.post('/api/conversations/:id/messages', validateUuidId, auth, async (req, re
|
||||
const conv = check.rows[0];
|
||||
const otherId = conv.user1_id === req.user.id ? conv.user2_id : conv.user1_id;
|
||||
|
||||
// 屏蔽检查:对方屏蔽了我则不能发送。提示保持中性,
|
||||
// 不透露「你被屏蔽了」这一事实。
|
||||
const blocked = await client.query(
|
||||
'SELECT 1 FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2',
|
||||
[otherId, req.user.id]
|
||||
);
|
||||
if (blocked.rows.length > 0) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(403).json({ error: '无法向该用户发送消息' });
|
||||
}
|
||||
|
||||
const stats = await client.query(`
|
||||
SELECT
|
||||
COUNT(*) FILTER (WHERE sender_id = $2) AS mine,
|
||||
|
||||
@@ -3706,6 +3706,79 @@ select:disabled {
|
||||
border-top: 1px solid rgba(245, 158, 11, 0.25);
|
||||
}
|
||||
|
||||
/* 会话 / 已屏蔽 视图切换 */
|
||||
.dm-view-switch {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.dm-view-switch button {
|
||||
flex: 1;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--glass-text-secondary);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition: background var(--dur-fast, 0.16s) ease, color var(--dur-fast, 0.16s) ease;
|
||||
}
|
||||
|
||||
.dm-view-switch button.active {
|
||||
background: var(--glass-bg);
|
||||
color: var(--glass-text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.dm-view-switch button:hover:not(.active) {
|
||||
background: rgba(127, 127, 147, 0.08);
|
||||
}
|
||||
|
||||
/* 搜索结果里的屏蔽按钮,位于「私信」左侧 */
|
||||
.dm-user-block {
|
||||
flex: none;
|
||||
padding: 4px 10px;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--glass-text-secondary);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: background var(--dur-fast, 0.16s) ease, color var(--dur-fast, 0.16s) ease,
|
||||
border-color var(--dur-fast, 0.16s) ease;
|
||||
}
|
||||
|
||||
.dm-user-block:hover {
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
border-color: #ef4444;
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
/* 已屏蔽列表中的解除按钮 */
|
||||
.dm-user-unblock {
|
||||
flex: none;
|
||||
padding: 4px 12px;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--glass-text-secondary);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: background var(--dur-fast, 0.16s) ease, color var(--dur-fast, 0.16s) ease;
|
||||
}
|
||||
|
||||
.dm-user-unblock:hover {
|
||||
background: rgba(127, 127, 147, 0.12);
|
||||
color: var(--glass-text);
|
||||
}
|
||||
|
||||
/* 用户主页上的「解除屏蔽」按钮——用更中性的外观,与「屏蔽」区分 */
|
||||
#blockBtn.is-blocked {
|
||||
border-color: var(--primary);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
/* ===== 列表容器高度稳定 =====
|
||||
骨架屏按「理想内容」绘制,实际帖子往往更短,数据到达时容器高度会
|
||||
骤降,导致其下方的内容(分页控件、页脚)整体上跳——这就是首屏
|
||||
|
||||
Reference in new issue
Block a user