feat: port private messaging (私信) from upstream
- Add conversations/messages tables to schema.sql (upstream missed them) - API: GET/POST /api/conversations, GET/POST /api/conversations/[id]/messages, PUT /api/messages/[id]/read - Chat UI: conversation list modal, chat window with 3s polling, unread badge - Navbar message entry opens DM list; user profile has 发私信 button - Access control: only conversation participants (403 otherwise)
This commit is contained in:
1 parent
5ef8d4b1ff
commit
300ad5959c
11 files changed
+522
-3
No files matched your search
@@ -0,0 +1,78 @@
|
|||||||
|
// GET /api/conversations/[id]/messages, POST /api/conversations/[id]/messages
|
||||||
|
import pool from '@/lib/db';
|
||||||
|
import { getUser } from '@/lib/auth';
|
||||||
|
|
||||||
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
export async function GET(req, { params }) {
|
||||||
|
const user = getUser(req);
|
||||||
|
if (!user) {
|
||||||
|
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||||
|
}
|
||||||
|
if (!UUID_RE.test(params.id)) {
|
||||||
|
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const check = await pool.query(`
|
||||||
|
SELECT id FROM conversations
|
||||||
|
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||||
|
`, [params.id, user.id]);
|
||||||
|
if (check.rows.length === 0) {
|
||||||
|
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||||
|
}
|
||||||
|
const r = await pool.query(`
|
||||||
|
SELECT
|
||||||
|
m.*,
|
||||||
|
u.username as sender_username,
|
||||||
|
u.avatar_url as sender_avatar_url
|
||||||
|
FROM messages m
|
||||||
|
JOIN users u ON m.sender_id = u.id
|
||||||
|
WHERE m.conversation_id = $1
|
||||||
|
ORDER BY m.created_at ASC
|
||||||
|
`, [params.id]);
|
||||||
|
await pool.query(`
|
||||||
|
UPDATE messages SET is_read = true
|
||||||
|
WHERE conversation_id = $1 AND sender_id != $2 AND is_read = false
|
||||||
|
`, [params.id, user.id]);
|
||||||
|
return Response.json(r.rows);
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req, { params }) {
|
||||||
|
const user = getUser(req);
|
||||||
|
if (!user) {
|
||||||
|
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||||
|
}
|
||||||
|
if (!UUID_RE.test(params.id)) {
|
||||||
|
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||||
|
}
|
||||||
|
const { content } = await req.json();
|
||||||
|
if (!content || content.trim().length === 0) {
|
||||||
|
return Response.json({ error: '请填写消息内容' }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const check = await pool.query(`
|
||||||
|
SELECT id FROM conversations
|
||||||
|
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||||
|
`, [params.id, user.id]);
|
||||||
|
if (check.rows.length === 0) {
|
||||||
|
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||||
|
}
|
||||||
|
const r = await pool.query(`
|
||||||
|
INSERT INTO messages (conversation_id, sender_id, content)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
RETURNING *
|
||||||
|
`, [params.id, user.id, content]);
|
||||||
|
await pool.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [params.id]);
|
||||||
|
const userInfo = await pool.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
|
||||||
|
return Response.json({
|
||||||
|
...r.rows[0],
|
||||||
|
sender_username: userInfo.rows[0].username,
|
||||||
|
sender_avatar_url: userInfo.rows[0].avatar_url,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// GET /api/conversations, POST /api/conversations
|
||||||
|
import pool from '@/lib/db';
|
||||||
|
import { getUser } from '@/lib/auth';
|
||||||
|
|
||||||
|
export async function GET(req) {
|
||||||
|
const user = getUser(req);
|
||||||
|
if (!user) {
|
||||||
|
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const r = await pool.query(`
|
||||||
|
SELECT
|
||||||
|
c.id,
|
||||||
|
c.user1_id,
|
||||||
|
c.user2_id,
|
||||||
|
c.last_message_at,
|
||||||
|
c.created_at,
|
||||||
|
u.id as other_user_id,
|
||||||
|
u.username as other_username,
|
||||||
|
u.avatar_url as other_avatar_url,
|
||||||
|
(SELECT COUNT(*) FROM messages WHERE conversation_id = c.id AND sender_id != $1 AND is_read = false) as unread_count,
|
||||||
|
(SELECT content FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message,
|
||||||
|
(SELECT created_at FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message_time
|
||||||
|
FROM conversations c
|
||||||
|
JOIN users u ON (u.id = c.user1_id OR u.id = c.user2_id) AND u.id != $1
|
||||||
|
WHERE c.user1_id = $1 OR c.user2_id = $1
|
||||||
|
ORDER BY c.last_message_at DESC
|
||||||
|
`, [user.id]);
|
||||||
|
return Response.json(r.rows);
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req) {
|
||||||
|
const user = getUser(req);
|
||||||
|
if (!user) {
|
||||||
|
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||||
|
}
|
||||||
|
const { other_user_id } = await req.json();
|
||||||
|
if (!other_user_id) {
|
||||||
|
return Response.json({ error: '缺少对方用户ID' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (other_user_id === user.id) {
|
||||||
|
return Response.json({ error: '不能与自己私信' }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
|
||||||
|
if (userCheck.rows.length === 0) {
|
||||||
|
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||||
|
}
|
||||||
|
const existing = await pool.query(`
|
||||||
|
SELECT id FROM conversations
|
||||||
|
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
|
||||||
|
`, [user.id, other_user_id]);
|
||||||
|
if (existing.rows.length > 0) {
|
||||||
|
return Response.json({ id: existing.rows[0].id });
|
||||||
|
}
|
||||||
|
const r = await pool.query(`
|
||||||
|
INSERT INTO conversations (user1_id, user2_id)
|
||||||
|
VALUES ($1, $2)
|
||||||
|
RETURNING id
|
||||||
|
`, [user.id, other_user_id]);
|
||||||
|
return Response.json({ id: r.rows[0].id });
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
// PUT /api/messages/[id]/read — 标记消息已读
|
||||||
|
import pool from '@/lib/db';
|
||||||
|
import { getUser } from '@/lib/auth';
|
||||||
|
|
||||||
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
export async function PUT(req, { params }) {
|
||||||
|
const user = getUser(req);
|
||||||
|
if (!user) {
|
||||||
|
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||||
|
}
|
||||||
|
if (!UUID_RE.test(params.id)) {
|
||||||
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await pool.query(`
|
||||||
|
UPDATE messages SET is_read = true
|
||||||
|
WHERE id = $1 AND sender_id != $2
|
||||||
|
`, [params.id, user.id]);
|
||||||
|
return Response.json({ success: true });
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
-1
@@ -11,6 +11,7 @@ import NewPost from '@/components/NewPost';
|
|||||||
import AdminPage from '@/components/AdminPage';
|
import AdminPage from '@/components/AdminPage';
|
||||||
import SettingsPage from '@/components/SettingsPage';
|
import SettingsPage from '@/components/SettingsPage';
|
||||||
import UserProfile from '@/components/UserProfile';
|
import UserProfile from '@/components/UserProfile';
|
||||||
|
import ChatManager from '@/components/chat/ChatManager';
|
||||||
import Modals from '@/components/Modals';
|
import Modals from '@/components/Modals';
|
||||||
|
|
||||||
function HomeInner() {
|
function HomeInner() {
|
||||||
@@ -23,7 +24,12 @@ function HomeInner() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Navbar onOpenModal={openModal} />
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<Navbar onOpenModal={openModal} style={{ flex: 1 }} />
|
||||||
|
<div style={{ paddingRight: 16 }}>
|
||||||
|
<ChatManager />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div id="app" style={{ display: view === 'feed' ? 'flex' : 'none' }}>
|
<div id="app" style={{ display: view === 'feed' ? 'flex' : 'none' }}>
|
||||||
<Sidebar />
|
<Sidebar />
|
||||||
|
|||||||
@@ -22,6 +22,13 @@ export default function Navbar({ onOpenModal }) {
|
|||||||
navigate(page);
|
navigate(page);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const openMessages = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setMenuOpen(false);
|
||||||
|
// 打开私信列表(ChatManager 监听)
|
||||||
|
window.dispatchEvent(new CustomEvent('forumlify-open-messages'));
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<nav id="navbar">
|
<nav id="navbar">
|
||||||
<div className="nav-left">
|
<div className="nav-left">
|
||||||
@@ -46,7 +53,7 @@ export default function Navbar({ onOpenModal }) {
|
|||||||
/>
|
/>
|
||||||
{menuOpen && (
|
{menuOpen && (
|
||||||
<div className="dropdown-menu show" onClick={(e) => e.stopPropagation()}>
|
<div className="dropdown-menu show" onClick={(e) => e.stopPropagation()}>
|
||||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('messages'); }}>
|
<a href="#" onClick={openMessages}>
|
||||||
<Icon name="message" /> 消息
|
<Icon name="message" /> 消息
|
||||||
</a>
|
</a>
|
||||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('settings'); }}>
|
<a href="#" onClick={(e) => { e.preventDefault(); goPage('settings'); }}>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useEffect, useState, useCallback } from 'react';
|
|||||||
import { API } from '@/lib/api';
|
import { API } from '@/lib/api';
|
||||||
import { useApp } from './AppProvider';
|
import { useApp } from './AppProvider';
|
||||||
import { Icon } from './Icons';
|
import { Icon } from './Icons';
|
||||||
|
import { useOpenPrivateChat } from './chat/ChatManager';
|
||||||
|
|
||||||
function avatar(username, size = 128) {
|
function avatar(username, size = 128) {
|
||||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||||
@@ -12,7 +13,8 @@ function avatar(username, size = 128) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function UserProfile({ username }) {
|
export default function UserProfile({ username }) {
|
||||||
const { openPost } = useApp();
|
const { currentUser, openPost } = useApp();
|
||||||
|
const openPrivateChat = useOpenPrivateChat();
|
||||||
const [user, setUser] = useState(null);
|
const [user, setUser] = useState(null);
|
||||||
const [posts, setPosts] = useState([]);
|
const [posts, setPosts] = useState([]);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
@@ -57,6 +59,15 @@ export default function UserProfile({ username }) {
|
|||||||
<img src={avatar(user.username)} style={{ width: 96, height: 96, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
|
<img src={avatar(user.username)} style={{ width: 96, height: 96, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
|
||||||
<h2 style={{ margin: '16px 0 4px', fontSize: 24 }}>{user.username}</h2>
|
<h2 style={{ margin: '16px 0 4px', fontSize: 24 }}>{user.username}</h2>
|
||||||
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
|
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
|
||||||
|
{currentUser && currentUser.id !== user.id && (
|
||||||
|
<button
|
||||||
|
className="btn-primary"
|
||||||
|
style={{ marginTop: 12, padding: '8px 20px' }}
|
||||||
|
onClick={() => openPrivateChat(user.id, user.username)}
|
||||||
|
>
|
||||||
|
<Icon name="message" size={14} /> 发私信
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
|
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
|
||||||
<span>📅 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
|
<span>📅 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
|
||||||
<span>📝 发了 {posts.length} 个帖子</span>
|
<span>📝 发了 {posts.length} 个帖子</span>
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
// 私信管理器:会话列表 modal + 聊天窗口 modal + 未读 badge + openPrivateChat
|
||||||
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { API } from '@/lib/api';
|
||||||
|
import { useApp } from '../AppProvider';
|
||||||
|
import ConversationList from './ConversationList';
|
||||||
|
import ChatWindow from './ChatWindow';
|
||||||
|
|
||||||
|
export default function ChatManager() {
|
||||||
|
const { currentUser } = useApp();
|
||||||
|
const [listOpen, setListOpen] = useState(false);
|
||||||
|
const [chat, setChat] = useState(null); // {conversationId, otherUserId, otherUsername}
|
||||||
|
const [unread, setUnread] = useState(0);
|
||||||
|
const [refreshKey, setRefreshKey] = useState(0);
|
||||||
|
|
||||||
|
const refreshList = useCallback(() => setRefreshKey((k) => k + 1), []);
|
||||||
|
|
||||||
|
// 未读 badge 轮询(30 秒 + 每次刷新)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!currentUser) return;
|
||||||
|
const update = () => {
|
||||||
|
API.getConversations()
|
||||||
|
.then((cs) => {
|
||||||
|
const total = (cs || []).reduce((s, c) => s + (c.unread_count || 0), 0);
|
||||||
|
setUnread(total);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
};
|
||||||
|
update();
|
||||||
|
const t = setInterval(update, 30000);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
}, [currentUser, refreshKey]);
|
||||||
|
|
||||||
|
// 监听其他组件发起的打开私信事件
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = (e) => {
|
||||||
|
setChat(e.detail);
|
||||||
|
setListOpen(false);
|
||||||
|
};
|
||||||
|
const openList = () => setListOpen(true);
|
||||||
|
window.addEventListener('forumlify-open-chat', handler);
|
||||||
|
window.addEventListener('forumlify-open-messages', openList);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('forumlify-open-chat', handler);
|
||||||
|
window.removeEventListener('forumlify-open-messages', openList);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const openChat = (conversationId, otherUserId, otherUsername) => {
|
||||||
|
setChat({ conversationId, otherUserId, otherUsername });
|
||||||
|
setListOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeChat = () => {
|
||||||
|
setChat(null);
|
||||||
|
refreshList();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* 导航栏私信按钮 + 未读 badge */}
|
||||||
|
<button
|
||||||
|
className="nav-icon-btn"
|
||||||
|
title="私信"
|
||||||
|
style={{ position: 'relative', padding: '6px 8px', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-secondary)', borderRadius: 4, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}
|
||||||
|
onClick={() => setListOpen(true)}
|
||||||
|
>
|
||||||
|
✉️
|
||||||
|
{unread > 0 && (
|
||||||
|
<span style={{ position: 'absolute', top: -2, right: -2, background: '#ef4444', color: '#fff', borderRadius: '50%', padding: '2px 6px', fontSize: 10, fontWeight: 600, minWidth: 18, textAlign: 'center', lineHeight: 1.4 }}>
|
||||||
|
{unread > 99 ? '99+' : unread}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{listOpen && (
|
||||||
|
<ConversationList
|
||||||
|
onOpenChat={openChat}
|
||||||
|
onClose={() => setListOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{chat && (
|
||||||
|
<ChatWindow
|
||||||
|
conversationId={chat.conversationId}
|
||||||
|
otherUserId={chat.otherUserId}
|
||||||
|
otherUsername={chat.otherUsername}
|
||||||
|
onClose={closeChat}
|
||||||
|
onRefreshList={refreshList}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 供其他组件调用的打开私信(通过自定义事件桥接)
|
||||||
|
export function useOpenPrivateChat() {
|
||||||
|
const { currentUser } = useApp();
|
||||||
|
const open = async (otherUserId, otherUsername) => {
|
||||||
|
if (!currentUser) { alert('请先登录'); return; }
|
||||||
|
try {
|
||||||
|
const result = await API.getOrCreateConversation(otherUserId);
|
||||||
|
window.dispatchEvent(new CustomEvent('forumlify-open-chat', {
|
||||||
|
detail: { conversationId: result.id, otherUserId, otherUsername },
|
||||||
|
}));
|
||||||
|
} catch (err) {
|
||||||
|
alert('打开私信失败:' + err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return open;
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
// 私信 - 聊天窗口(3 秒轮询新消息)
|
||||||
|
import { useEffect, useState, useRef, useCallback } from 'react';
|
||||||
|
import { API } from '@/lib/api';
|
||||||
|
import { useApp } from '../AppProvider';
|
||||||
|
|
||||||
|
function avatar(username) {
|
||||||
|
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||||
|
'&background=6366f1&color=fff&size=64';
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
|
||||||
|
const { currentUser } = useApp();
|
||||||
|
const [messages, setMessages] = useState(null);
|
||||||
|
const [content, setContent] = useState('');
|
||||||
|
const containerRef = useRef(null);
|
||||||
|
|
||||||
|
const load = useCallback(async (silent = false) => {
|
||||||
|
if (!silent) setMessages(null);
|
||||||
|
try {
|
||||||
|
const data = await API.getMessages(conversationId);
|
||||||
|
setMessages(data || []);
|
||||||
|
} catch {
|
||||||
|
if (!silent) setMessages([]);
|
||||||
|
}
|
||||||
|
}, [conversationId]);
|
||||||
|
|
||||||
|
useEffect(() => { load(); }, [load]);
|
||||||
|
|
||||||
|
// 3 秒轮询
|
||||||
|
useEffect(() => {
|
||||||
|
const t = setInterval(() => load(true), 3000);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
// 自动滚动到底部
|
||||||
|
useEffect(() => {
|
||||||
|
if (containerRef.current) containerRef.current.scrollTop = containerRef.current.scrollHeight;
|
||||||
|
}, [messages]);
|
||||||
|
|
||||||
|
const send = async () => {
|
||||||
|
if (!content.trim()) return;
|
||||||
|
try {
|
||||||
|
await API.sendMessage(conversationId, content.trim());
|
||||||
|
setContent('');
|
||||||
|
load();
|
||||||
|
onRefreshList();
|
||||||
|
} catch (err) {
|
||||||
|
alert('发送失败:' + err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||||
|
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
|
||||||
|
<span id="chatTitle" style={{ fontWeight: 600, fontSize: 16 }}>{otherUsername}</span>
|
||||||
|
<span className="close" onClick={onClose} style={{ fontSize: 24, cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}>×</span>
|
||||||
|
</div>
|
||||||
|
<div id="chatMessages" ref={containerRef} style={{ flex: 1, overflowY: 'auto', padding: 16, minHeight: 300, maxHeight: 400 }}>
|
||||||
|
{messages === null ? (
|
||||||
|
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||||
|
) : messages.length === 0 ? (
|
||||||
|
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>还没有消息,打个招呼吧 👋</div>
|
||||||
|
) : (
|
||||||
|
messages.map((m) => {
|
||||||
|
const isMine = m.sender_id === currentUser?.id;
|
||||||
|
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
|
||||||
|
return (
|
||||||
|
<div key={m.id} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
|
||||||
|
{!isMine && (
|
||||||
|
<img src={m.sender_avatar_url || avatar(m.sender_username)} style={{ width: 32, height: 32, borderRadius: '50%', objectFit: 'cover', marginRight: 8, flexShrink: 0 }} alt="" />
|
||||||
|
)}
|
||||||
|
<div style={{ maxWidth: '70%' }}>
|
||||||
|
<div style={{
|
||||||
|
background: isMine ? 'var(--primary)' : 'var(--surface)',
|
||||||
|
color: isMine ? '#fff' : 'var(--text)',
|
||||||
|
padding: '10px 14px', borderRadius: 12,
|
||||||
|
border: isMine ? 'none' : '1px solid var(--border)',
|
||||||
|
wordBreak: 'break-word',
|
||||||
|
}}>
|
||||||
|
{m.content}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 11, color: 'var(--text-light)', marginTop: 4, textAlign: isMine ? 'right' : 'left' }}>
|
||||||
|
{time} {isMine ? (m.is_read ? '✓✓' : '✓') : ''}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', gap: 8, padding: '12px 16px', borderTop: '1px solid var(--border)' }}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="chatInput"
|
||||||
|
placeholder="输入消息..."
|
||||||
|
style={{ flex: 1, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
|
||||||
|
value={content}
|
||||||
|
onChange={(e) => setContent(e.target.value)}
|
||||||
|
onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
|
||||||
|
/>
|
||||||
|
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={send}>发送</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
// 私信 - 会话列表
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { API } from '@/lib/api';
|
||||||
|
|
||||||
|
function avatar(username) {
|
||||||
|
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||||
|
'&background=6366f1&color=fff&size=64';
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ConversationList({ onOpenChat, onClose }) {
|
||||||
|
const [conversations, setConversations] = useState(null);
|
||||||
|
|
||||||
|
const load = () => {
|
||||||
|
API.getConversations()
|
||||||
|
.then((data) => setConversations(data || []))
|
||||||
|
.catch(() => setConversations([]));
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(load, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||||
|
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
|
||||||
|
<h2 style={{ fontSize: 18, margin: 0 }}>✉️ 私信</h2>
|
||||||
|
<span className="close" onClick={onClose} style={{ fontSize: 24, cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}>×</span>
|
||||||
|
</div>
|
||||||
|
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
|
||||||
|
{conversations === null ? (
|
||||||
|
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||||
|
) : conversations.length === 0 ? (
|
||||||
|
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>暂无私信</div>
|
||||||
|
) : (
|
||||||
|
conversations.map((c) => {
|
||||||
|
const unread = c.unread_count || 0;
|
||||||
|
const lastMsg = c.last_message || '暂无消息';
|
||||||
|
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={c.id}
|
||||||
|
className="message-list-item"
|
||||||
|
style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderBottom: '1px solid var(--border)', cursor: 'pointer', transition: 'background 0.15s' }}
|
||||||
|
onClick={() => onOpenChat(c.id, c.other_user_id, c.other_username)}
|
||||||
|
>
|
||||||
|
<img src={c.other_avatar_url || avatar(c.other_username)} style={{ width: 40, height: 40, borderRadius: '50%', objectFit: 'cover' }} alt="" />
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||||
|
<span style={{ fontWeight: 600 }}>{c.other_username}</span>
|
||||||
|
<span style={{ fontSize: 12, color: 'var(--text-light)' }}>{time}</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||||
|
<span style={{ fontSize: 13, color: 'var(--text-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 200 }}>{lastMsg}</span>
|
||||||
|
{unread > 0 && (
|
||||||
|
<span style={{ background: '#ef4444', color: '#fff', borderRadius: '50%', padding: '2px 8px', fontSize: 11, fontWeight: 600 }}>{unread}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+13
@@ -102,6 +102,19 @@ export const API = {
|
|||||||
logEvent(action) {
|
logEvent(action) {
|
||||||
return apiFetch('/event-logs', { method: 'POST', body: JSON.stringify({ action }) }).catch(() => {});
|
return apiFetch('/event-logs', { method: 'POST', body: JSON.stringify({ action }) }).catch(() => {});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 私信
|
||||||
|
getConversations() { return apiFetch('/conversations'); },
|
||||||
|
getOrCreateConversation(other_user_id) {
|
||||||
|
return apiFetch('/conversations', { method: 'POST', body: JSON.stringify({ other_user_id }) });
|
||||||
|
},
|
||||||
|
getMessages(conversationId) { return apiFetch('/conversations/' + conversationId + '/messages'); },
|
||||||
|
sendMessage(conversationId, content) {
|
||||||
|
return apiFetch('/conversations/' + conversationId + '/messages', { method: 'POST', body: JSON.stringify({ content }) });
|
||||||
|
},
|
||||||
|
markMessageRead(messageId) {
|
||||||
|
return apiFetch('/messages/' + messageId + '/read', { method: 'PUT' });
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// 图片上传 (multipart)
|
// 图片上传 (multipart)
|
||||||
|
|||||||
+24
@@ -88,3 +88,27 @@ DROP TRIGGER IF EXISTS update_posts_updated_at ON posts;
|
|||||||
CREATE TRIGGER update_posts_updated_at
|
CREATE TRIGGER update_posts_updated_at
|
||||||
BEFORE UPDATE ON posts
|
BEFORE UPDATE ON posts
|
||||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
|
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 私信系统(conversations + messages)
|
||||||
|
-- ============================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS conversations (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user1_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
last_message_at TIMESTAMPTZ DEFAULT now(),
|
||||||
|
created_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
|
||||||
|
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
is_read BOOLEAN DEFAULT false,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_conversations_user1 ON conversations(user1_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_conversations_user2 ON conversations(user2_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_conversation ON messages(conversation_id);
|
||||||
Reference in new issue
Block a user