From 5995efc7a0a41b4e0edd1e095c9b7e127419a5f0 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Tue, 22 Sep 2026 22:12:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(dm):=20=E7=A7=81=E4=BF=A1=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=8C=89=E7=94=A8=E6=88=B7=E5=90=8D=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E5=BC=80=E8=81=8A=EF=BC=8C=E5=B9=B6=E5=8A=A0=E5=85=A5=E9=A6=96?= =?UTF-8?q?=E8=BD=AE=E5=8F=91=E9=80=81=E6=9D=A1=E6=95=B0=E9=99=90=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 一、私信用户搜索 此前只能先进入对方个人主页、再点「私信」才能发起会话。现在私信窗口 顶部新增搜索框,输入用户名即可搜索并直接开聊。 - 新增 GET /api/users/search:按用户名模糊匹配,前缀匹配优先、其次按 名字长度排序(更接近精确结果)。只返回用户名、头像、角色、签名, 不暴露邮箱等隐私字段(已实测确认响应中不含 email)。 - 关键词转义 % 与 _,与帖子搜索同样处理,避免通配符被当作模式。 - 关键词长度上限 50 字,limit 上限 20。 - 搜索结果中排除自己;输入防抖 300ms,回车立即搜索,Esc 与清除按钮 回到会话列表。 - 搜索框同样带上防密码管理器误填的属性,并在关闭窗口时清空关键词, 避免下次打开残留上次的搜索状态。 二、首轮发送条数限制 对方尚未回复时,发起方最多先发 3 条消息;对方一旦回复过,限制永久 解除。仅对「对方从未回复」的会话生效,已正常交流过的会话不受影响。 - 判定放在事务中并对会话行加 FOR UPDATE 锁:限制依赖「我方已发几条、 对方是否回过」两个计数,不加锁时并发发送可绕过。 - 达到上限返回 429,附带 limit_reached 与 limit 字段,前端据此给出 针对性提示而非笼统的「发送失败」。 - 发送成功时在响应中返回 remaining(对方已回复时为 null)。 - 聊天窗口底部新增提示条,显示「对方回复前还可发送 N 条消息」, 对方回复后自动隐藏。数字与文字分置于不同元素,使固定文案能被 i18n 词典匹配(整句含动态数字时匹配不上)。 实测: - 用户搜索:「dmtester」命中 2 个、「tester2」命中 1 个、无匹配返回 0, 响应中 email 字段出现 0 次 - 连续发送 4 条:前 3 条成功且 remaining 依次为 2/1/0, 第 4 条返回 429 与明确提示 - 对方回复后再发送:成功且 remaining 为 null,限制已解除 - 前端:搜索框正常显示,点击结果直接进入聊天窗口 - 全新会话提示条显示「对方回复前还可发送 3 条消息」, 发送 1 条后更新为 2 条 完整测试套件 25/25 通过。 --- index.html | 15 ++++++ js/api.js | 9 ++++ js/app.js | 156 ++++++++++++++++++++++++++++++++++++++++++++++++++++- js/i18n.js | 22 ++++++++ server.js | 95 +++++++++++++++++++++++++++++--- style.css | 117 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 407 insertions(+), 7 deletions(-) diff --git a/index.html b/index.html index 7af302d..d4f9349 100644 --- a/index.html +++ b/index.html @@ -480,6 +480,19 @@

✉️ 私信

