feat(dm): 私信支持按用户名搜索开聊,并加入首轮发送条数限制
一、私信用户搜索 此前只能先进入对方个人主页、再点「私信」才能发起会话。现在私信窗口 顶部新增搜索框,输入用户名即可搜索并直接开聊。 - 新增 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 通过。
This commit is contained in:
1 parent
c26e834982
commit
5995efc7a0
6 files changed
+407
-7
No files matched your search
+15
@@ -480,6 +480,19 @@
|
|||||||
<h2 style="font-size:18px;margin:0;">✉️ 私信</h2>
|
<h2 style="font-size:18px;margin:0;">✉️ 私信</h2>
|
||||||
<span class="close" data-modal="messageListModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">×</span>
|
<span class="close" data-modal="messageListModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">×</span>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 用户搜索:此前只能从对方主页点「私信」才能发起会话,
|
||||||
|
这里提供按用户名搜索并直接开聊的入口 -->
|
||||||
|
<div class="dm-search-wrap">
|
||||||
|
<div class="dm-search">
|
||||||
|
<input type="search" id="dmUserSearchInput" name="dm-user-search"
|
||||||
|
placeholder="搜索用户名开始私信…" autocomplete="off"
|
||||||
|
role="searchbox" aria-label="搜索用户"
|
||||||
|
data-form-type="other" data-1p-ignore data-lpignore="true" />
|
||||||
|
<button type="button" id="dmUserSearchClear" class="dm-search-clear" title="清除搜索" style="display:none;">
|
||||||
|
<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>
|
||||||
<div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;">
|
<div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;">
|
||||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -499,6 +512,8 @@
|
|||||||
<div id="chatMessages" style="flex:1;overflow-y:auto;padding:16px;min-height:300px;max-height:400px;">
|
<div id="chatMessages" style="flex:1;overflow-y:auto;padding:16px;min-height:300px;max-height:400px;">
|
||||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 对方回复前的发送条数提示,由 JS 控制显示 -->
|
||||||
|
<div id="chatLimitNote" class="dm-limit-note" style="display:none;"></div>
|
||||||
<div style="display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);flex-shrink:0;">
|
<div style="display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);flex-shrink:0;">
|
||||||
<input type="text" id="chatInput" placeholder="输入消息..." style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;background:var(--bg);color:var(--text);outline:none;" />
|
<input type="text" id="chatInput" placeholder="输入消息..." style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;background:var(--bg);color:var(--text);outline:none;" />
|
||||||
<button onclick="sendMessage()" class="btn-primary" style="padding:8px 16px;">发送</button>
|
<button onclick="sendMessage()" class="btn-primary" style="padding:8px 16px;">发送</button>
|
||||||
|
|||||||
@@ -272,6 +272,15 @@ const API = {
|
|||||||
return data || [];
|
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) {
|
async getOrCreateConversation(other_user_id) {
|
||||||
const data = await apiFetch('/conversations', {
|
const data = await apiFetch('/conversations', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -440,9 +440,124 @@ async function updateUnreadBadge() {
|
|||||||
|
|
||||||
function openMessageList() {
|
function openMessageList() {
|
||||||
document.getElementById('messageListModal').classList.add('active');
|
document.getElementById('messageListModal').classList.add('active');
|
||||||
|
// 每次打开都回到会话列表状态,避免上次的搜索词残留
|
||||||
|
const searchInput = document.getElementById('dmUserSearchInput');
|
||||||
|
if (searchInput) searchInput.value = '';
|
||||||
|
syncDmSearchClear();
|
||||||
renderMessageList();
|
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 = '<div class="dm-search-status">搜索中…</div>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const users = await API.searchUsers(kw, 10);
|
||||||
|
|
||||||
|
// 排除自己
|
||||||
|
const others = users.filter(u => !currentUser || u.id !== currentUser.id);
|
||||||
|
|
||||||
|
if (others.length === 0) {
|
||||||
|
container.innerHTML = '<div class="dm-search-status">没有找到匹配的用户</div>';
|
||||||
|
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 += `
|
||||||
|
<div class="dm-user-row" data-user-id="${escapeHTML(u.id)}" data-username="${escapeHTML(u.username)}">
|
||||||
|
<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">${escapeHTML(u.signature || '点击发送私信')}</div>
|
||||||
|
</div>
|
||||||
|
<span class="dm-user-action">私信</span>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
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 = '<div class="dm-search-status">搜索失败:' + escapeHTML(err.message) + '</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 绑定搜索框事件(防抖 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() {
|
function closeMessageList() {
|
||||||
closeModal(document.getElementById('messageListModal'));
|
closeModal(document.getElementById('messageListModal'));
|
||||||
if (messagePollInterval) {
|
if (messagePollInterval) {
|
||||||
@@ -525,6 +640,38 @@ function closeChat() {
|
|||||||
updateUnreadBadge();
|
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 = '<span>对方回复前还可发送</span> '
|
||||||
|
+ '<strong>' + remaining + '</strong> '
|
||||||
|
+ '<span>条消息</span>';
|
||||||
|
} else {
|
||||||
|
note.textContent = '对方回复前无法继续发送,请等待对方回复';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function renderMessages(conversationId, silent = false) {
|
async function renderMessages(conversationId, silent = false) {
|
||||||
const container = document.getElementById('chatMessages');
|
const container = document.getElementById('chatMessages');
|
||||||
if (!silent) {
|
if (!silent) {
|
||||||
@@ -533,6 +680,7 @@ async function renderMessages(conversationId, silent = false) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const messages = await API.getMessages(conversationId);
|
const messages = await API.getMessages(conversationId);
|
||||||
|
updateChatLimitNote(messages);
|
||||||
if (messages.length === 0) {
|
if (messages.length === 0) {
|
||||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">还没有消息,打个招呼吧</div>';
|
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">还没有消息,打个招呼吧</div>';
|
||||||
return;
|
return;
|
||||||
@@ -579,7 +727,13 @@ async function sendMessage() {
|
|||||||
renderMessageList();
|
renderMessageList();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showToast('发送失败:' + err.message, 'error');
|
// 达到首轮发送上限时给出更明确的提示,而不是笼统的「发送失败」
|
||||||
|
if (/最多发送/.test(err.message)) {
|
||||||
|
showToast(err.message, 'warning');
|
||||||
|
renderMessages(currentConversationId, true);
|
||||||
|
} else {
|
||||||
|
showToast('发送失败:' + err.message, 'error');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+22
@@ -372,6 +372,17 @@ const TRANSLATIONS = {
|
|||||||
'重新生成恢复码': '重新生成恢复码',
|
'重新生成恢复码': '重新生成恢复码',
|
||||||
'退出登录': '退出登录',
|
'退出登录': '退出登录',
|
||||||
|
|
||||||
|
// ===== 私信用户搜索 =====
|
||||||
|
'搜索用户名开始私信…': '搜索用户名开始私信…',
|
||||||
|
'搜索用户': '搜索用户',
|
||||||
|
'没有找到匹配的用户': '没有找到匹配的用户',
|
||||||
|
'点击发送私信': '点击发送私信',
|
||||||
|
'对方回复前还可发送': '对方回复前还可发送',
|
||||||
|
'条消息': '条消息',
|
||||||
|
'对方回复前无法继续发送,请等待对方回复': '对方回复前无法继续发送,请等待对方回复',
|
||||||
|
'搜索中…': '搜索中…',
|
||||||
|
'搜索失败:': '搜索失败:',
|
||||||
|
|
||||||
// ===== 帖子搜索 =====
|
// ===== 帖子搜索 =====
|
||||||
'搜索帖子…': '搜索帖子…',
|
'搜索帖子…': '搜索帖子…',
|
||||||
'清除搜索': '清除搜索',
|
'清除搜索': '清除搜索',
|
||||||
@@ -792,6 +803,17 @@ const TRANSLATIONS = {
|
|||||||
'重新生成恢复码': 'Regenerate Recovery Codes',
|
'重新生成恢复码': 'Regenerate Recovery Codes',
|
||||||
'退出登录': 'Logout',
|
'退出登录': '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…',
|
'搜索帖子…': 'Search posts…',
|
||||||
'清除搜索': 'Clear search',
|
'清除搜索': 'Clear search',
|
||||||
|
|||||||
@@ -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) => {
|
app.get('/api/conversations', auth, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
@@ -1891,38 +1934,78 @@ app.post('/api/conversations/:id/messages', validateUuidId, auth, async (req, re
|
|||||||
return res.status(400).json({ error: '消息长度应为1到10000个字符' });
|
return res.status(400).json({ error: '消息长度应为1到10000个字符' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let client;
|
||||||
try {
|
try {
|
||||||
const check = await pool.query(`
|
client = await pool.connect();
|
||||||
SELECT id FROM conversations
|
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)
|
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||||
|
FOR UPDATE
|
||||||
`, [conversationId, req.user.id]);
|
`, [conversationId, req.user.id]);
|
||||||
|
|
||||||
if (check.rows.length === 0) {
|
if (check.rows.length === 0) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
return res.status(403).json({ error: '无权限访问此会话' });
|
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)
|
INSERT INTO messages (conversation_id, sender_id, content)
|
||||||
VALUES ($1, $2, $3)
|
VALUES ($1, $2, $3)
|
||||||
RETURNING *
|
RETURNING *
|
||||||
`, [conversationId, req.user.id, content.trim()]);
|
`, [conversationId, req.user.id, content.trim()]);
|
||||||
|
|
||||||
await pool.query(`
|
await client.query(`
|
||||||
UPDATE conversations SET last_message_at = NOW()
|
UPDATE conversations SET last_message_at = NOW()
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
`, [conversationId]);
|
`, [conversationId]);
|
||||||
|
|
||||||
const userInfo = await pool.query(`
|
const userInfo = await client.query(`
|
||||||
SELECT username, avatar_url FROM users WHERE id = $1
|
SELECT username, avatar_url FROM users WHERE id = $1
|
||||||
`, [req.user.id]);
|
`, [req.user.id]);
|
||||||
|
|
||||||
|
await client.query('COMMIT');
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
...r.rows[0],
|
...r.rows[0],
|
||||||
sender_username: userInfo.rows[0].username,
|
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) {
|
} catch (err) {
|
||||||
|
if (client) await client.query('ROLLBACK').catch(() => {});
|
||||||
res.status(500).json({ error: '发送失败,请稍后重试' });
|
res.status(500).json({ error: '发送失败,请稍后重试' });
|
||||||
|
} finally {
|
||||||
|
if (client) client.release();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3589,6 +3589,123 @@ select:disabled {
|
|||||||
color: var(--glass-text);
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
/* ===== 列表容器高度稳定 =====
|
/* ===== 列表容器高度稳定 =====
|
||||||
骨架屏按「理想内容」绘制,实际帖子往往更短,数据到达时容器高度会
|
骨架屏按「理想内容」绘制,实际帖子往往更短,数据到达时容器高度会
|
||||||
骤降,导致其下方的内容(分页控件、页脚)整体上跳——这就是首屏
|
骤降,导致其下方的内容(分页控件、页脚)整体上跳——这就是首屏
|
||||||
|
|||||||
Reference in new issue
Block a user