diff --git a/index.html b/index.html
index 7af302d..d4f9349 100644
--- a/index.html
+++ b/index.html
@@ -480,6 +480,19 @@
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 += `
+
+
)})
+
+
${escapeHTML(u.username)}
+
${escapeHTML(u.signature || '点击发送私信')}
+
+
私信
+
+ `;
+ });
+ 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);
+}
+
/* ===== 列表容器高度稳定 =====
骨架屏按「理想内容」绘制,实际帖子往往更短,数据到达时容器高度会
骤降,导致其下方的内容(分页控件、页脚)整体上跳——这就是首屏