× + +
+ +
加载中...
@@ -499,6 +512,8 @@
加载中...
+ +
diff --git a/js/api.js b/js/api.js index be3b798..27c2fbd 100644 --- a/js/api.js +++ b/js/api.js @@ -272,6 +272,15 @@ const API = { return data || []; }, + // 搜索用户(用于发起私信)。仅返回用户名、头像等公开信息。 + async searchUsers(keyword, limit = 10) { + const data = await apiFetch( + '/users/search?q=' + encodeURIComponent(keyword) + '&limit=' + limit + ); + if (data.error) throw new Error(data.error); + return data.data || []; + }, + async getOrCreateConversation(other_user_id) { const data = await apiFetch('/conversations', { method: 'POST', diff --git a/js/app.js b/js/app.js index f8ebe09..2692367 100644 --- a/js/app.js +++ b/js/app.js @@ -440,9 +440,124 @@ async function updateUnreadBadge() { function openMessageList() { document.getElementById('messageListModal').classList.add('active'); + // 每次打开都回到会话列表状态,避免上次的搜索词残留 + const searchInput = document.getElementById('dmUserSearchInput'); + if (searchInput) searchInput.value = ''; + syncDmSearchClear(); renderMessageList(); } +// ============================================================ +// ✉️ 私信:按用户名搜索并直接开聊 +// ============================================================ +// 此前只能进入对方个人主页再点「私信」,这里提供直接搜索的入口。 + +function syncDmSearchClear() { + const input = document.getElementById('dmUserSearchInput'); + const btn = document.getElementById('dmUserSearchClear'); + if (input && btn) btn.style.display = input.value.trim() ? 'flex' : 'none'; +} + +async function renderDmUserSearch(keyword) { + const container = document.getElementById('messageListContent'); + const kw = (keyword || '').trim(); + + if (!kw) { + renderMessageList(); + return; + } + + container.innerHTML = '
搜索中…
'; + + try { + const users = await API.searchUsers(kw, 10); + + // 排除自己 + const others = users.filter(u => !currentUser || u.id !== currentUser.id); + + if (others.length === 0) { + container.innerHTML = '
没有找到匹配的用户
'; + return; + } + + let html = ''; + others.forEach(u => { + const avatar = u.avatar_url || + 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'; + html += ` +
+ + + 私信 +
+ `; + }); + container.innerHTML = sanitizeHTML(html); + + container.querySelectorAll('.dm-user-row').forEach(row => { + row.addEventListener('click', async function() { + const userId = this.dataset.userId; + const username = this.dataset.username; + try { + const conv = await API.getOrCreateConversation(userId); + // 关闭搜索状态,进入聊天窗口 + const searchInput = document.getElementById('dmUserSearchInput'); + if (searchInput) searchInput.value = ''; + syncDmSearchClear(); + // openChat 需要三个参数:会话 ID、对方用户 ID、对方用户名 + openChat(conv.id, userId, username); + } catch (err) { + showToast(err.message, 'error'); + } + }); + }); + } catch (err) { + container.innerHTML = '
搜索失败:' + escapeHTML(err.message) + '
'; + } +} + +// 绑定搜索框事件(防抖 300ms) +(function initDmUserSearch() { + const input = document.getElementById('dmUserSearchInput'); + const clearBtn = document.getElementById('dmUserSearchClear'); + if (!input) return; + + let timer = null; + + function run() { + syncDmSearchClear(); + if (timer) clearTimeout(timer); + timer = setTimeout(() => renderDmUserSearch(input.value), 300); + } + + input.addEventListener('input', run); + + input.addEventListener('keydown', e => { + if (e.key === 'Enter') { + e.preventDefault(); + if (timer) clearTimeout(timer); + renderDmUserSearch(input.value); + } else if (e.key === 'Escape') { + e.preventDefault(); + input.value = ''; + if (timer) clearTimeout(timer); + renderDmUserSearch(''); + } + }); + + if (clearBtn) { + clearBtn.addEventListener('click', () => { + input.value = ''; + if (timer) clearTimeout(timer); + renderDmUserSearch(''); + input.focus(); + }); + } +})(); + function closeMessageList() { closeModal(document.getElementById('messageListModal')); if (messagePollInterval) { @@ -525,6 +640,38 @@ function closeChat() { updateUnreadBadge(); } +// 更新聊天窗口底部的发送限制提示。 +// 规则:对方从未回复时,我方最多先发 3 条(与后端 +// NEW_CONVERSATION_MESSAGE_LIMIT 对应)。对方回复过就不再限制, +// 此时隐藏提示条。 +const DM_FIRST_ROUND_LIMIT = 3; + +function updateChatLimitNote(messages) { + const note = document.getElementById('chatLimitNote'); + if (!note || !currentUser) return; + + const mine = messages.filter(m => m.sender_id === currentUser.id).length; + const theirs = messages.filter(m => m.sender_id !== currentUser.id).length; + + if (theirs > 0) { + // 对方已回复,限制解除 + note.style.display = 'none'; + return; + } + + const remaining = Math.max(0, DM_FIRST_ROUND_LIMIT - mine); + note.style.display = 'block'; + // 数字与文字分开放进不同元素:整句含动态数字时 i18n 匹配不到词典, + // 拆开后固定文案可被翻译。 + if (remaining > 0) { + note.innerHTML = '对方回复前还可发送 ' + + '' + remaining + ' ' + + '条消息'; + } else { + note.textContent = '对方回复前无法继续发送,请等待对方回复'; + } +} + async function renderMessages(conversationId, silent = false) { const container = document.getElementById('chatMessages'); if (!silent) { @@ -533,6 +680,7 @@ async function renderMessages(conversationId, silent = false) { try { const messages = await API.getMessages(conversationId); + updateChatLimitNote(messages); if (messages.length === 0) { container.innerHTML = '
还没有消息,打个招呼吧
'; return; @@ -579,7 +727,13 @@ async function sendMessage() { renderMessageList(); } } catch (err) { - showToast('发送失败:' + err.message, 'error'); + // 达到首轮发送上限时给出更明确的提示,而不是笼统的「发送失败」 + if (/最多发送/.test(err.message)) { + showToast(err.message, 'warning'); + renderMessages(currentConversationId, true); + } else { + showToast('发送失败:' + err.message, 'error'); + } } } diff --git a/js/i18n.js b/js/i18n.js index ac8ca81..ffb0bf1 100644 --- a/js/i18n.js +++ b/js/i18n.js @@ -372,6 +372,17 @@ const TRANSLATIONS = { '重新生成恢复码': '重新生成恢复码', '退出登录': '退出登录', + // ===== 私信用户搜索 ===== + '搜索用户名开始私信…': '搜索用户名开始私信…', + '搜索用户': '搜索用户', + '没有找到匹配的用户': '没有找到匹配的用户', + '点击发送私信': '点击发送私信', + '对方回复前还可发送': '对方回复前还可发送', + '条消息': '条消息', + '对方回复前无法继续发送,请等待对方回复': '对方回复前无法继续发送,请等待对方回复', + '搜索中…': '搜索中…', + '搜索失败:': '搜索失败:', + // ===== 帖子搜索 ===== '搜索帖子…': '搜索帖子…', '清除搜索': '清除搜索', @@ -792,6 +803,17 @@ const TRANSLATIONS = { '重新生成恢复码': 'Regenerate Recovery Codes', '退出登录': 'Logout', + // ===== 私信用户搜索 ===== + '搜索用户名开始私信…': 'Search users to start a chat…', + '搜索用户': 'Search users', + '没有找到匹配的用户': 'No matching users found', + '点击发送私信': 'Click to send a message', + '对方回复前还可发送': 'You can send', + '条消息': 'more messages before they reply', + '对方回复前无法继续发送,请等待对方回复': 'You cannot send more until they reply', + '搜索中…': 'Searching…', + '搜索失败:': 'Search failed: ', + // ===== 帖子搜索 ===== '搜索帖子…': 'Search posts…', '清除搜索': 'Clear search', diff --git a/server.js b/server.js index 47e9c59..b4660e5 100644 --- a/server.js +++ b/server.js @@ -1789,6 +1789,49 @@ app.delete('/api/admin/custom-css', auth, admin, async (req, res) => { // 私信系统 // ============================================================ +// ============================================================ +// 私信系统 +// ============================================================ + +// 防骚扰限制:对方尚未回复时,发起方最多先发这么多条消息。 +// 对方一旦回复过,限制永久解除。仅对「对方从未回复」的会话生效, +// 因此已经正常交流过的会话不受影响。 +const NEW_CONVERSATION_MESSAGE_LIMIT = 3; + +// 搜索用户以便发起私信(公开信息:用户名与头像) +// 仅返回用户名/头像/角色,不暴露邮箱等隐私字段。 +app.get('/api/users/search', async (req, res) => { + const raw = typeof req.query.q === 'string' ? req.query.q.trim() : ''; + + if (raw.length === 0) { + return res.status(400).json({ error: '请输入搜索关键词' }); + } + if (raw.length > 50) { + return res.status(400).json({ error: '搜索关键词过长(最多 50 字)' }); + } + + const limit = Math.min(Number(req.query.limit) || 10, 20); + const pattern = '%' + escapeLikePattern(raw) + '%'; + + try { + const r = await pool.query( + `SELECT id, username, avatar_url, role, signature + FROM users + WHERE username ILIKE $1 + ORDER BY + -- 前缀匹配优先,其次按名字长度(更接近精确匹配) + CASE WHEN username ILIKE $2 THEN 0 ELSE 1 END, + LENGTH(username), + username + LIMIT $3`, + [pattern, escapeLikePattern(raw) + '%', limit] + ); + res.json({ data: r.rows, query: raw }); + } catch (err) { + res.status(500).json({ error: '服务器错误' }); + } +}); + // 获取会话列表 app.get('/api/conversations', auth, async (req, res) => { try { @@ -1891,38 +1934,78 @@ app.post('/api/conversations/:id/messages', validateUuidId, auth, async (req, re return res.status(400).json({ error: '消息长度应为1到10000个字符' }); } + let client; try { - const check = await pool.query(` - SELECT id FROM conversations + client = await pool.connect(); + await client.query('BEGIN'); + + // 取会话并加行锁:限制判定依赖「我方已发几条、对方是否回过」, + // 不加锁的话并发发送可以绕过计数。 + const check = await client.query(` + SELECT id, user1_id, user2_id FROM conversations WHERE id = $1 AND (user1_id = $2 OR user2_id = $2) + FOR UPDATE `, [conversationId, req.user.id]); if (check.rows.length === 0) { + await client.query('ROLLBACK'); return res.status(403).json({ error: '无权限访问此会话' }); } - const r = await pool.query(` + // 防骚扰限制:对方尚未回复时,我方最多先发 NEW_CONVERSATION_MESSAGE_LIMIT 条。 + // 对方一旦回复过,限制永久解除,之后不再计数。 + const conv = check.rows[0]; + const otherId = conv.user1_id === req.user.id ? conv.user2_id : conv.user1_id; + + const stats = await client.query(` + SELECT + COUNT(*) FILTER (WHERE sender_id = $2) AS mine, + COUNT(*) FILTER (WHERE sender_id = $3) AS theirs + FROM messages + WHERE conversation_id = $1 + `, [conversationId, req.user.id, otherId]); + + const mine = parseInt(stats.rows[0].mine || 0); + const theirs = parseInt(stats.rows[0].theirs || 0); + + if (theirs === 0 && mine >= NEW_CONVERSATION_MESSAGE_LIMIT) { + await client.query('ROLLBACK'); + return res.status(429).json({ + error: `对方回复前最多发送 ${NEW_CONVERSATION_MESSAGE_LIMIT} 条消息,请等待对方回复`, + limit_reached: true, + limit: NEW_CONVERSATION_MESSAGE_LIMIT, + }); + } + + const r = await client.query(` INSERT INTO messages (conversation_id, sender_id, content) VALUES ($1, $2, $3) RETURNING * `, [conversationId, req.user.id, content.trim()]); - await pool.query(` + await client.query(` UPDATE conversations SET last_message_at = NOW() WHERE id = $1 `, [conversationId]); - const userInfo = await pool.query(` + const userInfo = await client.query(` SELECT username, avatar_url FROM users WHERE id = $1 `, [req.user.id]); + await client.query('COMMIT'); + res.json({ ...r.rows[0], sender_username: userInfo.rows[0].username, - sender_avatar_url: userInfo.rows[0].avatar_url + sender_avatar_url: userInfo.rows[0].avatar_url, + // 告知前端剩余可发条数,便于在界面上提示(对方已回复时为 null) + remaining: theirs > 0 ? null : Math.max(0, NEW_CONVERSATION_MESSAGE_LIMIT - mine - 1), }); } catch (err) { + if (client) await client.query('ROLLBACK').catch(() => {}); res.status(500).json({ error: '发送失败,请稍后重试' }); + } finally { + if (client) client.release(); } }); diff --git a/style.css b/style.css index c67cb18..0186495 100644 --- a/style.css +++ b/style.css @@ -3589,6 +3589,123 @@ select:disabled { color: var(--glass-text); } +/* ============================================================ + ✉️ 私信:用户搜索 + ============================================================ */ + +.dm-search-wrap { + padding: 12px 20px 0; + flex-shrink: 0; +} + +.dm-search { + position: relative; +} + +.dm-search input { + width: 100%; + box-sizing: border-box; + /* 右侧留出清除按钮的位置 */ + padding-right: 34px !important; + margin-bottom: 0 !important; +} + +.dm-search-clear { + position: absolute; + right: 6px; + top: 50%; + transform: translateY(-50%); + display: flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + padding: 0; + border: none; + border-radius: 50%; + background: transparent; + color: var(--glass-text-light); + cursor: pointer; + transition: background var(--dur-fast, 0.16s) ease, color var(--dur-fast, 0.16s) ease; +} + +.dm-search-clear:hover { + background: rgba(127, 127, 147, 0.18); + color: var(--glass-text); +} + +/* 搜索结果条目 */ +.dm-user-row { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 20px; + cursor: pointer; + transition: background var(--dur-fast, 0.16s) ease; + border-bottom: 1px solid var(--glass-border); +} + +.dm-user-row:hover { + background: rgba(127, 127, 147, 0.08); +} + +.dm-user-row img { + width: 38px; + height: 38px; + border-radius: 50%; + object-fit: cover; + border: 1px solid var(--glass-border); + flex: none; +} + +.dm-user-info { + flex: 1; + min-width: 0; +} + +.dm-user-name { + font-weight: 600; + font-size: 14px; + color: var(--glass-text); + /* 过长的用户名截断而不是撑破布局 */ + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dm-user-hint { + font-size: 12px; + color: var(--glass-text-light); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dm-user-row .dm-user-action { + flex: none; + font-size: 12px; + color: var(--primary); + font-weight: 600; +} + +/* 搜索状态提示 */ +.dm-search-status { + text-align: center; + color: var(--glass-text-light); + font-size: 13px; + padding: 28px 20px; +} + +/* 会话中的限制提示条 */ +.dm-limit-note { + text-align: center; + font-size: 12px; + color: var(--glass-text-light); + padding: 8px 16px; + background: rgba(245, 158, 11, 0.1); + border-top: 1px solid rgba(245, 158, 11, 0.25); +} + /* ===== 列表容器高度稳定 ===== 骨架屏按「理想内容」绘制,实际帖子往往更短,数据到达时容器高度会 骤降,导致其下方的内容(分页控件、页脚)整体上跳——这就是首屏