1.0
This commit is contained in:
@@ -0,0 +1,77 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
**青叶 (QingYe)** — a social chat application with teal-green theme (#009688 primary). Monorepo with `frontend/` (Vue 3) and `backend/` (Python FastAPI), all orchestrated via Docker Compose.
|
||||||
|
|
||||||
|
## Development Commands
|
||||||
|
|
||||||
|
All services run in Docker. No host dependencies needed.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up --build # Start all 4 services
|
||||||
|
docker compose up -d # Start detached
|
||||||
|
docker compose down # Stop
|
||||||
|
docker compose logs -f backend # View logs
|
||||||
|
docker compose restart backend # Restart a service
|
||||||
|
```
|
||||||
|
|
||||||
|
**Backend** runs on `localhost:8000`, **Frontend** on `localhost:5173`. Both have hot-reload via volume mounts. Database changes requiring new columns need manual `ALTER TABLE` or `docker compose restart backend` (which triggers `Base.metadata.create_all`).
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Backend (FastAPI + SQLAlchemy 2.0 async)
|
||||||
|
|
||||||
|
**Pattern**: Router → Service → Model, with Pydantic v2 schemas for request/response.
|
||||||
|
|
||||||
|
- `backend/app/main.py` — App entry, lifespan (creates DB tables, seeds config), router registration at `/api/v1/{module}`
|
||||||
|
- `backend/app/config.py` — Pydantic Settings from env vars
|
||||||
|
- `backend/app/database.py` — Async engine + session factory + declarative Base
|
||||||
|
- `backend/app/dependencies.py` — `get_db()`, `get_current_user()`, `get_admin_user()`
|
||||||
|
- `backend/app/utils/security.py` — JWT (HS256, 30min access / 7day refresh), bcrypt hashing
|
||||||
|
|
||||||
|
**API routes**: auth, users, conversations, messages, friends, admin, uploads, **moments** (friend circle)
|
||||||
|
|
||||||
|
**Models** (7 + 3 new): User, Conversation, ConversationMember, Message, Friend, FriendRequest, SystemConfig, **Moment, MomentLike, MomentComment**
|
||||||
|
|
||||||
|
**Key convention**: All IDs are `str(uuid.uuid4())`, not auto-increment. Services return dicts, not ORM objects. Timestamps use `datetime.utcnow()` (NOT timezone-aware — PostgreSQL columns are `TIMESTAMP WITHOUT TIME ZONE`).
|
||||||
|
|
||||||
|
### Frontend (Vue 3 + Vite + Naive UI)
|
||||||
|
|
||||||
|
**Pattern**: Composition API with `<script setup>`, Pinia stores, Axios API modules.
|
||||||
|
|
||||||
|
- `frontend/src/main.ts` — App entry, globally registers Naive UI components (MUST use `N`-prefixed names: `NButton` not `Button`)
|
||||||
|
- `frontend/src/layouts/UnifiedLayout.vue` — Main authenticated layout: 64px icon sidebar + 300px secondary panel + main content
|
||||||
|
- `frontend/src/router/index.ts` — All auth routes under `UnifiedLayout`, uses named `secondary` + `default` router-views
|
||||||
|
- `frontend/src/api/client.ts` — Axios with JWT interceptors and auto-refresh on 401
|
||||||
|
- `frontend/src/composables/useWebSocket.ts` — WebSocket client with exponential backoff reconnect
|
||||||
|
|
||||||
|
**CRITICAL**: Naive UI components must be registered with `N`-prefixed names (e.g., `app.component('NButton', NButton)`) because Vue resolves `<n-button>` to `NButton`. The `component.name` property returns `"Button"` (no prefix) — do NOT use `component.name` for registration.
|
||||||
|
|
||||||
|
### Database
|
||||||
|
|
||||||
|
PostgreSQL 16 with tables auto-created on startup. No Alembic migrations set up yet. Adding columns to existing tables requires:
|
||||||
|
1. Manual SQL: `docker compose exec postgres psql -U qingye -d qingye -c "ALTER TABLE ..."`
|
||||||
|
2. Then the model update will work
|
||||||
|
|
||||||
|
## Key Files
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `docker-compose.yml` | 4 services: postgres, redis, backend, frontend |
|
||||||
|
| `frontend/src/layouts/UnifiedLayout.vue` | Main layout with fixed left icon sidebar |
|
||||||
|
| `frontend/src/views/chat/ConversationListPanel.vue` | Reusable conversation list with 3 display modes |
|
||||||
|
| `frontend/src/views/chat/GroupInfoPanel.vue` | Group management (members, roles) |
|
||||||
|
| `frontend/src/views/chat/CreateGroupModal.vue` | Create group with friend selection |
|
||||||
|
| `frontend/src/views/moments/MomentsFeedView.vue` | Friend circle / moments feed |
|
||||||
|
| `frontend/src/views/moments/MomentCard.vue` | Single moment card with like/comment |
|
||||||
|
| `frontend/src/views/settings/` | Settings pages: profile, account (password+email), notifications, about |
|
||||||
|
| `backend/app/services/moment_service.py` | Moments business logic (feed, like, comment, visibility) |
|
||||||
|
| `backend/app/services/conversation_service.py` | Chat + group management (create, update, add/remove members) |
|
||||||
|
| `backend/app/services/friend_service.py` | Friend system (request, direct-add, remark) |
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
Defined in `.env.example`: `DATABASE_URL`, `REDIS_URL`, `JWT_SECRET_KEY`, `JWT_REFRESH_SECRET_KEY`, `CORS_ORIGINS`, `ADMIN_PASSWORD`, `VITE_API_BASE_URL`, `VITE_WS_BASE_URL`.
|
||||||
+2
-1
@@ -64,7 +64,7 @@ app.add_middleware(
|
|||||||
app.mount("/uploads", StaticFiles(directory=settings.UPLOAD_DIR), name="uploads")
|
app.mount("/uploads", StaticFiles(directory=settings.UPLOAD_DIR), name="uploads")
|
||||||
|
|
||||||
# 注册路由
|
# 注册路由
|
||||||
from app.routers import auth, users, conversations, messages, friends, admin, uploads
|
from app.routers import auth, users, conversations, messages, friends, admin, uploads, moments
|
||||||
|
|
||||||
app.include_router(auth.router, prefix="/api/v1/auth", tags=["认证"])
|
app.include_router(auth.router, prefix="/api/v1/auth", tags=["认证"])
|
||||||
app.include_router(users.router, prefix="/api/v1/users", tags=["用户"])
|
app.include_router(users.router, prefix="/api/v1/users", tags=["用户"])
|
||||||
@@ -73,6 +73,7 @@ app.include_router(messages.router, prefix="/api/v1/conversations", tags=["消
|
|||||||
app.include_router(friends.router, prefix="/api/v1/friends", tags=["好友"])
|
app.include_router(friends.router, prefix="/api/v1/friends", tags=["好友"])
|
||||||
app.include_router(admin.router, prefix="/api/v1/admin", tags=["管理"])
|
app.include_router(admin.router, prefix="/api/v1/admin", tags=["管理"])
|
||||||
app.include_router(uploads.router, prefix="/api/v1/uploads", tags=["上传"])
|
app.include_router(uploads.router, prefix="/api/v1/uploads", tags=["上传"])
|
||||||
|
app.include_router(moments.router, prefix="/api/v1/moments", tags=["朋友圈"])
|
||||||
|
|
||||||
# WebSocket
|
# WebSocket
|
||||||
from app.websocket.router import websocket_router
|
from app.websocket.router import websocket_router
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from app.models.message import Message
|
|||||||
from app.models.friend import Friend
|
from app.models.friend import Friend
|
||||||
from app.models.friend_request import FriendRequest
|
from app.models.friend_request import FriendRequest
|
||||||
from app.models.system_config import SystemConfig
|
from app.models.system_config import SystemConfig
|
||||||
|
from app.models.moment import Moment, MomentLike, MomentComment
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"User",
|
"User",
|
||||||
@@ -16,4 +17,7 @@ __all__ = [
|
|||||||
"Friend",
|
"Friend",
|
||||||
"FriendRequest",
|
"FriendRequest",
|
||||||
"SystemConfig",
|
"SystemConfig",
|
||||||
|
"Moment",
|
||||||
|
"MomentLike",
|
||||||
|
"MomentComment",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""朋友圈动态模型"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import String, Text, DateTime, ForeignKey, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Moment(Base):
|
||||||
|
__tablename__ = "moments"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
||||||
|
user_id: Mapped[str] = mapped_column(String(36), ForeignKey("users.id", ondelete="CASCADE"))
|
||||||
|
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
images: Mapped[str | None] = mapped_column(Text, nullable=True) # JSON array of URLs
|
||||||
|
visibility: Mapped[str] = mapped_column(String(20), default="friends") # public/friends/private
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.utcnow())
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
default=lambda: datetime.utcnow(),
|
||||||
|
onupdate=lambda: datetime.utcnow(),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 关系
|
||||||
|
user = relationship("User", foreign_keys=[user_id])
|
||||||
|
likes = relationship("MomentLike", back_populates="moment", cascade="all, delete-orphan")
|
||||||
|
comments = relationship("MomentComment", back_populates="moment", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class MomentLike(Base):
|
||||||
|
__tablename__ = "moment_likes"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("moment_id", "user_id", name="uq_moment_like"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
||||||
|
moment_id: Mapped[str] = mapped_column(String(36), ForeignKey("moments.id", ondelete="CASCADE"))
|
||||||
|
user_id: Mapped[str] = mapped_column(String(36), ForeignKey("users.id", ondelete="CASCADE"))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.utcnow())
|
||||||
|
|
||||||
|
moment = relationship("Moment", back_populates="likes")
|
||||||
|
user = relationship("User", foreign_keys=[user_id])
|
||||||
|
|
||||||
|
|
||||||
|
class MomentComment(Base):
|
||||||
|
__tablename__ = "moment_comments"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
||||||
|
moment_id: Mapped[str] = mapped_column(String(36), ForeignKey("moments.id", ondelete="CASCADE"))
|
||||||
|
user_id: Mapped[str] = mapped_column(String(36), ForeignKey("users.id", ondelete="CASCADE"))
|
||||||
|
content: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
reply_to_id: Mapped[str | None] = mapped_column(
|
||||||
|
String(36), ForeignKey("moment_comments.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.utcnow())
|
||||||
|
|
||||||
|
moment = relationship("Moment", back_populates="comments")
|
||||||
|
user = relationship("User", foreign_keys=[user_id])
|
||||||
|
reply_to = relationship("MomentComment", remote_side=[id])
|
||||||
@@ -13,6 +13,7 @@ class User(Base):
|
|||||||
|
|
||||||
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
||||||
username: Mapped[str] = mapped_column(String(50), unique=True, nullable=False, index=True)
|
username: Mapped[str] = mapped_column(String(50), unique=True, nullable=False, index=True)
|
||||||
|
nickname: Mapped[str | None] = mapped_column(String(50), nullable=True)
|
||||||
email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, index=True)
|
email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, index=True)
|
||||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
avatar_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
|
avatar_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
|
||||||
|
|||||||
@@ -5,7 +5,10 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.dependencies import get_db, get_current_user
|
from app.dependencies import get_db, get_current_user
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.schemas.conversation import ConversationCreate, ConversationRead, ConversationDetail, GroupCreate
|
from app.schemas.conversation import (
|
||||||
|
ConversationCreate, ConversationRead, ConversationDetail,
|
||||||
|
GroupCreate, GroupUpdate, MemberAdd, RoleUpdate,
|
||||||
|
)
|
||||||
from app.services.conversation_service import ConversationService
|
from app.services.conversation_service import ConversationService
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -65,3 +68,83 @@ async def get_conversation(
|
|||||||
if not detail:
|
if not detail:
|
||||||
raise HTTPException(status_code=404, detail="会话不存在或无权访问")
|
raise HTTPException(status_code=404, detail="会话不存在或无权访问")
|
||||||
return detail
|
return detail
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{conversation_id}")
|
||||||
|
async def update_group(
|
||||||
|
conversation_id: str,
|
||||||
|
req: GroupUpdate,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""更新群聊信息(群主/管理员)"""
|
||||||
|
service = ConversationService(db)
|
||||||
|
try:
|
||||||
|
await service.update_group(conversation_id, user.id, **req.model_dump(exclude_none=True))
|
||||||
|
return {"success": True, "message": "群信息已更新"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{conversation_id}/members")
|
||||||
|
async def add_members(
|
||||||
|
conversation_id: str,
|
||||||
|
req: MemberAdd,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""添加群成员(群主/管理员)"""
|
||||||
|
service = ConversationService(db)
|
||||||
|
try:
|
||||||
|
await service.add_members(conversation_id, user.id, req.user_ids)
|
||||||
|
return {"success": True, "message": "成员已添加"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{conversation_id}/members/{target_user_id}")
|
||||||
|
async def remove_member(
|
||||||
|
conversation_id: str,
|
||||||
|
target_user_id: str,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""移除群成员(群主/管理员)"""
|
||||||
|
service = ConversationService(db)
|
||||||
|
try:
|
||||||
|
await service.remove_member(conversation_id, user.id, target_user_id)
|
||||||
|
return {"success": True, "message": "成员已移除"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{conversation_id}/leave")
|
||||||
|
async def leave_group(
|
||||||
|
conversation_id: str,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""退出群聊"""
|
||||||
|
service = ConversationService(db)
|
||||||
|
try:
|
||||||
|
await service.leave_group(conversation_id, user.id)
|
||||||
|
return {"success": True, "message": "已退出群聊"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{conversation_id}/members/{target_user_id}/role")
|
||||||
|
async def update_member_role(
|
||||||
|
conversation_id: str,
|
||||||
|
target_user_id: str,
|
||||||
|
req: RoleUpdate,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""修改群成员角色(群主)"""
|
||||||
|
service = ConversationService(db)
|
||||||
|
try:
|
||||||
|
await service.update_member_role(conversation_id, user.id, target_user_id, req.role)
|
||||||
|
return {"success": True, "message": "角色已更新"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.dependencies import get_db, get_current_user
|
from app.dependencies import get_db, get_current_user
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.schemas.friend import FriendRequestCreate, FriendRead, FriendRequestRead
|
from app.schemas.friend import FriendRequestCreate, FriendRead, FriendRequestRead, RemarkUpdate
|
||||||
from app.services.friend_service import FriendService
|
from app.services.friend_service import FriendService
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -46,6 +46,37 @@ async def send_friend_request(
|
|||||||
raise HTTPException(status_code=400, detail=str(e))
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/add-direct")
|
||||||
|
async def add_friend_direct(
|
||||||
|
req: FriendRequestCreate,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""直接添加好友(跳过验证)"""
|
||||||
|
service = FriendService(db)
|
||||||
|
try:
|
||||||
|
await service.add_direct(user.id, req.to_user_id)
|
||||||
|
return {"success": True, "message": "已添加好友"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{friend_user_id}/remark")
|
||||||
|
async def update_friend_remark(
|
||||||
|
friend_user_id: str,
|
||||||
|
req: RemarkUpdate,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""修改好友备注"""
|
||||||
|
service = FriendService(db)
|
||||||
|
try:
|
||||||
|
await service.update_remark(user.id, friend_user_id, req.remark)
|
||||||
|
return {"success": True, "message": "备注已更新"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
@router.put("/request/{request_id}/accept")
|
@router.put("/request/{request_id}/accept")
|
||||||
async def accept_friend_request(
|
async def accept_friend_request(
|
||||||
request_id: str,
|
request_id: str,
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""朋友圈路由"""
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.dependencies import get_db, get_current_user
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.moment import MomentCreate, MomentCommentCreate
|
||||||
|
from app.services.moment_service import MomentService
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/")
|
||||||
|
async def get_feed(
|
||||||
|
cursor: str | None = Query(None),
|
||||||
|
limit: int = Query(20, ge=1, le=50),
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取朋友圈 feed"""
|
||||||
|
service = MomentService(db)
|
||||||
|
return await service.get_feed(user.id, cursor, limit)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/")
|
||||||
|
async def create_moment(
|
||||||
|
req: MomentCreate,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""发布动态"""
|
||||||
|
service = MomentService(db)
|
||||||
|
try:
|
||||||
|
moment = await service.create_moment(user.id, req.content, req.images, req.visibility)
|
||||||
|
detail = await service.get_feed(user.id, limit=1)
|
||||||
|
return detail[0] if detail else {"success": True}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/user/{target_user_id}")
|
||||||
|
async def get_user_moments(
|
||||||
|
target_user_id: str,
|
||||||
|
cursor: str | None = Query(None),
|
||||||
|
limit: int = Query(20, ge=1, le=50),
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取指定用户的动态"""
|
||||||
|
service = MomentService(db)
|
||||||
|
return await service.get_user_moments(target_user_id, user.id, cursor, limit)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{moment_id}")
|
||||||
|
async def get_moment(
|
||||||
|
moment_id: str,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取单条动态详情"""
|
||||||
|
service = MomentService(db)
|
||||||
|
feed = await service.get_feed(user.id, limit=100)
|
||||||
|
moment = next((m for m in feed if m["id"] == moment_id), None)
|
||||||
|
if not moment:
|
||||||
|
raise HTTPException(status_code=404, detail="动态不存在")
|
||||||
|
return moment
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{moment_id}")
|
||||||
|
async def delete_moment(
|
||||||
|
moment_id: str,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""删除动态"""
|
||||||
|
service = MomentService(db)
|
||||||
|
try:
|
||||||
|
await service.delete_moment(moment_id, user.id)
|
||||||
|
return {"success": True, "message": "动态已删除"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{moment_id}/like")
|
||||||
|
async def toggle_like(
|
||||||
|
moment_id: str,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""点赞/取消点赞"""
|
||||||
|
service = MomentService(db)
|
||||||
|
try:
|
||||||
|
is_liked = await service.toggle_like(moment_id, user.id)
|
||||||
|
return {"success": True, "is_liked": is_liked}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{moment_id}/comments")
|
||||||
|
async def get_comments(
|
||||||
|
moment_id: str,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取评论列表"""
|
||||||
|
service = MomentService(db)
|
||||||
|
return await service.get_comments(moment_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{moment_id}/comments")
|
||||||
|
async def add_comment(
|
||||||
|
moment_id: str,
|
||||||
|
req: MomentCommentCreate,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""添加评论"""
|
||||||
|
service = MomentService(db)
|
||||||
|
try:
|
||||||
|
comment = await service.add_comment(moment_id, user.id, req.content, req.reply_to_id)
|
||||||
|
return comment
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{moment_id}/comments/{comment_id}")
|
||||||
|
async def delete_comment(
|
||||||
|
moment_id: str,
|
||||||
|
comment_id: str,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""删除评论"""
|
||||||
|
service = MomentService(db)
|
||||||
|
try:
|
||||||
|
await service.delete_comment(comment_id, user.id)
|
||||||
|
return {"success": True, "message": "评论已删除"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
@@ -5,7 +5,10 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.dependencies import get_db, get_current_user
|
from app.dependencies import get_db, get_current_user
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.schemas.user import UserRead, UserProfile, UserUpdate, UserSearchResult
|
from app.schemas.user import (
|
||||||
|
UserRead, UserProfile, UserUpdate, UserSearchResult,
|
||||||
|
PasswordChange, EmailChange,
|
||||||
|
)
|
||||||
from app.services.user_service import UserService
|
from app.services.user_service import UserService
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -29,6 +32,36 @@ async def update_me(
|
|||||||
return updated
|
return updated
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/me/password")
|
||||||
|
async def change_password(
|
||||||
|
req: PasswordChange,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""修改密码"""
|
||||||
|
service = UserService(db)
|
||||||
|
try:
|
||||||
|
await service.change_password(user.id, req.old_password, req.new_password)
|
||||||
|
return {"success": True, "message": "密码修改成功"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/me/email")
|
||||||
|
async def change_email(
|
||||||
|
req: EmailChange,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""更换绑定邮箱"""
|
||||||
|
service = UserService(db)
|
||||||
|
try:
|
||||||
|
await service.change_email(user.id, req.email, req.password)
|
||||||
|
return {"success": True, "message": "邮箱已更新"}
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
@router.get("/search", response_model=list[UserSearchResult])
|
@router.get("/search", response_model=list[UserSearchResult])
|
||||||
async def search_users(
|
async def search_users(
|
||||||
q: str = Query(..., min_length=1),
|
q: str = Query(..., min_length=1),
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ class RefreshRequest(BaseModel):
|
|||||||
class UserBrief(BaseModel):
|
class UserBrief(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
username: str
|
username: str
|
||||||
|
nickname: str | None = None
|
||||||
avatar_url: str | None = None
|
avatar_url: str | None = None
|
||||||
is_admin: bool = False
|
is_admin: bool = False
|
||||||
|
|
||||||
|
|||||||
@@ -51,3 +51,17 @@ class GroupCreate(BaseModel):
|
|||||||
name: str = Field(..., min_length=1, max_length=100)
|
name: str = Field(..., min_length=1, max_length=100)
|
||||||
description: str | None = Field(None, max_length=500)
|
description: str | None = Field(None, max_length=500)
|
||||||
member_ids: list[str] = Field(..., min_length=1)
|
member_ids: list[str] = Field(..., min_length=1)
|
||||||
|
|
||||||
|
|
||||||
|
class GroupUpdate(BaseModel):
|
||||||
|
name: str | None = Field(None, max_length=100)
|
||||||
|
description: str | None = Field(None, max_length=500)
|
||||||
|
avatar_url: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class MemberAdd(BaseModel):
|
||||||
|
user_ids: list[str] = Field(..., min_length=1)
|
||||||
|
|
||||||
|
|
||||||
|
class RoleUpdate(BaseModel):
|
||||||
|
role: str = Field(..., pattern="^(admin|member)$")
|
||||||
|
|||||||
@@ -34,3 +34,7 @@ class FriendRead(BaseModel):
|
|||||||
status: str = "offline"
|
status: str = "offline"
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
|
class RemarkUpdate(BaseModel):
|
||||||
|
remark: str | None = None
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""朋友圈相关 Schema"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class MomentCreate(BaseModel):
|
||||||
|
content: str = Field(..., min_length=1, max_length=1000)
|
||||||
|
images: list[str] | None = Field(None, max_length=9)
|
||||||
|
visibility: str = Field("friends", pattern="^(public|friends|private)$")
|
||||||
|
|
||||||
|
|
||||||
|
class MomentRead(BaseModel):
|
||||||
|
id: str
|
||||||
|
user_id: str
|
||||||
|
username: str
|
||||||
|
nickname: str | None = None
|
||||||
|
avatar_url: str | None = None
|
||||||
|
content: str
|
||||||
|
images: list[str] = []
|
||||||
|
visibility: str
|
||||||
|
like_count: int = 0
|
||||||
|
is_liked: bool = False
|
||||||
|
comment_count: int = 0
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
|
class MomentCommentCreate(BaseModel):
|
||||||
|
content: str = Field(..., min_length=1, max_length=500)
|
||||||
|
reply_to_id: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class MomentCommentRead(BaseModel):
|
||||||
|
id: str
|
||||||
|
moment_id: str
|
||||||
|
user_id: str
|
||||||
|
username: str
|
||||||
|
nickname: str | None = None
|
||||||
|
avatar_url: str | None = None
|
||||||
|
content: str
|
||||||
|
reply_to_id: str | None = None
|
||||||
|
reply_to_username: str | None = None
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
@@ -2,16 +2,18 @@
|
|||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, EmailStr, Field
|
||||||
|
|
||||||
|
|
||||||
class UserRead(BaseModel):
|
class UserRead(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
username: str
|
username: str
|
||||||
|
nickname: str | None = None
|
||||||
email: str
|
email: str
|
||||||
avatar_url: str | None = None
|
avatar_url: str | None = None
|
||||||
bio: str | None = None
|
bio: str | None = None
|
||||||
status: str = "offline"
|
status: str = "offline"
|
||||||
|
is_admin: bool = False
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
model_config = {"from_attributes": True}
|
||||||
@@ -21,6 +23,7 @@ class UserProfile(BaseModel):
|
|||||||
"""他人可见的公开信息"""
|
"""他人可见的公开信息"""
|
||||||
id: str
|
id: str
|
||||||
username: str
|
username: str
|
||||||
|
nickname: str | None = None
|
||||||
avatar_url: str | None = None
|
avatar_url: str | None = None
|
||||||
bio: str | None = None
|
bio: str | None = None
|
||||||
status: str = "offline"
|
status: str = "offline"
|
||||||
@@ -30,6 +33,7 @@ class UserProfile(BaseModel):
|
|||||||
|
|
||||||
class UserUpdate(BaseModel):
|
class UserUpdate(BaseModel):
|
||||||
username: str | None = Field(None, min_length=2, max_length=50)
|
username: str | None = Field(None, min_length=2, max_length=50)
|
||||||
|
nickname: str | None = Field(None, max_length=50)
|
||||||
bio: str | None = Field(None, max_length=200)
|
bio: str | None = Field(None, max_length=200)
|
||||||
avatar_url: str | None = None
|
avatar_url: str | None = None
|
||||||
|
|
||||||
@@ -39,9 +43,15 @@ class PasswordChange(BaseModel):
|
|||||||
new_password: str = Field(..., min_length=6, max_length=100)
|
new_password: str = Field(..., min_length=6, max_length=100)
|
||||||
|
|
||||||
|
|
||||||
|
class EmailChange(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
class UserSearchResult(BaseModel):
|
class UserSearchResult(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
username: str
|
username: str
|
||||||
|
nickname: str | None = None
|
||||||
avatar_url: str | None = None
|
avatar_url: str | None = None
|
||||||
bio: str | None = None
|
bio: str | None = None
|
||||||
status: str = "offline"
|
status: str = "offline"
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
"""会话服务"""
|
"""会话服务"""
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime
|
||||||
|
|
||||||
from sqlalchemy import select, and_
|
from sqlalchemy import select, func
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from sqlalchemy.orm import selectinload
|
|
||||||
|
|
||||||
from app.models.conversation import Conversation
|
from app.models.conversation import Conversation
|
||||||
from app.models.conversation_member import ConversationMember
|
from app.models.conversation_member import ConversationMember
|
||||||
@@ -18,7 +17,6 @@ class ConversationService:
|
|||||||
|
|
||||||
async def get_or_create_private(self, user1_id: str, user2_id: str) -> Conversation:
|
async def get_or_create_private(self, user1_id: str, user2_id: str) -> Conversation:
|
||||||
"""获取或创建私聊会话"""
|
"""获取或创建私聊会话"""
|
||||||
# 查找已有的私聊
|
|
||||||
result = await self.db.execute(
|
result = await self.db.execute(
|
||||||
select(Conversation).join(ConversationMember)
|
select(Conversation).join(ConversationMember)
|
||||||
.where(
|
.where(
|
||||||
@@ -36,12 +34,10 @@ class ConversationService:
|
|||||||
if member_result.scalars().first():
|
if member_result.scalars().first():
|
||||||
return conv
|
return conv
|
||||||
|
|
||||||
# 创建新私聊
|
|
||||||
conv = Conversation(id=str(uuid.uuid4()), type="private")
|
conv = Conversation(id=str(uuid.uuid4()), type="private")
|
||||||
self.db.add(conv)
|
self.db.add(conv)
|
||||||
await self.db.flush()
|
await self.db.flush()
|
||||||
|
|
||||||
# 添加两个成员
|
|
||||||
self.db.add(ConversationMember(
|
self.db.add(ConversationMember(
|
||||||
id=str(uuid.uuid4()), conversation_id=conv.id, user_id=user1_id, role="member"
|
id=str(uuid.uuid4()), conversation_id=conv.id, user_id=user1_id, role="member"
|
||||||
))
|
))
|
||||||
@@ -63,12 +59,10 @@ class ConversationService:
|
|||||||
self.db.add(conv)
|
self.db.add(conv)
|
||||||
await self.db.flush()
|
await self.db.flush()
|
||||||
|
|
||||||
# 创建者为 owner
|
|
||||||
self.db.add(ConversationMember(
|
self.db.add(ConversationMember(
|
||||||
id=str(uuid.uuid4()), conversation_id=conv.id,
|
id=str(uuid.uuid4()), conversation_id=conv.id,
|
||||||
user_id=creator_id, role="owner"
|
user_id=creator_id, role="owner"
|
||||||
))
|
))
|
||||||
# 其他成员
|
|
||||||
for mid in member_ids:
|
for mid in member_ids:
|
||||||
if mid != creator_id:
|
if mid != creator_id:
|
||||||
self.db.add(ConversationMember(
|
self.db.add(ConversationMember(
|
||||||
@@ -77,6 +71,86 @@ class ConversationService:
|
|||||||
))
|
))
|
||||||
return conv
|
return conv
|
||||||
|
|
||||||
|
async def update_group(self, conv_id: str, user_id: str, **kwargs):
|
||||||
|
"""更新群聊信息(仅群主/管理员)"""
|
||||||
|
conv = await self._get_conv_if_admin(conv_id, user_id)
|
||||||
|
for key, value in kwargs.items():
|
||||||
|
if value is not None and hasattr(conv, key):
|
||||||
|
setattr(conv, key, value)
|
||||||
|
|
||||||
|
async def add_members(self, conv_id: str, user_id: str, new_member_ids: list[str]):
|
||||||
|
"""添加群成员(仅群主/管理员)"""
|
||||||
|
await self._get_conv_if_admin(conv_id, user_id)
|
||||||
|
for mid in new_member_ids:
|
||||||
|
# 检查是否已在群中
|
||||||
|
existing = await self.db.execute(
|
||||||
|
select(ConversationMember).where(
|
||||||
|
ConversationMember.conversation_id == conv_id,
|
||||||
|
ConversationMember.user_id == mid,
|
||||||
|
ConversationMember.left_at.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if not existing.scalars().first():
|
||||||
|
self.db.add(ConversationMember(
|
||||||
|
id=str(uuid.uuid4()), conversation_id=conv_id,
|
||||||
|
user_id=mid, role="member"
|
||||||
|
))
|
||||||
|
|
||||||
|
async def remove_member(self, conv_id: str, user_id: str, target_user_id: str):
|
||||||
|
"""移除群成员(仅群主/管理员,不能移除群主)"""
|
||||||
|
await self._get_conv_if_admin(conv_id, user_id)
|
||||||
|
member = await self._get_member(conv_id, target_user_id)
|
||||||
|
if not member:
|
||||||
|
raise ValueError("该用户不在群中")
|
||||||
|
if member.role == "owner":
|
||||||
|
raise ValueError("不能移除群主")
|
||||||
|
member.left_at = datetime.utcnow()
|
||||||
|
|
||||||
|
async def leave_group(self, conv_id: str, user_id: str):
|
||||||
|
"""退出群聊"""
|
||||||
|
member = await self._get_member(conv_id, user_id)
|
||||||
|
if not member:
|
||||||
|
raise ValueError("你不在该群中")
|
||||||
|
if member.role == "owner":
|
||||||
|
raise ValueError("群主不能退出,请先转让群主身份")
|
||||||
|
member.left_at = datetime.utcnow()
|
||||||
|
|
||||||
|
async def update_member_role(self, conv_id: str, user_id: str, target_user_id: str, role: str):
|
||||||
|
"""修改成员角色(仅群主)"""
|
||||||
|
member = await self._get_member(conv_id, user_id)
|
||||||
|
if not member or member.role != "owner":
|
||||||
|
raise ValueError("只有群主可以修改角色")
|
||||||
|
target = await self._get_member(conv_id, target_user_id)
|
||||||
|
if not target:
|
||||||
|
raise ValueError("目标用户不在群中")
|
||||||
|
target.role = role
|
||||||
|
|
||||||
|
async def _get_conv_if_admin(self, conv_id: str, user_id: str) -> Conversation:
|
||||||
|
"""获取会话并验证管理员权限"""
|
||||||
|
conv_result = await self.db.execute(
|
||||||
|
select(Conversation).where(Conversation.id == conv_id)
|
||||||
|
)
|
||||||
|
conv = conv_result.scalars().first()
|
||||||
|
if not conv:
|
||||||
|
raise ValueError("会话不存在")
|
||||||
|
if conv.type != "group":
|
||||||
|
raise ValueError("仅群聊支持此操作")
|
||||||
|
member = await self._get_member(conv_id, user_id)
|
||||||
|
if not member or member.role not in ("owner", "admin"):
|
||||||
|
raise ValueError("仅群主或管理员可执行此操作")
|
||||||
|
return conv
|
||||||
|
|
||||||
|
async def _get_member(self, conv_id: str, user_id: str) -> ConversationMember | None:
|
||||||
|
"""获取成员记录"""
|
||||||
|
result = await self.db.execute(
|
||||||
|
select(ConversationMember).where(
|
||||||
|
ConversationMember.conversation_id == conv_id,
|
||||||
|
ConversationMember.user_id == user_id,
|
||||||
|
ConversationMember.left_at.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return result.scalars().first()
|
||||||
|
|
||||||
async def get_user_conversations(self, user_id: str) -> list[dict]:
|
async def get_user_conversations(self, user_id: str) -> list[dict]:
|
||||||
"""获取用户的会话列表"""
|
"""获取用户的会话列表"""
|
||||||
result = await self.db.execute(
|
result = await self.db.execute(
|
||||||
@@ -95,17 +169,15 @@ class ConversationService:
|
|||||||
if not conv:
|
if not conv:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 获取未读数
|
|
||||||
unread = await self._get_unread_count(conv.id, member.last_read_message_id)
|
unread = await self._get_unread_count(conv.id, member.last_read_message_id)
|
||||||
|
|
||||||
# 获取显示信息
|
|
||||||
display_name = conv.name
|
display_name = conv.name
|
||||||
display_avatar = conv.avatar_url
|
display_avatar = conv.avatar_url
|
||||||
|
|
||||||
if conv.type == "private":
|
if conv.type == "private":
|
||||||
other = await self._get_other_member(conv.id, user_id)
|
other = await self._get_other_member(conv.id, user_id)
|
||||||
if other:
|
if other:
|
||||||
display_name = other.username
|
display_name = other.nickname or other.username
|
||||||
display_avatar = other.avatar_url
|
display_avatar = other.avatar_url
|
||||||
|
|
||||||
conversations.append({
|
conversations.append({
|
||||||
@@ -120,7 +192,6 @@ class ConversationService:
|
|||||||
"created_at": conv.created_at,
|
"created_at": conv.created_at,
|
||||||
})
|
})
|
||||||
|
|
||||||
# 按最后消息时间排序
|
|
||||||
conversations.sort(key=lambda x: x["last_message_at"] or x["created_at"], reverse=True)
|
conversations.sort(key=lambda x: x["last_message_at"] or x["created_at"], reverse=True)
|
||||||
return conversations
|
return conversations
|
||||||
|
|
||||||
@@ -133,7 +204,6 @@ class ConversationService:
|
|||||||
if not conv:
|
if not conv:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 验证成员身份
|
|
||||||
member_result = await self.db.execute(
|
member_result = await self.db.execute(
|
||||||
select(ConversationMember).where(
|
select(ConversationMember).where(
|
||||||
ConversationMember.conversation_id == conv_id,
|
ConversationMember.conversation_id == conv_id,
|
||||||
@@ -144,7 +214,6 @@ class ConversationService:
|
|||||||
if not member_result.scalars().first():
|
if not member_result.scalars().first():
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 获取所有成员
|
|
||||||
members_result = await self.db.execute(
|
members_result = await self.db.execute(
|
||||||
select(ConversationMember).where(
|
select(ConversationMember).where(
|
||||||
ConversationMember.conversation_id == conv_id,
|
ConversationMember.conversation_id == conv_id,
|
||||||
@@ -160,7 +229,7 @@ class ConversationService:
|
|||||||
"id": m.id,
|
"id": m.id,
|
||||||
"user_id": user.id,
|
"user_id": user.id,
|
||||||
"username": user.username,
|
"username": user.username,
|
||||||
"nickname": user.bio,
|
"nickname": user.nickname,
|
||||||
"avatar_url": user.avatar_url,
|
"avatar_url": user.avatar_url,
|
||||||
"role": m.role,
|
"role": m.role,
|
||||||
"joined_at": m.joined_at,
|
"joined_at": m.joined_at,
|
||||||
@@ -196,12 +265,11 @@ class ConversationService:
|
|||||||
async def _get_unread_count(self, conv_id: str, last_read_id: str | None) -> int:
|
async def _get_unread_count(self, conv_id: str, last_read_id: str | None) -> int:
|
||||||
"""计算未读消息数"""
|
"""计算未读消息数"""
|
||||||
from app.models.message import Message
|
from app.models.message import Message
|
||||||
query = select(func := __import__("sqlalchemy").func).count(Message.id).where(
|
query = select(func.count(Message.id)).where(
|
||||||
Message.conversation_id == conv_id,
|
Message.conversation_id == conv_id,
|
||||||
Message.is_deleted == False,
|
Message.is_deleted == False,
|
||||||
)
|
)
|
||||||
if last_read_id:
|
if last_read_id:
|
||||||
# 获取 last_read 消息的时间
|
|
||||||
lr = await self.db.execute(select(Message).where(Message.id == last_read_id))
|
lr = await self.db.execute(select(Message).where(Message.id == last_read_id))
|
||||||
lr_msg = lr.scalars().first()
|
lr_msg = lr.scalars().first()
|
||||||
if lr_msg:
|
if lr_msg:
|
||||||
|
|||||||
@@ -113,7 +113,7 @@ class FriendService:
|
|||||||
"id": friendship.id,
|
"id": friendship.id,
|
||||||
"friend_user_id": user.id,
|
"friend_user_id": user.id,
|
||||||
"username": user.username,
|
"username": user.username,
|
||||||
"nickname": user.bio,
|
"nickname": user.nickname,
|
||||||
"avatar_url": user.avatar_url,
|
"avatar_url": user.avatar_url,
|
||||||
"remark": friendship.remark,
|
"remark": friendship.remark,
|
||||||
"status": user.status,
|
"status": user.status,
|
||||||
@@ -160,3 +160,46 @@ class FriendService:
|
|||||||
(Friend.user_id == friend_id) & (Friend.friend_user_id == user_id)
|
(Friend.user_id == friend_id) & (Friend.friend_user_id == user_id)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def add_direct(self, from_user_id: str, to_user_id: str):
|
||||||
|
"""直接添加好友(跳过验证)"""
|
||||||
|
if from_user_id == to_user_id:
|
||||||
|
raise ValueError("不能添加自己为好友")
|
||||||
|
|
||||||
|
# 检查目标用户是否存在
|
||||||
|
target = await self.db.execute(select(User).where(User.id == to_user_id))
|
||||||
|
if not target.scalars().first():
|
||||||
|
raise ValueError("目标用户不存在")
|
||||||
|
|
||||||
|
# 检查是否已是好友
|
||||||
|
existing = await self.db.execute(
|
||||||
|
select(Friend).where(
|
||||||
|
Friend.user_id == from_user_id,
|
||||||
|
Friend.friend_user_id == to_user_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if existing.scalars().first():
|
||||||
|
raise ValueError("已经是好友了")
|
||||||
|
|
||||||
|
# 创建双向好友关系
|
||||||
|
self.db.add(Friend(
|
||||||
|
id=str(uuid.uuid4()), user_id=from_user_id,
|
||||||
|
friend_user_id=to_user_id,
|
||||||
|
))
|
||||||
|
self.db.add(Friend(
|
||||||
|
id=str(uuid.uuid4()), user_id=to_user_id,
|
||||||
|
friend_user_id=from_user_id,
|
||||||
|
))
|
||||||
|
|
||||||
|
async def update_remark(self, user_id: str, friend_user_id: str, remark: str | None):
|
||||||
|
"""修改好友备注"""
|
||||||
|
result = await self.db.execute(
|
||||||
|
select(Friend).where(
|
||||||
|
Friend.user_id == user_id,
|
||||||
|
Friend.friend_user_id == friend_user_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
friendship = result.scalars().first()
|
||||||
|
if not friendship:
|
||||||
|
raise ValueError("好友关系不存在")
|
||||||
|
friendship.remark = remark
|
||||||
|
|||||||
@@ -0,0 +1,312 @@
|
|||||||
|
"""朋友圈服务"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import select, func, and_
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.moment import Moment, MomentLike, MomentComment
|
||||||
|
from app.models.friend import Friend
|
||||||
|
from app.models.user import User
|
||||||
|
|
||||||
|
|
||||||
|
class MomentService:
|
||||||
|
def __init__(self, db: AsyncSession):
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
async def create_moment(self, user_id: str, content: str,
|
||||||
|
images: list[str] | None = None,
|
||||||
|
visibility: str = "friends") -> Moment:
|
||||||
|
"""发布动态"""
|
||||||
|
moment = Moment(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
user_id=user_id,
|
||||||
|
content=content,
|
||||||
|
images=json.dumps(images) if images else None,
|
||||||
|
visibility=visibility,
|
||||||
|
)
|
||||||
|
self.db.add(moment)
|
||||||
|
await self.db.flush()
|
||||||
|
return moment
|
||||||
|
|
||||||
|
async def get_feed(self, user_id: str, cursor: str | None = None,
|
||||||
|
limit: int = 20) -> list[dict]:
|
||||||
|
"""获取朋友圈 feed(自己 + 好友的动态)"""
|
||||||
|
# 获取好友ID列表
|
||||||
|
friend_ids = await self._get_friend_ids(user_id)
|
||||||
|
# 可以看到的人:自己 + 好友
|
||||||
|
visible_user_ids = [user_id] + friend_ids
|
||||||
|
|
||||||
|
query = (
|
||||||
|
select(Moment)
|
||||||
|
.where(
|
||||||
|
Moment.user_id.in_(visible_user_ids),
|
||||||
|
Moment.visibility != "private", # 私密动态只有自己能看到(下面单独处理)
|
||||||
|
)
|
||||||
|
.order_by(Moment.created_at.desc())
|
||||||
|
.limit(limit)
|
||||||
|
)
|
||||||
|
|
||||||
|
# 也获取自己的私密动态
|
||||||
|
own_private_query = (
|
||||||
|
select(Moment)
|
||||||
|
.where(Moment.user_id == user_id, Moment.visibility == "private")
|
||||||
|
.order_by(Moment.created_at.desc())
|
||||||
|
.limit(limit)
|
||||||
|
)
|
||||||
|
|
||||||
|
if cursor:
|
||||||
|
cursor_result = await self.db.execute(
|
||||||
|
select(Moment.created_at).where(Moment.id == cursor)
|
||||||
|
)
|
||||||
|
cursor_time = cursor_result.scalar()
|
||||||
|
if cursor_time:
|
||||||
|
query = query.where(Moment.created_at < cursor_time)
|
||||||
|
own_private_query = own_private_query.where(Moment.created_at < cursor_time)
|
||||||
|
|
||||||
|
result = await self.db.execute(query)
|
||||||
|
own_private_result = await self.db.execute(own_private_query)
|
||||||
|
|
||||||
|
moments = list(result.scalars().all())
|
||||||
|
moments.extend(own_private_result.scalars().all())
|
||||||
|
|
||||||
|
# 合并并去重、排序
|
||||||
|
seen_ids = set()
|
||||||
|
unique = []
|
||||||
|
for m in moments:
|
||||||
|
if m.id not in seen_ids:
|
||||||
|
seen_ids.add(m.id)
|
||||||
|
unique.append(m)
|
||||||
|
unique.sort(key=lambda x: x.created_at, reverse=True)
|
||||||
|
unique = unique[:limit]
|
||||||
|
|
||||||
|
return [await self._moment_to_dict(m, user_id) for m in unique]
|
||||||
|
|
||||||
|
async def get_user_moments(self, user_id: str, viewer_id: str | None = None,
|
||||||
|
cursor: str | None = None, limit: int = 20) -> list[dict]:
|
||||||
|
"""获取指定用户的动态"""
|
||||||
|
query = (
|
||||||
|
select(Moment)
|
||||||
|
.where(Moment.user_id == user_id)
|
||||||
|
.order_by(Moment.created_at.desc())
|
||||||
|
.limit(limit)
|
||||||
|
)
|
||||||
|
if cursor:
|
||||||
|
cursor_result = await self.db.execute(
|
||||||
|
select(Moment.created_at).where(Moment.id == cursor)
|
||||||
|
)
|
||||||
|
cursor_time = cursor_result.scalar()
|
||||||
|
if cursor_time:
|
||||||
|
query = query.where(Moment.created_at < cursor_time)
|
||||||
|
|
||||||
|
result = await self.db.execute(query)
|
||||||
|
moments = list(result.scalars().all())
|
||||||
|
|
||||||
|
# 过滤可见性
|
||||||
|
filtered = []
|
||||||
|
for m in moments:
|
||||||
|
if m.visibility == "public":
|
||||||
|
filtered.append(m)
|
||||||
|
elif m.visibility == "friends":
|
||||||
|
if viewer_id and (viewer_id == user_id or await self._are_friends(viewer_id, user_id)):
|
||||||
|
filtered.append(m)
|
||||||
|
elif m.visibility == "private":
|
||||||
|
if viewer_id == user_id:
|
||||||
|
filtered.append(m)
|
||||||
|
|
||||||
|
return [await self._moment_to_dict(m, viewer_id) for m in filtered]
|
||||||
|
|
||||||
|
async def delete_moment(self, moment_id: str, user_id: str):
|
||||||
|
"""删除动态(仅作者)"""
|
||||||
|
result = await self.db.execute(select(Moment).where(Moment.id == moment_id))
|
||||||
|
moment = result.scalars().first()
|
||||||
|
if not moment:
|
||||||
|
raise ValueError("动态不存在")
|
||||||
|
if moment.user_id != user_id:
|
||||||
|
raise ValueError("只能删除自己的动态")
|
||||||
|
await self.db.delete(moment)
|
||||||
|
|
||||||
|
async def toggle_like(self, moment_id: str, user_id: str) -> bool:
|
||||||
|
"""点赞/取消点赞,返回是否已点赞"""
|
||||||
|
result = await self.db.execute(
|
||||||
|
select(MomentLike).where(
|
||||||
|
MomentLike.moment_id == moment_id,
|
||||||
|
MomentLike.user_id == user_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
existing = result.scalars().first()
|
||||||
|
if existing:
|
||||||
|
await self.db.delete(existing)
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
self.db.add(MomentLike(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
moment_id=moment_id,
|
||||||
|
user_id=user_id,
|
||||||
|
))
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def add_comment(self, moment_id: str, user_id: str, content: str,
|
||||||
|
reply_to_id: str | None = None) -> dict:
|
||||||
|
"""添加评论"""
|
||||||
|
# 验证动态存在
|
||||||
|
moment_result = await self.db.execute(select(Moment).where(Moment.id == moment_id))
|
||||||
|
if not moment_result.scalars().first():
|
||||||
|
raise ValueError("动态不存在")
|
||||||
|
|
||||||
|
comment = MomentComment(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
moment_id=moment_id,
|
||||||
|
user_id=user_id,
|
||||||
|
content=content,
|
||||||
|
reply_to_id=reply_to_id,
|
||||||
|
)
|
||||||
|
self.db.add(comment)
|
||||||
|
await self.db.flush()
|
||||||
|
|
||||||
|
# 返回带用户信息的评论
|
||||||
|
user_result = await self.db.execute(select(User).where(User.id == user_id))
|
||||||
|
user = user_result.scalars().first()
|
||||||
|
|
||||||
|
reply_to_username = None
|
||||||
|
if reply_to_id:
|
||||||
|
rt_result = await self.db.execute(select(User).where(User.id == comment.reply_to_id))
|
||||||
|
# reply_to_id 是评论 ID,需要找到评论者的 user
|
||||||
|
rt_comment = await self.db.execute(
|
||||||
|
select(MomentComment).where(MomentComment.id == reply_to_id)
|
||||||
|
)
|
||||||
|
rt_c = rt_comment.scalars().first()
|
||||||
|
if rt_c:
|
||||||
|
rt_user = await self.db.execute(select(User).where(User.id == rt_c.user_id))
|
||||||
|
rt_u = rt_user.scalars().first()
|
||||||
|
reply_to_username = rt_u.username if rt_u else None
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": comment.id,
|
||||||
|
"moment_id": moment_id,
|
||||||
|
"user_id": user_id,
|
||||||
|
"username": user.username if user else "未知",
|
||||||
|
"nickname": user.nickname if user else None,
|
||||||
|
"avatar_url": user.avatar_url if user else None,
|
||||||
|
"content": content,
|
||||||
|
"reply_to_id": reply_to_id,
|
||||||
|
"reply_to_username": reply_to_username,
|
||||||
|
"created_at": comment.created_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def get_comments(self, moment_id: str) -> list[dict]:
|
||||||
|
"""获取评论列表"""
|
||||||
|
result = await self.db.execute(
|
||||||
|
select(MomentComment).where(
|
||||||
|
MomentComment.moment_id == moment_id
|
||||||
|
).order_by(MomentComment.created_at.asc())
|
||||||
|
)
|
||||||
|
comments = []
|
||||||
|
for c in result.scalars().all():
|
||||||
|
user_result = await self.db.execute(select(User).where(User.id == c.user_id))
|
||||||
|
user = user_result.scalars().first()
|
||||||
|
|
||||||
|
reply_to_username = None
|
||||||
|
if c.reply_to_id:
|
||||||
|
rt_comment = await self.db.execute(
|
||||||
|
select(MomentComment).where(MomentComment.id == c.reply_to_id)
|
||||||
|
)
|
||||||
|
rt_c = rt_comment.scalars().first()
|
||||||
|
if rt_c:
|
||||||
|
rt_user = await self.db.execute(select(User).where(User.id == rt_c.user_id))
|
||||||
|
rt_u = rt_user.scalars().first()
|
||||||
|
reply_to_username = rt_u.username if rt_u else None
|
||||||
|
|
||||||
|
comments.append({
|
||||||
|
"id": c.id,
|
||||||
|
"moment_id": moment_id,
|
||||||
|
"user_id": c.user_id,
|
||||||
|
"username": user.username if user else "未知",
|
||||||
|
"nickname": user.nickname if user else None,
|
||||||
|
"avatar_url": user.avatar_url if user else None,
|
||||||
|
"content": c.content,
|
||||||
|
"reply_to_id": c.reply_to_id,
|
||||||
|
"reply_to_username": reply_to_username,
|
||||||
|
"created_at": c.created_at,
|
||||||
|
})
|
||||||
|
return comments
|
||||||
|
|
||||||
|
async def delete_comment(self, comment_id: str, user_id: str):
|
||||||
|
"""删除评论(仅作者)"""
|
||||||
|
result = await self.db.execute(select(MomentComment).where(MomentComment.id == comment_id))
|
||||||
|
comment = result.scalars().first()
|
||||||
|
if not comment:
|
||||||
|
raise ValueError("评论不存在")
|
||||||
|
if comment.user_id != user_id:
|
||||||
|
raise ValueError("只能删除自己的评论")
|
||||||
|
await self.db.delete(comment)
|
||||||
|
|
||||||
|
async def _moment_to_dict(self, moment: Moment, viewer_id: str | None) -> dict:
|
||||||
|
"""将 Moment ORM 对象转为前端需要的字典"""
|
||||||
|
user_result = await self.db.execute(select(User).where(User.id == moment.user_id))
|
||||||
|
user = user_result.scalars().first()
|
||||||
|
|
||||||
|
# 点赞数
|
||||||
|
like_count_result = await self.db.execute(
|
||||||
|
select(func.count(MomentLike.id)).where(MomentLike.moment_id == moment.id)
|
||||||
|
)
|
||||||
|
like_count = like_count_result.scalar() or 0
|
||||||
|
|
||||||
|
# 是否已点赞
|
||||||
|
is_liked = False
|
||||||
|
if viewer_id:
|
||||||
|
like_result = await self.db.execute(
|
||||||
|
select(MomentLike).where(
|
||||||
|
MomentLike.moment_id == moment.id,
|
||||||
|
MomentLike.user_id == viewer_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
is_liked = like_result.scalars().first() is not None
|
||||||
|
|
||||||
|
# 评论数
|
||||||
|
comment_count_result = await self.db.execute(
|
||||||
|
select(func.count(MomentComment.id)).where(MomentComment.moment_id == moment.id)
|
||||||
|
)
|
||||||
|
comment_count = comment_count_result.scalar() or 0
|
||||||
|
|
||||||
|
# 解析图片
|
||||||
|
images = []
|
||||||
|
if moment.images:
|
||||||
|
try:
|
||||||
|
images = json.loads(moment.images)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": moment.id,
|
||||||
|
"user_id": moment.user_id,
|
||||||
|
"username": user.username if user else "未知",
|
||||||
|
"nickname": user.nickname if user else None,
|
||||||
|
"avatar_url": user.avatar_url if user else None,
|
||||||
|
"content": moment.content,
|
||||||
|
"images": images,
|
||||||
|
"visibility": moment.visibility,
|
||||||
|
"like_count": like_count,
|
||||||
|
"is_liked": is_liked,
|
||||||
|
"comment_count": comment_count,
|
||||||
|
"created_at": moment.created_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _get_friend_ids(self, user_id: str) -> list[str]:
|
||||||
|
"""获取好友ID列表"""
|
||||||
|
result = await self.db.execute(
|
||||||
|
select(Friend.friend_user_id).where(Friend.user_id == user_id)
|
||||||
|
)
|
||||||
|
return [r[0] for r in result.all()]
|
||||||
|
|
||||||
|
async def _are_friends(self, user1_id: str, user2_id: str) -> bool:
|
||||||
|
"""检查两人是否是好友"""
|
||||||
|
result = await self.db.execute(
|
||||||
|
select(Friend).where(
|
||||||
|
Friend.user_id == user1_id,
|
||||||
|
Friend.friend_user_id == user2_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return result.scalars().first() is not None
|
||||||
@@ -6,6 +6,7 @@ from sqlalchemy import select, or_, func
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
|
from app.utils.security import hash_password, verify_password
|
||||||
|
|
||||||
|
|
||||||
class UserService:
|
class UserService:
|
||||||
@@ -23,11 +24,12 @@ class UserService:
|
|||||||
return result.scalars().first()
|
return result.scalars().first()
|
||||||
|
|
||||||
async def search_users(self, query: str, current_user_id: str, limit: int = 20) -> list[User]:
|
async def search_users(self, query: str, current_user_id: str, limit: int = 20) -> list[User]:
|
||||||
"""搜索用户"""
|
"""搜索用户(支持用户名、昵称、邮箱)"""
|
||||||
result = await self.db.execute(
|
result = await self.db.execute(
|
||||||
select(User).where(
|
select(User).where(
|
||||||
or_(
|
or_(
|
||||||
User.username.ilike(f"%{query}%"),
|
User.username.ilike(f"%{query}%"),
|
||||||
|
User.nickname.ilike(f"%{query}%"),
|
||||||
User.email.ilike(f"%{query}%"),
|
User.email.ilike(f"%{query}%"),
|
||||||
),
|
),
|
||||||
User.id != current_user_id,
|
User.id != current_user_id,
|
||||||
@@ -49,6 +51,32 @@ class UserService:
|
|||||||
user.updated_at = datetime.utcnow()
|
user.updated_at = datetime.utcnow()
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
async def change_password(self, user_id: str, old_password: str, new_password: str):
|
||||||
|
"""修改密码"""
|
||||||
|
user = await self.get_by_id(user_id)
|
||||||
|
if not user:
|
||||||
|
raise ValueError("用户不存在")
|
||||||
|
if not verify_password(old_password, user.password_hash):
|
||||||
|
raise ValueError("原密码错误")
|
||||||
|
user.password_hash = hash_password(new_password)
|
||||||
|
user.updated_at = datetime.utcnow()
|
||||||
|
|
||||||
|
async def change_email(self, user_id: str, new_email: str, password: str):
|
||||||
|
"""更换绑定邮箱"""
|
||||||
|
user = await self.get_by_id(user_id)
|
||||||
|
if not user:
|
||||||
|
raise ValueError("用户不存在")
|
||||||
|
if not verify_password(password, user.password_hash):
|
||||||
|
raise ValueError("密码错误")
|
||||||
|
# 检查邮箱是否已被使用
|
||||||
|
result = await self.db.execute(
|
||||||
|
select(User).where(User.email == new_email, User.id != user_id)
|
||||||
|
)
|
||||||
|
if result.scalars().first():
|
||||||
|
raise ValueError("该邮箱已被其他账号使用")
|
||||||
|
user.email = new_email
|
||||||
|
user.updated_at = datetime.utcnow()
|
||||||
|
|
||||||
async def update_status(self, user_id: str, status: str):
|
async def update_status(self, user_id: str, status: str):
|
||||||
"""更新用户在线状态"""
|
"""更新用户在线状态"""
|
||||||
user = await self.get_by_id(user_id)
|
user = await self.get_by_id(user_id)
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
<template>
|
<template>
|
||||||
<n-config-provider :theme-overrides="themeOverrides">
|
<n-config-provider :theme-overrides="themeOverrides">
|
||||||
<n-message-provider>
|
<n-notification-provider>
|
||||||
<n-dialog-provider>
|
<n-message-provider>
|
||||||
<router-view />
|
<n-dialog-provider>
|
||||||
</n-dialog-provider>
|
<router-view />
|
||||||
</n-message-provider>
|
</n-dialog-provider>
|
||||||
|
</n-message-provider>
|
||||||
|
</n-notification-provider>
|
||||||
</n-config-provider>
|
</n-config-provider>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,18 @@ export const chatApi = {
|
|||||||
|
|
||||||
getConversationDetail: (id: string) => api.get(`/conversations/${id}`),
|
getConversationDetail: (id: string) => api.get(`/conversations/${id}`),
|
||||||
|
|
||||||
|
updateGroup: (id: string, data: { name?: string; description?: string }) =>
|
||||||
|
api.put(`/conversations/${id}`, data),
|
||||||
|
|
||||||
|
addMembers: (convId: string, userIds: string[]) =>
|
||||||
|
api.post(`/conversations/${convId}/members`, { user_ids: userIds }),
|
||||||
|
|
||||||
|
removeMember: (convId: string, userId: string) =>
|
||||||
|
api.delete(`/conversations/${convId}/members/${userId}`),
|
||||||
|
|
||||||
|
leaveGroup: (convId: string) =>
|
||||||
|
api.post(`/conversations/${convId}/leave`),
|
||||||
|
|
||||||
getMessages: (conversationId: string, before?: string, limit = 50) => {
|
getMessages: (conversationId: string, before?: string, limit = 50) => {
|
||||||
const params: Record<string, any> = { limit }
|
const params: Record<string, any> = { limit }
|
||||||
if (before) params.before = before
|
if (before) params.before = before
|
||||||
|
|||||||
@@ -8,12 +8,18 @@ export const friendsApi = {
|
|||||||
sendRequest: (toUserId: string, message?: string) =>
|
sendRequest: (toUserId: string, message?: string) =>
|
||||||
api.post('/friends/request', { to_user_id: toUserId, message }),
|
api.post('/friends/request', { to_user_id: toUserId, message }),
|
||||||
|
|
||||||
|
addDirect: (toUserId: string) =>
|
||||||
|
api.post('/friends/add-direct', { to_user_id: toUserId }),
|
||||||
|
|
||||||
acceptRequest: (requestId: string) =>
|
acceptRequest: (requestId: string) =>
|
||||||
api.put(`/friends/request/${requestId}/accept`),
|
api.put(`/friends/request/${requestId}/accept`),
|
||||||
|
|
||||||
rejectRequest: (requestId: string) =>
|
rejectRequest: (requestId: string) =>
|
||||||
api.put(`/friends/request/${requestId}/reject`),
|
api.put(`/friends/request/${requestId}/reject`),
|
||||||
|
|
||||||
|
updateRemark: (friendUserId: string, remark: string | null) =>
|
||||||
|
api.put(`/friends/${friendUserId}/remark`, { remark }),
|
||||||
|
|
||||||
removeFriend: (friendId: string) =>
|
removeFriend: (friendId: string) =>
|
||||||
api.delete(`/friends/${friendId}`),
|
api.delete(`/friends/${friendId}`),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import api from './client'
|
||||||
|
|
||||||
|
export const momentsApi = {
|
||||||
|
getFeed: (cursor?: string, limit = 20) =>
|
||||||
|
api.get('/moments/', { params: { cursor, limit } }),
|
||||||
|
|
||||||
|
createMoment: (data: { content: string; images?: string[]; visibility?: string }) =>
|
||||||
|
api.post('/moments/', data),
|
||||||
|
|
||||||
|
deleteMoment: (id: string) =>
|
||||||
|
api.delete(`/moments/${id}`),
|
||||||
|
|
||||||
|
toggleLike: (id: string) =>
|
||||||
|
api.post(`/moments/${id}/like`),
|
||||||
|
|
||||||
|
getComments: (id: string) =>
|
||||||
|
api.get(`/moments/${id}/comments`),
|
||||||
|
|
||||||
|
addComment: (momentId: string, content: string, replyToId?: string) =>
|
||||||
|
api.post(`/moments/${momentId}/comments`, {
|
||||||
|
content,
|
||||||
|
reply_to_id: replyToId || null,
|
||||||
|
}),
|
||||||
|
|
||||||
|
deleteComment: (momentId: string, commentId: string) =>
|
||||||
|
api.delete(`/moments/${momentId}/comments/${commentId}`),
|
||||||
|
|
||||||
|
getUserMoments: (userId: string, cursor?: string) =>
|
||||||
|
api.get(`/moments/user/${userId}`, { params: { cursor } }),
|
||||||
|
}
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
<template>
|
||||||
|
<div class="unified-layout">
|
||||||
|
<!-- 左侧固定图标导航栏 -->
|
||||||
|
<aside class="icon-rail">
|
||||||
|
<div class="rail-logo" @click="$router.push('/chat')">🌿</div>
|
||||||
|
<nav class="rail-nav">
|
||||||
|
<router-link to="/chat" class="rail-item" :class="{ active: activeFeature === 'chat' }" title="消息">
|
||||||
|
<span class="rail-icon">💬</span>
|
||||||
|
<n-badge v-if="totalUnread > 0" :value="totalUnread" :max="99" class="rail-badge" />
|
||||||
|
</router-link>
|
||||||
|
<router-link to="/contacts" class="rail-item" :class="{ active: activeFeature === 'contacts' }" title="通讯录">
|
||||||
|
<span class="rail-icon">👥</span>
|
||||||
|
<n-badge v-if="pendingRequestCount > 0" :value="pendingRequestCount" :max="9" class="rail-badge" />
|
||||||
|
</router-link>
|
||||||
|
<router-link to="/moments" class="rail-item" :class="{ active: activeFeature === 'moments' }" title="朋友圈">
|
||||||
|
<span class="rail-icon">🌿</span>
|
||||||
|
</router-link>
|
||||||
|
</nav>
|
||||||
|
<div class="rail-bottom">
|
||||||
|
<router-link to="/settings" class="rail-item" :class="{ active: activeFeature === 'settings' }" title="设置">
|
||||||
|
<span class="rail-icon">⚙️</span>
|
||||||
|
</router-link>
|
||||||
|
<div class="rail-avatar" @click="$router.push('/settings')">
|
||||||
|
<n-avatar v-if="auth.user?.avatar_url" :src="auth.user.avatar_url" :size="36" round />
|
||||||
|
<n-avatar v-else :size="36" round style="background: var(--color-primary)">
|
||||||
|
{{ displayName.charAt(0).toUpperCase() }}
|
||||||
|
</n-avatar>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<!-- 中间辅助面板 -->
|
||||||
|
<div class="secondary-panel" :class="{ 'panel-hidden': isMobile && hideSecondary }">
|
||||||
|
<router-view name="secondary" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 右侧主内容区 -->
|
||||||
|
<div class="main-content" :class="{ 'content-full': isMobile && !hideSecondary }">
|
||||||
|
<router-view />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, watch } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { useChatStore } from '@/stores/chat'
|
||||||
|
import { useUiStore } from '@/stores/ui'
|
||||||
|
import { useWebSocket } from '@/composables/useWebSocket'
|
||||||
|
import { friendsApi } from '@/api/friends'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const chatStore = useChatStore()
|
||||||
|
const uiStore = useUiStore()
|
||||||
|
const { connect } = useWebSocket()
|
||||||
|
|
||||||
|
const isMobile = computed(() => uiStore.isMobile)
|
||||||
|
const hideSecondary = computed(() => {
|
||||||
|
// 在移动端,当进入具体内容页时隐藏辅助面板
|
||||||
|
return route.matched.some((r) => r.meta.hideSecondary)
|
||||||
|
})
|
||||||
|
|
||||||
|
const pendingRequestCount = ref(0)
|
||||||
|
|
||||||
|
const activeFeature = computed(() => {
|
||||||
|
const path = route.path
|
||||||
|
if (path.startsWith('/chat')) return 'chat'
|
||||||
|
if (path.startsWith('/contacts')) return 'contacts'
|
||||||
|
if (path.startsWith('/moments')) return 'moments'
|
||||||
|
if (path.startsWith('/settings')) return 'settings'
|
||||||
|
return 'chat'
|
||||||
|
})
|
||||||
|
|
||||||
|
const displayName = computed(() => auth.user?.nickname || auth.user?.username || '?')
|
||||||
|
|
||||||
|
const totalUnread = computed(() =>
|
||||||
|
chatStore.conversations.reduce((sum: number, c: any) => sum + (c.unread_count || 0), 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
await auth.fetchProfile()
|
||||||
|
} catch {
|
||||||
|
// 未登录,路由守卫会处理
|
||||||
|
}
|
||||||
|
await chatStore.fetchConversations()
|
||||||
|
connect()
|
||||||
|
loadPendingRequests()
|
||||||
|
})
|
||||||
|
|
||||||
|
async function loadPendingRequests() {
|
||||||
|
try {
|
||||||
|
const { data } = await friendsApi.getPendingRequests()
|
||||||
|
pendingRequestCount.value = Array.isArray(data) ? data.length : 0
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.unified-layout {
|
||||||
|
display: flex;
|
||||||
|
height: 100vh;
|
||||||
|
background: var(--color-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 左侧图标栏 */
|
||||||
|
.icon-rail {
|
||||||
|
width: 64px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border-right: 1px solid var(--color-border);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
padding: 12px 0;
|
||||||
|
flex-shrink: 0;
|
||||||
|
z-index: 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rail-logo {
|
||||||
|
font-size: 28px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.2s;
|
||||||
|
}
|
||||||
|
.rail-logo:hover {
|
||||||
|
transform: scale(1.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rail-nav {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rail-item {
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 10px;
|
||||||
|
text-decoration: none;
|
||||||
|
font-size: 20px;
|
||||||
|
transition: all 0.2s;
|
||||||
|
position: relative;
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
}
|
||||||
|
.rail-item:hover {
|
||||||
|
background: var(--color-primary-lightest);
|
||||||
|
}
|
||||||
|
.rail-item.active {
|
||||||
|
background: var(--color-primary-lightest);
|
||||||
|
color: var(--color-primary);
|
||||||
|
}
|
||||||
|
.rail-item.active::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
left: -10px;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
width: 3px;
|
||||||
|
height: 20px;
|
||||||
|
background: var(--color-primary);
|
||||||
|
border-radius: 0 2px 2px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rail-badge {
|
||||||
|
position: absolute;
|
||||||
|
top: 4px;
|
||||||
|
right: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rail-bottom {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
margin-top: auto;
|
||||||
|
padding-top: 12px;
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rail-avatar {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.2s;
|
||||||
|
}
|
||||||
|
.rail-avatar:hover {
|
||||||
|
transform: scale(1.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 中间辅助面板 */
|
||||||
|
.secondary-panel {
|
||||||
|
width: 300px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border-right: 1px solid var(--color-border);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
flex-shrink: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
transition: width 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-hidden {
|
||||||
|
width: 0;
|
||||||
|
border-right: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 主内容区 */
|
||||||
|
.main-content {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
background: var(--color-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.content-full {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 移动端 */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.icon-rail {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 60px;
|
||||||
|
flex-direction: row;
|
||||||
|
padding: 0 8px;
|
||||||
|
border-right: none;
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
z-index: 100;
|
||||||
|
justify-content: space-around;
|
||||||
|
}
|
||||||
|
.rail-logo {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.rail-nav {
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 0;
|
||||||
|
flex: 1;
|
||||||
|
justify-content: space-around;
|
||||||
|
}
|
||||||
|
.rail-item.active::before {
|
||||||
|
left: 50%;
|
||||||
|
top: -12px;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
width: 20px;
|
||||||
|
height: 3px;
|
||||||
|
border-radius: 0 0 2px 2px;
|
||||||
|
}
|
||||||
|
.rail-bottom {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.secondary-panel {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.secondary-panel.panel-hidden {
|
||||||
|
width: 0;
|
||||||
|
}
|
||||||
|
.main-content {
|
||||||
|
padding-bottom: 60px;
|
||||||
|
}
|
||||||
|
.content-full {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
.unified-layout {
|
||||||
|
padding-bottom: 60px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
NConfigProvider,
|
NConfigProvider,
|
||||||
NMessageProvider,
|
NMessageProvider,
|
||||||
NDialogProvider,
|
NDialogProvider,
|
||||||
|
NNotificationProvider,
|
||||||
NButton,
|
NButton,
|
||||||
NInput,
|
NInput,
|
||||||
NForm,
|
NForm,
|
||||||
@@ -20,6 +21,27 @@ import {
|
|||||||
NSwitch,
|
NSwitch,
|
||||||
NSelect,
|
NSelect,
|
||||||
NButtonGroup,
|
NButtonGroup,
|
||||||
|
NModal,
|
||||||
|
NUpload,
|
||||||
|
NTooltip,
|
||||||
|
NTab,
|
||||||
|
NTabs,
|
||||||
|
NTabPane,
|
||||||
|
NDivider,
|
||||||
|
NSpace,
|
||||||
|
NImage,
|
||||||
|
NIcon,
|
||||||
|
NText,
|
||||||
|
NPopconfirm,
|
||||||
|
NResult,
|
||||||
|
NSpin,
|
||||||
|
NEmpty,
|
||||||
|
NGrid,
|
||||||
|
NGridItem,
|
||||||
|
NStatistic,
|
||||||
|
NTag,
|
||||||
|
NRadio,
|
||||||
|
NRadioGroup,
|
||||||
} from 'naive-ui'
|
} from 'naive-ui'
|
||||||
|
|
||||||
const app = createApp(App)
|
const app = createApp(App)
|
||||||
@@ -34,6 +56,7 @@ const naiveComponents: Record<string, any> = {
|
|||||||
NConfigProvider,
|
NConfigProvider,
|
||||||
NMessageProvider,
|
NMessageProvider,
|
||||||
NDialogProvider,
|
NDialogProvider,
|
||||||
|
NNotificationProvider,
|
||||||
NButton,
|
NButton,
|
||||||
NInput,
|
NInput,
|
||||||
NForm,
|
NForm,
|
||||||
@@ -45,6 +68,27 @@ const naiveComponents: Record<string, any> = {
|
|||||||
NSwitch,
|
NSwitch,
|
||||||
NSelect,
|
NSelect,
|
||||||
NButtonGroup,
|
NButtonGroup,
|
||||||
|
NModal,
|
||||||
|
NUpload,
|
||||||
|
NTooltip,
|
||||||
|
NTab,
|
||||||
|
NTabs,
|
||||||
|
NTabPane,
|
||||||
|
NDivider,
|
||||||
|
NSpace,
|
||||||
|
NImage,
|
||||||
|
NIcon,
|
||||||
|
NText,
|
||||||
|
NPopconfirm,
|
||||||
|
NResult,
|
||||||
|
NSpin,
|
||||||
|
NEmpty,
|
||||||
|
NGrid,
|
||||||
|
NGridItem,
|
||||||
|
NStatistic,
|
||||||
|
NTag,
|
||||||
|
NRadio,
|
||||||
|
NRadioGroup,
|
||||||
}
|
}
|
||||||
Object.entries(naiveComponents).forEach(([name, component]) => {
|
Object.entries(naiveComponents).forEach(([name, component]) => {
|
||||||
app.component(name, component)
|
app.component(name, component)
|
||||||
|
|||||||
+104
-25
@@ -13,36 +13,115 @@ const routes: RouteRecordRaw[] = [
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
// ==================== 聊天主界面(套用 ChatLayout)=====================
|
// ==================== 主界面(统一布局)=====================
|
||||||
{
|
{
|
||||||
path: '/',
|
path: '/',
|
||||||
component: () => import('@/layouts/ChatLayout.vue'),
|
component: () => import('@/layouts/UnifiedLayout.vue'),
|
||||||
meta: { requiresAuth: true },
|
meta: { requiresAuth: true },
|
||||||
children: [
|
children: [
|
||||||
|
// 聊天
|
||||||
|
{
|
||||||
|
path: 'chat',
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: '',
|
||||||
|
name: 'ChatList',
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/chat/ConversationListPanel.vue'),
|
||||||
|
default: () => import('@/views/chat/ChatListView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: ':id',
|
||||||
|
name: 'ChatRoom',
|
||||||
|
meta: { hideSecondary: true },
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/chat/ConversationListPanel.vue'),
|
||||||
|
default: () => import('@/views/chat/ChatRoomView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
// 通讯录
|
||||||
|
{
|
||||||
|
path: 'contacts',
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: '',
|
||||||
|
name: 'Contacts',
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/contacts/ContactsSidebar.vue'),
|
||||||
|
default: () => import('@/views/contacts/ContactsView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'search',
|
||||||
|
name: 'Search',
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/contacts/ContactsSidebar.vue'),
|
||||||
|
default: () => import('@/views/contacts/SearchView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
// 朋友圈
|
||||||
|
{
|
||||||
|
path: 'moments',
|
||||||
|
name: 'Moments',
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/moments/MomentsFeedView.vue'),
|
||||||
|
default: () => import('@/views/moments/MomentsFeedView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// 设置
|
||||||
|
{
|
||||||
|
path: 'settings',
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: '',
|
||||||
|
redirect: '/settings/profile',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'profile',
|
||||||
|
name: 'SettingsProfile',
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/settings/SettingsSidebar.vue'),
|
||||||
|
default: () => import('@/views/settings/ProfileSettingsView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'account',
|
||||||
|
name: 'SettingsAccount',
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/settings/SettingsSidebar.vue'),
|
||||||
|
default: () => import('@/views/settings/AccountSettingsView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'notifications',
|
||||||
|
name: 'SettingsNotifications',
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/settings/SettingsSidebar.vue'),
|
||||||
|
default: () => import('@/views/settings/NotificationSettingsView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'about',
|
||||||
|
name: 'SettingsAbout',
|
||||||
|
components: {
|
||||||
|
secondary: () => import('@/views/settings/SettingsSidebar.vue'),
|
||||||
|
default: () => import('@/views/settings/AboutView.vue'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
// 根路径重定向
|
||||||
{ path: '', redirect: '/chat' },
|
{ path: '', redirect: '/chat' },
|
||||||
{ path: 'chat', name: 'ChatList', component: () => import('@/views/chat/ChatListView.vue') },
|
{ path: 'profile', redirect: '/settings/profile' },
|
||||||
{ path: 'chat/:id', name: 'ChatRoom', component: () => import('@/views/chat/ChatRoomView.vue') },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
|
|
||||||
// ==================== 通讯录(套用 MainLayout)=====================
|
|
||||||
{
|
|
||||||
path: '/contacts',
|
|
||||||
component: () => import('@/layouts/MainLayout.vue'),
|
|
||||||
meta: { requiresAuth: true },
|
|
||||||
children: [
|
|
||||||
{ path: '', name: 'Contacts', component: () => import('@/views/contacts/ContactsView.vue') },
|
|
||||||
{ path: 'search', name: 'Search', component: () => import('@/views/contacts/SearchView.vue') },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
|
|
||||||
// ==================== 个人中心 =====================
|
|
||||||
{
|
|
||||||
path: '/profile',
|
|
||||||
component: () => import('@/layouts/MainLayout.vue'),
|
|
||||||
meta: { requiresAuth: true },
|
|
||||||
children: [
|
|
||||||
{ path: '', name: 'Profile', component: () => import('@/views/profile/ProfileView.vue') },
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { momentsApi } from '@/api/moments'
|
||||||
|
|
||||||
|
export const useMomentsStore = defineStore('moments', () => {
|
||||||
|
const feed = ref<any[]>([])
|
||||||
|
const isLoading = ref(false)
|
||||||
|
const hasMore = ref(true)
|
||||||
|
const cursor = ref<string | null>(null)
|
||||||
|
|
||||||
|
async function fetchFeed(refresh = false) {
|
||||||
|
if (isLoading.value) return
|
||||||
|
if (!refresh && !hasMore.value) return
|
||||||
|
|
||||||
|
isLoading.value = true
|
||||||
|
try {
|
||||||
|
if (refresh) {
|
||||||
|
cursor.value = null
|
||||||
|
feed.value = []
|
||||||
|
hasMore.value = true
|
||||||
|
}
|
||||||
|
const { data } = await momentsApi.getFeed(cursor.value || undefined)
|
||||||
|
if (refresh) {
|
||||||
|
feed.value = data
|
||||||
|
} else {
|
||||||
|
feed.value = [...feed.value, ...data]
|
||||||
|
}
|
||||||
|
if (data.length > 0) {
|
||||||
|
cursor.value = data[data.length - 1].id
|
||||||
|
}
|
||||||
|
if (data.length < 20) {
|
||||||
|
hasMore.value = false
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
isLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createMoment(content: string, images?: string[], visibility?: string) {
|
||||||
|
const { data } = await momentsApi.createMoment({ content, images, visibility })
|
||||||
|
feed.value.unshift(data)
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleLike(momentId: string) {
|
||||||
|
const { data } = await momentsApi.toggleLike(momentId)
|
||||||
|
const moment = feed.value.find((m) => m.id === momentId)
|
||||||
|
if (moment) {
|
||||||
|
moment.is_liked = data.is_liked
|
||||||
|
moment.like_count = data.is_liked ? moment.like_count + 1 : Math.max(0, moment.like_count - 1)
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addComment(momentId: string, content: string, replyToId?: string) {
|
||||||
|
const { data } = await momentsApi.addComment(momentId, content, replyToId)
|
||||||
|
const moment = feed.value.find((m) => m.id === momentId)
|
||||||
|
if (moment) {
|
||||||
|
moment.comment_count = (moment.comment_count || 0) + 1
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteMoment(momentId: string) {
|
||||||
|
await momentsApi.deleteMoment(momentId)
|
||||||
|
feed.value = feed.value.filter((m) => m.id !== momentId)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
feed, isLoading, hasMore,
|
||||||
|
fetchFeed, createMoment, toggleLike, addComment, deleteMoment,
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -3,56 +3,76 @@
|
|||||||
<!-- 聊天头部 -->
|
<!-- 聊天头部 -->
|
||||||
<div class="chat-header">
|
<div class="chat-header">
|
||||||
<n-button v-if="uiStore.isMobile" quaternary circle @click="$router.push('/chat')">←</n-button>
|
<n-button v-if="uiStore.isMobile" quaternary circle @click="$router.push('/chat')">←</n-button>
|
||||||
<span class="room-name">{{ conversationName }}</span>
|
<div class="header-info">
|
||||||
|
<span class="room-name">{{ conversationName }}</span>
|
||||||
|
<span v-if="convDetail?.type === 'group'" class="member-count">
|
||||||
|
({{ convDetail.members?.length || 0 }}人)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
<!-- 聊天风格切换 -->
|
<!-- 聊天风格切换 -->
|
||||||
<n-button-group size="tiny" style="margin-left: auto">
|
<n-button-group size="tiny" style="margin-left: auto">
|
||||||
<n-button :type="uiStore.chatStyle === 'classic' ? 'primary' : 'default'" @click="uiStore.setChatStyle('classic')">经典</n-button>
|
<n-button :type="uiStore.chatStyle === 'classic' ? 'primary' : 'default'" @click="uiStore.setChatStyle('classic')">经典</n-button>
|
||||||
<n-button :type="uiStore.chatStyle === 'compact' ? 'primary' : 'default'" @click="uiStore.setChatStyle('compact')">紧凑</n-button>
|
<n-button :type="uiStore.chatStyle === 'compact' ? 'primary' : 'default'" @click="uiStore.setChatStyle('compact')">紧凑</n-button>
|
||||||
<n-button :type="uiStore.chatStyle === 'bubble' ? 'primary' : 'default'" @click="uiStore.setChatStyle('bubble')">气泡</n-button>
|
<n-button :type="uiStore.chatStyle === 'bubble' ? 'primary' : 'default'" @click="uiStore.setChatStyle('bubble')">气泡</n-button>
|
||||||
</n-button-group>
|
</n-button-group>
|
||||||
|
<!-- 群聊信息按钮 -->
|
||||||
|
<n-button v-if="convDetail?.type === 'group'" quaternary circle size="small" @click="showGroupInfo = !showGroupInfo" title="群信息">
|
||||||
|
ℹ️
|
||||||
|
</n-button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 消息列表 -->
|
<div class="chat-body">
|
||||||
<div class="message-list" ref="messageListRef">
|
<!-- 消息列表 -->
|
||||||
<div v-if="chatStore.currentMessages.length === 0" class="no-messages">
|
<div class="message-list" ref="messageListRef">
|
||||||
<p>开始聊天吧 🌿</p>
|
<div v-if="chatStore.currentMessages.length === 0" class="no-messages">
|
||||||
</div>
|
<p>开始聊天吧 🌿</p>
|
||||||
<div
|
</div>
|
||||||
v-for="msg in chatStore.currentMessages" :key="msg.id"
|
<div
|
||||||
class="message-row" :class="{
|
v-for="msg in chatStore.currentMessages" :key="msg.id"
|
||||||
'own': msg.sender_id === auth.user?.id,
|
class="message-row" :class="{
|
||||||
'other': msg.sender_id !== auth.user?.id,
|
'own': msg.sender_id === auth.user?.id,
|
||||||
[`style-${uiStore.chatStyle}`]: true,
|
'other': msg.sender_id !== auth.user?.id,
|
||||||
}"
|
[`style-${uiStore.chatStyle}`]: true,
|
||||||
>
|
}"
|
||||||
<template v-if="msg.type === 'system'">
|
>
|
||||||
<div class="system-msg">{{ msg.content }}</div>
|
<template v-if="msg.type === 'system'">
|
||||||
</template>
|
<div class="system-msg">{{ msg.content }}</div>
|
||||||
<template v-else>
|
</template>
|
||||||
<div v-if="msg.sender_id !== auth.user?.id" class="avatar">
|
<template v-else>
|
||||||
<n-avatar :size="uiStore.chatStyle === 'compact' ? 28 : 34" round
|
<div v-if="msg.sender_id !== auth.user?.id" class="avatar">
|
||||||
:style="{ background: 'var(--color-primary)' }">
|
<n-avatar :size="uiStore.chatStyle === 'compact' ? 28 : 34" round
|
||||||
{{ (msg.sender_name || '?')[0] }}
|
:style="{ background: 'var(--color-primary)' }">
|
||||||
</n-avatar>
|
{{ (msg.sender_name || '?')[0] }}
|
||||||
</div>
|
</n-avatar>
|
||||||
<div class="bubble-area">
|
</div>
|
||||||
<div v-if="uiStore.chatStyle !== 'compact' && msg.sender_id !== auth.user?.id" class="sender-name">
|
<div class="bubble-area">
|
||||||
{{ msg.sender_name }}
|
<div v-if="uiStore.chatStyle !== 'compact' && msg.sender_id !== auth.user?.id" class="sender-name">
|
||||||
</div>
|
{{ msg.sender_name }}
|
||||||
<div class="bubble" :class="{ 'bubble-self': msg.sender_id === auth.user?.id, 'bubble-other': msg.sender_id !== auth.user?.id }">
|
</div>
|
||||||
<img v-if="msg.type === 'image'" :src="msg.content" class="msg-image" />
|
<div class="bubble" :class="{ 'bubble-self': msg.sender_id === auth.user?.id, 'bubble-other': msg.sender_id !== auth.user?.id }">
|
||||||
<span v-else>{{ msg.content }}</span>
|
<img v-if="msg.type === 'image'" :src="msg.content" class="msg-image" />
|
||||||
</div>
|
<span v-else>{{ msg.content }}</span>
|
||||||
<div v-if="uiStore.chatStyle === 'classic'" class="msg-time">
|
</div>
|
||||||
{{ formatTime(msg.created_at) }}
|
<div v-if="uiStore.chatStyle === 'classic'" class="msg-time">
|
||||||
</div>
|
{{ formatTime(msg.created_at) }}
|
||||||
</div>
|
</div>
|
||||||
<div v-if="msg.sender_id === auth.user?.id" class="avatar">
|
</div>
|
||||||
<n-avatar :size="uiStore.chatStyle === 'compact' ? 28 : 34" round
|
<div v-if="msg.sender_id === auth.user?.id" class="avatar">
|
||||||
style="background: var(--color-primary-dark)">我</n-avatar>
|
<n-avatar :size="uiStore.chatStyle === 'compact' ? 28 : 34" round
|
||||||
</div>
|
style="background: var(--color-primary-dark)">我</n-avatar>
|
||||||
</template>
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 群聊信息侧栏 -->
|
||||||
|
<GroupInfoPanel
|
||||||
|
v-if="showGroupInfo && convDetail?.type === 'group'"
|
||||||
|
:conversation-id="String(route.params.id)"
|
||||||
|
:detail="convDetail"
|
||||||
|
@close="showGroupInfo = false"
|
||||||
|
@updated="loadDetail"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 输入框 -->
|
<!-- 输入框 -->
|
||||||
@@ -73,6 +93,8 @@ import { useChatStore } from '@/stores/chat'
|
|||||||
import { useAuthStore } from '@/stores/auth'
|
import { useAuthStore } from '@/stores/auth'
|
||||||
import { useUiStore } from '@/stores/ui'
|
import { useUiStore } from '@/stores/ui'
|
||||||
import { useWebSocket } from '@/composables/useWebSocket'
|
import { useWebSocket } from '@/composables/useWebSocket'
|
||||||
|
import { chatApi } from '@/api/chat'
|
||||||
|
import GroupInfoPanel from './GroupInfoPanel.vue'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
@@ -84,16 +106,29 @@ const { send } = useWebSocket()
|
|||||||
const inputText = ref('')
|
const inputText = ref('')
|
||||||
const messageListRef = ref<HTMLElement>()
|
const messageListRef = ref<HTMLElement>()
|
||||||
const conversationName = ref('')
|
const conversationName = ref('')
|
||||||
|
const convDetail = ref<any>(null)
|
||||||
|
const showGroupInfo = ref(false)
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
const id = route.params.id as string
|
const id = route.params.id as string
|
||||||
if (id) {
|
if (id) {
|
||||||
await chatStore.fetchMessages(id)
|
await chatStore.fetchMessages(id)
|
||||||
|
await loadDetail()
|
||||||
await nextTick()
|
await nextTick()
|
||||||
scrollToBottom()
|
scrollToBottom()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
async function loadDetail() {
|
||||||
|
const id = route.params.id as string
|
||||||
|
if (!id) return
|
||||||
|
try {
|
||||||
|
const { data } = await chatApi.getConversationDetail(id)
|
||||||
|
convDetail.value = data
|
||||||
|
conversationName.value = data.name || '未命名'
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
watch(() => chatStore.currentMessages.length, () => {
|
watch(() => chatStore.currentMessages.length, () => {
|
||||||
nextTick(scrollToBottom)
|
nextTick(scrollToBottom)
|
||||||
})
|
})
|
||||||
@@ -127,7 +162,11 @@ function formatTime(time: string) {
|
|||||||
padding: 12px 20px; border-bottom: 1px solid var(--color-border);
|
padding: 12px 20px; border-bottom: 1px solid var(--color-border);
|
||||||
background: var(--color-surface);
|
background: var(--color-surface);
|
||||||
}
|
}
|
||||||
|
.header-info { display: flex; align-items: baseline; gap: 4px; }
|
||||||
.room-name { font-weight: 600; font-size: 16px; }
|
.room-name { font-weight: 600; font-size: 16px; }
|
||||||
|
.member-count { font-size: 12px; color: var(--color-text-hint); }
|
||||||
|
|
||||||
|
.chat-body { flex: 1; display: flex; overflow: hidden; }
|
||||||
|
|
||||||
.message-list { flex: 1; overflow-y: auto; padding: 16px 20px; }
|
.message-list { flex: 1; overflow-y: auto; padding: 16px 20px; }
|
||||||
.no-messages { text-align: center; padding-top: 120px; color: var(--color-text-hint); }
|
.no-messages { text-align: center; padding-top: 120px; color: var(--color-text-hint); }
|
||||||
|
|||||||
@@ -0,0 +1,216 @@
|
|||||||
|
<template>
|
||||||
|
<div class="conv-list-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<h3 class="panel-title">消息</h3>
|
||||||
|
<div class="header-actions">
|
||||||
|
<n-button quaternary circle size="small" @click="$router.push('/contacts/search')" title="搜索添加好友">🔍</n-button>
|
||||||
|
<n-button quaternary circle size="small" @click="showCreateGroup = true" title="创建群聊">👥</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- 搜索框 -->
|
||||||
|
<div class="search-bar">
|
||||||
|
<n-input v-model:value="searchKeyword" placeholder="搜索会话..." size="small" clearable />
|
||||||
|
</div>
|
||||||
|
<!-- 布局模式切换 -->
|
||||||
|
<div class="layout-switch">
|
||||||
|
<n-button-group size="tiny">
|
||||||
|
<n-button :type="uiStore.layoutMode === 'list' ? 'primary' : 'default'" @click="uiStore.setLayoutMode('list')">列表</n-button>
|
||||||
|
<n-button :type="uiStore.layoutMode === 'card' ? 'primary' : 'default'" @click="uiStore.setLayoutMode('card')">卡片</n-button>
|
||||||
|
<n-button :type="uiStore.layoutMode === 'waterfall' ? 'primary' : 'default'" @click="uiStore.setLayoutMode('waterfall')">瀑布流</n-button>
|
||||||
|
</n-button-group>
|
||||||
|
</div>
|
||||||
|
<!-- 会话列表 -->
|
||||||
|
<div class="conversation-list">
|
||||||
|
<div v-if="chatStore.isLoading" style="text-align: center; padding: 40px; color: var(--color-text-hint)">加载中...</div>
|
||||||
|
<div v-else-if="filteredConversations.length === 0" class="empty-state">
|
||||||
|
<div style="font-size: 48px">💬</div>
|
||||||
|
<p>{{ searchKeyword ? '没有找到匹配的会话' : '暂无消息' }}</p>
|
||||||
|
<p style="font-size: 13px; color: var(--color-text-hint)">去通讯录找朋友聊天吧</p>
|
||||||
|
</div>
|
||||||
|
<!-- 列表模式 -->
|
||||||
|
<template v-if="uiStore.layoutMode === 'list'">
|
||||||
|
<div v-for="conv in filteredConversations" :key="conv.id"
|
||||||
|
class="conv-item" :class="{ active: chatStore.activeConversation === conv.id }"
|
||||||
|
@click="openChat(conv.id)">
|
||||||
|
<n-avatar :size="46" round :style="{ background: 'var(--color-primary)' }">
|
||||||
|
{{ (conv.name || '?')[0] }}
|
||||||
|
</n-avatar>
|
||||||
|
<div class="conv-info">
|
||||||
|
<div class="conv-top">
|
||||||
|
<span class="conv-name">{{ conv.name || '未命名' }}</span>
|
||||||
|
<span class="conv-time">{{ formatTime(conv.last_message_at) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="conv-bottom">
|
||||||
|
<span class="conv-preview">{{ conv.last_message_preview || '' }}</span>
|
||||||
|
<n-badge v-if="conv.unread_count > 0" :value="conv.unread_count" :max="99" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<!-- 卡片模式 -->
|
||||||
|
<template v-else-if="uiStore.layoutMode === 'card'">
|
||||||
|
<div class="card-grid">
|
||||||
|
<div v-for="conv in filteredConversations" :key="conv.id"
|
||||||
|
class="conv-card" :class="{ active: chatStore.activeConversation === conv.id }"
|
||||||
|
@click="openChat(conv.id)">
|
||||||
|
<n-avatar :size="56" round :style="{ background: 'var(--color-primary)' }">
|
||||||
|
{{ (conv.name || '?')[0] }}
|
||||||
|
</n-avatar>
|
||||||
|
<div class="conv-card-name">{{ conv.name || '未命名' }}</div>
|
||||||
|
<div class="conv-card-preview">{{ conv.last_message_preview?.substring(0, 30) || '' }}</div>
|
||||||
|
<n-badge v-if="conv.unread_count > 0" :value="conv.unread_count" :max="99" style="position: absolute; top: 8px; right: 8px" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<!-- 瀑布流模式 -->
|
||||||
|
<template v-else>
|
||||||
|
<div class="waterfall-grid">
|
||||||
|
<div v-for="conv in filteredConversations" :key="conv.id"
|
||||||
|
class="conv-waterfall" @click="openChat(conv.id)">
|
||||||
|
<div class="wf-header">
|
||||||
|
<n-avatar :size="32" round :style="{ background: 'var(--color-primary)' }">
|
||||||
|
{{ (conv.name || '?')[0] }}
|
||||||
|
</n-avatar>
|
||||||
|
<span class="wf-name">{{ conv.name }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="wf-content">{{ conv.last_message_preview || '暂无消息' }}</div>
|
||||||
|
<div class="wf-footer">
|
||||||
|
<span>{{ formatTime(conv.last_message_at) }}</span>
|
||||||
|
<n-badge v-if="conv.unread_count > 0" :value="conv.unread_count" :max="99" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<!-- 创建群聊弹窗 -->
|
||||||
|
<CreateGroupModal :visible="showCreateGroup" @close="showCreateGroup = false" @created="onGroupCreated" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useChatStore } from '@/stores/chat'
|
||||||
|
import { useUiStore } from '@/stores/ui'
|
||||||
|
import CreateGroupModal from './CreateGroupModal.vue'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const chatStore = useChatStore()
|
||||||
|
const uiStore = useUiStore()
|
||||||
|
const searchKeyword = ref('')
|
||||||
|
const showCreateGroup = ref(false)
|
||||||
|
|
||||||
|
const filteredConversations = computed(() => {
|
||||||
|
if (!searchKeyword.value) return chatStore.conversations
|
||||||
|
const kw = searchKeyword.value.toLowerCase()
|
||||||
|
return chatStore.conversations.filter((c: any) =>
|
||||||
|
(c.name || '').toLowerCase().includes(kw) ||
|
||||||
|
(c.last_message_preview || '').toLowerCase().includes(kw)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
function openChat(id: string) {
|
||||||
|
router.push(`/chat/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onGroupCreated() {
|
||||||
|
await chatStore.fetchConversations()
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(time: string | null) {
|
||||||
|
if (!time) return ''
|
||||||
|
const d = dayjs(time)
|
||||||
|
const now = dayjs()
|
||||||
|
if (d.isSame(now, 'day')) return d.format('HH:mm')
|
||||||
|
if (d.isSame(now.subtract(1, 'day'), 'day')) return '昨天'
|
||||||
|
return d.format('MM/DD')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.conv-list-panel {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 16px;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-title {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-bar {
|
||||||
|
padding: 8px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.layout-switch {
|
||||||
|
padding: 4px 12px 8px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversation-list {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 60px 20px;
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 列表模式 */
|
||||||
|
.conv-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 12px 16px;
|
||||||
|
gap: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.15s;
|
||||||
|
border-bottom: 0.5px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.conv-item:hover { background: var(--color-primary-lightest); }
|
||||||
|
.conv-item.active { background: var(--color-primary-lightest); border-left: 3px solid var(--color-primary); }
|
||||||
|
.conv-info { flex: 1; min-width: 0; }
|
||||||
|
.conv-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
|
||||||
|
.conv-name { font-weight: 500; font-size: 14px; }
|
||||||
|
.conv-time { font-size: 11px; color: var(--color-text-hint); }
|
||||||
|
.conv-bottom { display: flex; justify-content: space-between; align-items: center; }
|
||||||
|
.conv-preview { font-size: 12px; color: var(--color-text-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
|
||||||
|
|
||||||
|
/* 卡片模式 */
|
||||||
|
.card-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding: 8px 12px; }
|
||||||
|
.conv-card {
|
||||||
|
background: var(--color-surface-elevated); border-radius: 10px; padding: 14px;
|
||||||
|
text-align: center; cursor: pointer; border: 1px solid var(--color-border);
|
||||||
|
transition: all 0.2s; position: relative;
|
||||||
|
}
|
||||||
|
.conv-card:hover { border-color: var(--color-primary-lighter); box-shadow: 0 2px 8px rgba(0,150,136,0.08); }
|
||||||
|
.conv-card.active { border-color: var(--color-primary); background: var(--color-primary-lightest); }
|
||||||
|
.conv-card-name { font-weight: 500; margin-top: 6px; font-size: 13px; }
|
||||||
|
.conv-card-preview { font-size: 11px; color: var(--color-text-hint); margin-top: 3px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
|
||||||
|
/* 瀑布流模式 */
|
||||||
|
.waterfall-grid { columns: 2; column-gap: 8px; padding: 8px 12px; }
|
||||||
|
.conv-waterfall {
|
||||||
|
break-inside: avoid; background: var(--color-surface-elevated); border-radius: 10px;
|
||||||
|
padding: 12px; margin-bottom: 8px; cursor: pointer; border: 1px solid var(--color-border);
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
.conv-waterfall:hover { border-color: var(--color-primary-lighter); }
|
||||||
|
.wf-header { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }
|
||||||
|
.wf-name { font-weight: 500; font-size: 13px; }
|
||||||
|
.wf-content { font-size: 12px; color: var(--color-text-secondary); line-height: 1.4; margin-bottom: 6px; }
|
||||||
|
.wf-footer { display: flex; justify-content: space-between; align-items: center; font-size: 11px; color: var(--color-text-hint); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
<template>
|
||||||
|
<div v-if="visible" class="modal-overlay" @click.self="$emit('close')">
|
||||||
|
<div class="modal-card">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>创建群聊</h3>
|
||||||
|
<span class="close-btn" @click="$emit('close')">✕</span>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>群名称</label>
|
||||||
|
<n-input v-model:value="groupName" placeholder="给群聊起个名字" maxlength="50" />
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>群简介(可选)</label>
|
||||||
|
<n-input v-model:value="groupDesc" type="textarea" :rows="2" placeholder="介绍一下这个群..." maxlength="200" />
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>选择成员 ({{ selectedFriends.size }} 人)</label>
|
||||||
|
<div v-if="friends.length === 0" class="no-friends">暂无好友,请先添加好友</div>
|
||||||
|
<div v-else class="friend-select-list">
|
||||||
|
<div v-for="friend in friends" :key="friend.friend_user_id"
|
||||||
|
class="friend-select-item" :class="{ selected: selectedFriends.has(friend.friend_user_id) }"
|
||||||
|
@click="toggleFriend(friend.friend_user_id)">
|
||||||
|
<n-avatar :size="32" round :style="{ background: 'var(--color-primary)' }">
|
||||||
|
{{ (friend.remark || friend.nickname || friend.username || '?')[0] }}
|
||||||
|
</n-avatar>
|
||||||
|
<span class="friend-name">{{ friend.remark || friend.nickname || friend.username }}</span>
|
||||||
|
<span class="check-mark">{{ selectedFriends.has(friend.friend_user_id) ? '✓' : '' }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<n-button @click="$emit('close')">取消</n-button>
|
||||||
|
<n-button type="primary" :loading="creating" :disabled="!groupName.trim() || selectedFriends.size === 0" @click="handleCreate">
|
||||||
|
创建群聊 ({{ selectedFriends.size + 1 }} 人)
|
||||||
|
</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useMessage } from 'naive-ui'
|
||||||
|
import { friendsApi } from '@/api/friends'
|
||||||
|
import { chatApi } from '@/api/chat'
|
||||||
|
|
||||||
|
defineProps<{ visible: boolean }>()
|
||||||
|
const emit = defineEmits<{ close: []; created: [] }>()
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const message = useMessage()
|
||||||
|
const friends = ref<any[]>([])
|
||||||
|
const selectedFriends = ref<Set<string>>(new Set())
|
||||||
|
const groupName = ref('')
|
||||||
|
const groupDesc = ref('')
|
||||||
|
const creating = ref(false)
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
const { data } = await friendsApi.getFriends()
|
||||||
|
friends.value = data
|
||||||
|
} catch {}
|
||||||
|
})
|
||||||
|
|
||||||
|
function toggleFriend(userId: string) {
|
||||||
|
const newSet = new Set(selectedFriends.value)
|
||||||
|
if (newSet.has(userId)) {
|
||||||
|
newSet.delete(userId)
|
||||||
|
} else {
|
||||||
|
newSet.add(userId)
|
||||||
|
}
|
||||||
|
selectedFriends.value = newSet
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleCreate() {
|
||||||
|
if (!groupName.value.trim()) return
|
||||||
|
creating.value = true
|
||||||
|
try {
|
||||||
|
const { data } = await chatApi.createGroup(
|
||||||
|
groupName.value.trim(),
|
||||||
|
Array.from(selectedFriends.value),
|
||||||
|
groupDesc.value.trim() || undefined
|
||||||
|
)
|
||||||
|
message.success('群聊创建成功')
|
||||||
|
emit('created')
|
||||||
|
emit('close')
|
||||||
|
router.push(`/chat/${data.id}`)
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e.response?.data?.detail || '创建失败')
|
||||||
|
} finally {
|
||||||
|
creating.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed; inset: 0; background: rgba(0,0,0,0.4);
|
||||||
|
display: flex; align-items: center; justify-content: center; z-index: 1000;
|
||||||
|
}
|
||||||
|
.modal-card {
|
||||||
|
width: 440px; max-height: 80vh; background: var(--color-surface);
|
||||||
|
border-radius: 16px; display: flex; flex-direction: column;
|
||||||
|
box-shadow: 0 12px 40px rgba(0,0,0,0.15);
|
||||||
|
}
|
||||||
|
.modal-header {
|
||||||
|
display: flex; justify-content: space-between; align-items: center;
|
||||||
|
padding: 20px 24px 16px; border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.modal-header h3 { margin: 0; font-size: 18px; }
|
||||||
|
.close-btn { cursor: pointer; font-size: 18px; color: var(--color-text-hint); padding: 4px; }
|
||||||
|
.close-btn:hover { color: var(--color-text-primary); }
|
||||||
|
.modal-body { flex: 1; overflow-y: auto; padding: 16px 24px; }
|
||||||
|
.modal-footer {
|
||||||
|
display: flex; justify-content: flex-end; gap: 8px;
|
||||||
|
padding: 16px 24px; border-top: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.form-group { margin-bottom: 16px; }
|
||||||
|
.form-group label { display: block; font-size: 13px; color: var(--color-text-secondary); margin-bottom: 6px; }
|
||||||
|
.no-friends { padding: 20px; text-align: center; color: var(--color-text-hint); font-size: 13px; }
|
||||||
|
.friend-select-list { max-height: 240px; overflow-y: auto; }
|
||||||
|
.friend-select-item {
|
||||||
|
display: flex; align-items: center; gap: 10px; padding: 8px 12px;
|
||||||
|
border-radius: 8px; cursor: pointer; transition: background 0.15s;
|
||||||
|
}
|
||||||
|
.friend-select-item:hover { background: var(--color-primary-lightest); }
|
||||||
|
.friend-select-item.selected { background: var(--color-primary-lightest); }
|
||||||
|
.friend-name { flex: 1; font-size: 14px; }
|
||||||
|
.check-mark { width: 20px; text-align: center; color: var(--color-primary); font-weight: bold; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
<template>
|
||||||
|
<div class="group-info-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<h3>群聊信息</h3>
|
||||||
|
<span class="close-btn" @click="$emit('close')">✕</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="detail" class="panel-body">
|
||||||
|
<!-- 群头像和名称 -->
|
||||||
|
<div class="group-header">
|
||||||
|
<n-avatar :size="64" round :style="{ background: 'var(--color-primary)', fontSize: '24px' }">
|
||||||
|
{{ (detail.name || '群')[0] }}
|
||||||
|
</n-avatar>
|
||||||
|
<div class="group-meta">
|
||||||
|
<span class="group-name">{{ detail.name || '未命名群聊' }}</span>
|
||||||
|
<span class="group-desc">{{ detail.description || '暂无简介' }}</span>
|
||||||
|
<span class="member-count">{{ detail.members?.length || 0 }} 人</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 修改群名(管理员) -->
|
||||||
|
<div v-if="isAdmin" class="section">
|
||||||
|
<div class="form-row">
|
||||||
|
<n-input v-model:value="editName" placeholder="群名称" size="small" style="flex: 1" />
|
||||||
|
<n-button size="small" type="primary" @click="saveGroupInfo">保存</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 成员列表 -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-header">
|
||||||
|
<span>群成员</span>
|
||||||
|
<n-button v-if="isAdmin" size="tiny" @click="showAddMember = true">添加成员</n-button>
|
||||||
|
</div>
|
||||||
|
<div class="member-list">
|
||||||
|
<div v-for="member in detail.members" :key="member.user_id" class="member-item">
|
||||||
|
<n-avatar :size="36" round :style="{ background: 'var(--color-primary)' }">
|
||||||
|
{{ (member.nickname || member.username || '?')[0] }}
|
||||||
|
</n-avatar>
|
||||||
|
<div class="member-info">
|
||||||
|
<span class="member-name">{{ member.nickname || member.username }}</span>
|
||||||
|
<span class="member-role" :class="member.role">{{ roleLabel(member.role) }}</span>
|
||||||
|
</div>
|
||||||
|
<n-button v-if="isAdmin && member.role !== 'owner'" size="tiny" quaternary type="error"
|
||||||
|
@click="removeMember(member.user_id)">移除</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 操作按钮 -->
|
||||||
|
<div class="section actions">
|
||||||
|
<n-button v-if="isOwner" type="error" ghost block>解散群聊</n-button>
|
||||||
|
<n-button v-else type="error" ghost block @click="leaveGroup">退出群聊</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, watch } from 'vue'
|
||||||
|
import { useMessage } from 'naive-ui'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { chatApi } from '@/api/chat'
|
||||||
|
|
||||||
|
const props = defineProps<{ conversationId: string; detail: any }>()
|
||||||
|
const emit = defineEmits<{ close: []; updated: [] }>()
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const message = useMessage()
|
||||||
|
const editName = ref('')
|
||||||
|
const showAddMember = ref(false)
|
||||||
|
|
||||||
|
const myRole = computed(() => {
|
||||||
|
const me = props.detail?.members?.find((m: any) => m.user_id === auth.user?.id)
|
||||||
|
return me?.role || 'member'
|
||||||
|
})
|
||||||
|
const isAdmin = computed(() => myRole.value === 'owner' || myRole.value === 'admin')
|
||||||
|
const isOwner = computed(() => myRole.value === 'owner')
|
||||||
|
|
||||||
|
watch(() => props.detail, (d) => {
|
||||||
|
if (d) editName.value = d.name || ''
|
||||||
|
}, { immediate: true })
|
||||||
|
|
||||||
|
function roleLabel(role: string) {
|
||||||
|
if (role === 'owner') return '群主'
|
||||||
|
if (role === 'admin') return '管理员'
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveGroupInfo() {
|
||||||
|
try {
|
||||||
|
await chatApi.updateGroup(props.conversationId, { name: editName.value })
|
||||||
|
message.success('群信息已更新')
|
||||||
|
emit('updated')
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e.response?.data?.detail || '更新失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeMember(userId: string) {
|
||||||
|
try {
|
||||||
|
await chatApi.removeMember(props.conversationId, userId)
|
||||||
|
message.success('已移除成员')
|
||||||
|
emit('updated')
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e.response?.data?.detail || '操作失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function leaveGroup() {
|
||||||
|
try {
|
||||||
|
await chatApi.leaveGroup(props.conversationId)
|
||||||
|
message.success('已退出群聊')
|
||||||
|
emit('close')
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e.response?.data?.detail || '退出失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.group-info-panel {
|
||||||
|
width: 320px; background: var(--color-surface);
|
||||||
|
border-left: 1px solid var(--color-border);
|
||||||
|
display: flex; flex-direction: column; height: 100%;
|
||||||
|
}
|
||||||
|
.panel-header {
|
||||||
|
display: flex; justify-content: space-between; align-items: center;
|
||||||
|
padding: 16px; border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.panel-header h3 { margin: 0; font-size: 16px; }
|
||||||
|
.close-btn { cursor: pointer; font-size: 16px; color: var(--color-text-hint); }
|
||||||
|
.close-btn:hover { color: var(--color-text-primary); }
|
||||||
|
.panel-body { flex: 1; overflow-y: auto; padding: 16px; }
|
||||||
|
.group-header { text-align: center; margin-bottom: 20px; }
|
||||||
|
.group-meta { margin-top: 8px; }
|
||||||
|
.group-name { font-size: 18px; font-weight: 600; display: block; }
|
||||||
|
.group-desc { font-size: 13px; color: var(--color-text-secondary); display: block; margin-top: 4px; }
|
||||||
|
.member-count { font-size: 12px; color: var(--color-text-hint); display: block; margin-top: 2px; }
|
||||||
|
.section { margin-bottom: 16px; }
|
||||||
|
.section-header {
|
||||||
|
display: flex; justify-content: space-between; align-items: center;
|
||||||
|
font-size: 13px; color: var(--color-text-secondary); margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.form-row { display: flex; gap: 8px; }
|
||||||
|
.member-list { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.member-item {
|
||||||
|
display: flex; align-items: center; gap: 10px;
|
||||||
|
padding: 8px; border-radius: 8px;
|
||||||
|
}
|
||||||
|
.member-info { flex: 1; display: flex; align-items: center; gap: 6px; }
|
||||||
|
.member-name { font-size: 14px; }
|
||||||
|
.member-role { font-size: 11px; padding: 1px 6px; border-radius: 4px; background: var(--color-primary-lightest); color: var(--color-primary); }
|
||||||
|
.member-role.owner { background: #FFF3E0; color: #F57C00; }
|
||||||
|
.member-role.admin { background: #E3F2FD; color: #1976D2; }
|
||||||
|
.actions { padding-top: 12px; border-top: 1px solid var(--color-border); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
<template>
|
||||||
|
<div class="contacts-sidebar">
|
||||||
|
<div class="panel-header">
|
||||||
|
<h3 class="panel-title">通讯录</h3>
|
||||||
|
<n-button quaternary circle size="small" @click="$router.push('/contacts/search')" title="搜索添加">➕</n-button>
|
||||||
|
</div>
|
||||||
|
<div class="search-bar">
|
||||||
|
<n-input v-model:value="searchKeyword" placeholder="搜索好友..." size="small" clearable />
|
||||||
|
</div>
|
||||||
|
<!-- 好友请求 -->
|
||||||
|
<div v-if="pendingRequests.length > 0" class="section" @click="$router.push('/contacts')">
|
||||||
|
<div class="request-banner">
|
||||||
|
<span>👤</span>
|
||||||
|
<span class="request-text"> {{ pendingRequests.length }} 个好友请求</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- 好友列表 -->
|
||||||
|
<div class="friend-list">
|
||||||
|
<div v-if="isLoading" style="text-align: center; padding: 40px; color: var(--color-text-hint)">加载中...</div>
|
||||||
|
<div v-else-if="filteredFriends.length === 0" class="empty">
|
||||||
|
<p style="color: var(--color-text-hint); font-size: 13px">
|
||||||
|
{{ searchKeyword ? '没有找到匹配的好友' : '还没有好友' }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div v-for="friend in filteredFriends" :key="friend.id" class="friend-item"
|
||||||
|
:class="{ active: selectedFriendId === friend.friend_user_id }"
|
||||||
|
@click="selectFriend(friend)">
|
||||||
|
<n-avatar :size="38" round :style="{ background: 'var(--color-primary)' }">
|
||||||
|
{{ (friend.remark || friend.username || '?')[0] }}
|
||||||
|
</n-avatar>
|
||||||
|
<div class="friend-info">
|
||||||
|
<span class="friend-name">{{ friend.remark || friend.username }}</span>
|
||||||
|
<span class="friend-status" :class="friend.status">·</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted } from 'vue'
|
||||||
|
import { useRouter, useRoute } from 'vue-router'
|
||||||
|
import { useMessage } from 'naive-ui'
|
||||||
|
import { friendsApi } from '@/api/friends'
|
||||||
|
import { chatApi } from '@/api/chat'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const route = useRoute()
|
||||||
|
const message = useMessage()
|
||||||
|
const searchKeyword = ref('')
|
||||||
|
const friends = ref<any[]>([])
|
||||||
|
const pendingRequests = ref<any[]>([])
|
||||||
|
const isLoading = ref(false)
|
||||||
|
const selectedFriendId = computed(() => route.query.friend_id as string || '')
|
||||||
|
|
||||||
|
const filteredFriends = computed(() => {
|
||||||
|
if (!searchKeyword.value) return friends.value
|
||||||
|
const kw = searchKeyword.value.toLowerCase()
|
||||||
|
return friends.value.filter((f: any) =>
|
||||||
|
(f.remark || f.username || '').toLowerCase().includes(kw)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
isLoading.value = true
|
||||||
|
await Promise.all([loadFriends(), loadRequests()])
|
||||||
|
isLoading.value = false
|
||||||
|
})
|
||||||
|
|
||||||
|
async function loadFriends() {
|
||||||
|
try { const { data } = await friendsApi.getFriends(); friends.value = data } catch {}
|
||||||
|
}
|
||||||
|
async function loadRequests() {
|
||||||
|
try { const { data } = await friendsApi.getPendingRequests(); pendingRequests.value = data } catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function selectFriend(friend: any) {
|
||||||
|
try {
|
||||||
|
const { data } = await chatApi.createPrivateConversation(friend.friend_user_id)
|
||||||
|
router.push(`/chat/${data.id}`)
|
||||||
|
} catch { message.error('创建会话失败') }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.contacts-sidebar {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
.panel-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 16px;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.panel-title { margin: 0; font-size: 16px; font-weight: 600; }
|
||||||
|
.search-bar { padding: 8px 12px; }
|
||||||
|
.request-banner {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 10px 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
background: var(--color-primary-lightest);
|
||||||
|
color: var(--color-primary);
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.request-text { flex: 1; }
|
||||||
|
.friend-list { flex: 1; overflow-y: auto; }
|
||||||
|
.friend-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
.friend-item:hover { background: var(--color-primary-lightest); }
|
||||||
|
.friend-item.active { background: var(--color-primary-lightest); }
|
||||||
|
.friend-info { flex: 1; min-width: 0; }
|
||||||
|
.friend-name { font-size: 14px; font-weight: 500; }
|
||||||
|
.friend-status { font-size: 16px; margin-left: 4px; }
|
||||||
|
.friend-status.online { color: var(--color-success); }
|
||||||
|
.friend-status.offline { color: var(--color-text-hint); }
|
||||||
|
.empty { text-align: center; padding: 40px 20px; }
|
||||||
|
</style>
|
||||||
@@ -1,18 +1,26 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="search-page">
|
<div class="search-page">
|
||||||
<h2>搜索用户</h2>
|
<h2>搜索用户</h2>
|
||||||
<n-input v-model:value="keyword" placeholder="输入用户名或邮箱搜索..." size="large" @input="debouncedSearch" style="margin: 16px 0" />
|
<n-input v-model:value="keyword" placeholder="输入用户名、昵称或邮箱搜索..." size="large" @input="debouncedSearch" style="margin: 16px 0" />
|
||||||
<div v-if="results.length > 0">
|
<div v-if="results.length > 0">
|
||||||
<div v-for="user in results" :key="user.id" class="search-result">
|
<div v-for="user in results" :key="user.id" class="search-result">
|
||||||
<n-avatar :size="44" round :style="{ background: 'var(--color-primary)' }">{{ (user.username)[0] }}</n-avatar>
|
<n-avatar :size="48" round :style="{ background: 'var(--color-primary)' }">
|
||||||
|
{{ (user.nickname || user.username)[0] }}
|
||||||
|
</n-avatar>
|
||||||
<div class="result-info">
|
<div class="result-info">
|
||||||
<span class="result-name">{{ user.username }}</span>
|
<span class="result-name">{{ user.nickname || user.username }}</span>
|
||||||
|
<span v-if="user.nickname && user.nickname !== user.username" class="result-username">@{{ user.username }}</span>
|
||||||
<span class="result-bio">{{ user.bio || '这个人很懒,什么都没写' }}</span>
|
<span class="result-bio">{{ user.bio || '这个人很懒,什么都没写' }}</span>
|
||||||
</div>
|
</div>
|
||||||
<n-button type="primary" size="small" @click="addFriend(user.id)">添加好友</n-button>
|
<div class="result-actions">
|
||||||
|
<n-button type="primary" size="small" @click="addDirect(user.id)">添加</n-button>
|
||||||
|
<n-button size="small" @click="sendRequest(user.id)">发请求</n-button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-else-if="searched" class="empty">没有找到匹配的用户</div>
|
<div v-else-if="searched" class="empty">
|
||||||
|
<p style="color: var(--color-text-hint)">没有找到匹配的用户</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -20,6 +28,7 @@
|
|||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
import { useMessage } from 'naive-ui'
|
import { useMessage } from 'naive-ui'
|
||||||
import api from '@/api/client'
|
import api from '@/api/client'
|
||||||
|
import { friendsApi } from '@/api/friends'
|
||||||
|
|
||||||
const message = useMessage()
|
const message = useMessage()
|
||||||
const keyword = ref('')
|
const keyword = ref('')
|
||||||
@@ -38,9 +47,18 @@ const debouncedSearch = () => {
|
|||||||
}, 400)
|
}, 400)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function addFriend(userId: string) {
|
async function addDirect(userId: string) {
|
||||||
try {
|
try {
|
||||||
await api.post('/friends/request', { to_user_id: userId })
|
await friendsApi.addDirect(userId)
|
||||||
|
message.success('已添加为好友')
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e.response?.data?.detail || '添加失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendRequest(userId: string) {
|
||||||
|
try {
|
||||||
|
await friendsApi.sendRequest(userId)
|
||||||
message.success('好友请求已发送')
|
message.success('好友请求已发送')
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
message.error(e.response?.data?.detail || '发送失败')
|
message.error(e.response?.data?.detail || '发送失败')
|
||||||
@@ -50,9 +68,16 @@ async function addFriend(userId: string) {
|
|||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.search-page { max-width: 600px; margin: 0 auto; padding: 24px; }
|
.search-page { max-width: 600px; margin: 0 auto; padding: 24px; }
|
||||||
.search-result { display: flex; align-items: center; gap: 12px; padding: 12px; background: var(--color-surface); border-radius: 10px; margin-bottom: 8px; }
|
.search-page h2 { margin-bottom: 8px; }
|
||||||
.result-info { flex: 1; }
|
.search-result {
|
||||||
.result-name { font-weight: 500; display: block; }
|
display: flex; align-items: center; gap: 12px; padding: 14px;
|
||||||
.result-bio { font-size: 13px; color: var(--color-text-hint); }
|
background: var(--color-surface); border-radius: 10px; margin-bottom: 8px;
|
||||||
.empty { text-align: center; padding: 40px; color: var(--color-text-hint); }
|
border: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.result-info { flex: 1; min-width: 0; }
|
||||||
|
.result-name { font-weight: 500; display: block; font-size: 15px; }
|
||||||
|
.result-username { font-size: 12px; color: var(--color-text-hint); margin-left: 4px; }
|
||||||
|
.result-bio { font-size: 13px; color: var(--color-text-hint); display: block; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.result-actions { display: flex; gap: 6px; flex-shrink: 0; }
|
||||||
|
.empty { text-align: center; padding: 40px; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
<template>
|
||||||
|
<div class="moment-card">
|
||||||
|
<!-- 头部:头像 + 用户名 + 时间 -->
|
||||||
|
<div class="moment-header">
|
||||||
|
<n-avatar :size="40" round :style="{ background: 'var(--color-primary)' }">
|
||||||
|
{{ (moment.nickname || moment.username || '?')[0] }}
|
||||||
|
</n-avatar>
|
||||||
|
<div class="header-info">
|
||||||
|
<span class="author-name">{{ moment.nickname || moment.username }}</span>
|
||||||
|
<span class="post-time">{{ formatTime(moment.created_at) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 内容 -->
|
||||||
|
<div class="moment-content">{{ moment.content }}</div>
|
||||||
|
|
||||||
|
<!-- 图片 -->
|
||||||
|
<div v-if="moment.images && moment.images.length > 0" class="moment-images" :class="`grid-${Math.min(moment.images.length, 3)}`">
|
||||||
|
<div v-for="(img, i) in moment.images" :key="i" class="image-item">
|
||||||
|
<img :src="img" :alt="`图片${i + 1}`" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 操作栏 -->
|
||||||
|
<div class="moment-actions">
|
||||||
|
<span class="action-btn" :class="{ liked: moment.is_liked }" @click="$emit('toggle-like', moment.id)">
|
||||||
|
{{ moment.is_liked ? '❤️' : '🤍' }} {{ moment.like_count || '' }}
|
||||||
|
</span>
|
||||||
|
<span class="action-btn" @click="showComments = !showComments">
|
||||||
|
💬 {{ moment.comment_count || '' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 评论区 -->
|
||||||
|
<div v-if="showComments" class="comments-section">
|
||||||
|
<div v-if="comments.length > 0" class="comments-list">
|
||||||
|
<div v-for="comment in comments" :key="comment.id" class="comment-item">
|
||||||
|
<span class="comment-author">{{ comment.nickname || comment.username }}</span>
|
||||||
|
<span v-if="comment.reply_to_username" class="comment-reply">
|
||||||
|
回复 <span class="comment-author">{{ comment.reply_to_username }}</span>
|
||||||
|
</span>
|
||||||
|
<span class="comment-text">:{{ comment.content }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="comment-input">
|
||||||
|
<n-input v-model:value="commentText" placeholder="写评论..." size="small"
|
||||||
|
@keydown.enter.prevent="submitComment" />
|
||||||
|
<n-button size="tiny" type="primary" :disabled="!commentText.trim()" @click="submitComment">发送</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, watch } from 'vue'
|
||||||
|
import { momentsApi } from '@/api/moments'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import relativeTime from 'dayjs/plugin/relativeTime'
|
||||||
|
import 'dayjs/locale/zh-cn'
|
||||||
|
|
||||||
|
dayjs.extend(relativeTime)
|
||||||
|
dayjs.locale('zh-cn')
|
||||||
|
|
||||||
|
const props = defineProps<{ moment: any }>()
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'toggle-like': [momentId: string]
|
||||||
|
'comment': [momentId: string, content: string]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const showComments = ref(false)
|
||||||
|
const comments = ref<any[]>([])
|
||||||
|
const commentText = ref('')
|
||||||
|
|
||||||
|
watch(showComments, async (val) => {
|
||||||
|
if (val && comments.value.length === 0) {
|
||||||
|
try {
|
||||||
|
const { data } = await momentsApi.getComments(props.moment.id)
|
||||||
|
comments.value = data
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
async function submitComment() {
|
||||||
|
if (!commentText.value.trim()) return
|
||||||
|
try {
|
||||||
|
const { data } = await momentsApi.addComment(props.moment.id, commentText.value.trim())
|
||||||
|
comments.value.push(data)
|
||||||
|
emit('comment', props.moment.id, commentText.value.trim())
|
||||||
|
commentText.value = ''
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(time: string) {
|
||||||
|
const d = dayjs(time)
|
||||||
|
const now = dayjs()
|
||||||
|
const diffMin = now.diff(d, 'minute')
|
||||||
|
if (diffMin < 1) return '刚刚'
|
||||||
|
if (diffMin < 60) return `${diffMin}分钟前`
|
||||||
|
const diffHour = now.diff(d, 'hour')
|
||||||
|
if (diffHour < 24) return `${diffHour}小时前`
|
||||||
|
const diffDay = now.diff(d, 'day')
|
||||||
|
if (diffDay < 7) return `${diffDay}天前`
|
||||||
|
return d.format('MM/DD')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.moment-card {
|
||||||
|
background: var(--color-surface); border-radius: 12px; padding: 16px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.moment-header { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
|
||||||
|
.header-info { display: flex; flex-direction: column; }
|
||||||
|
.author-name { font-weight: 600; font-size: 14px; }
|
||||||
|
.post-time { font-size: 11px; color: var(--color-text-hint); }
|
||||||
|
|
||||||
|
.moment-content {
|
||||||
|
font-size: 14px; line-height: 1.6; color: var(--color-text-primary);
|
||||||
|
margin-bottom: 10px; white-space: pre-wrap; word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.moment-images { display: grid; gap: 6px; margin-bottom: 10px; border-radius: 8px; overflow: hidden; }
|
||||||
|
.moment-images.grid-1 { grid-template-columns: 1fr; max-width: 280px; }
|
||||||
|
.moment-images.grid-2 { grid-template-columns: 1fr 1fr; }
|
||||||
|
.moment-images.grid-3 { grid-template-columns: 1fr 1fr 1fr; }
|
||||||
|
.image-item { aspect-ratio: 1; overflow: hidden; border-radius: 6px; cursor: pointer; }
|
||||||
|
.image-item img { width: 100%; height: 100%; object-fit: cover; }
|
||||||
|
|
||||||
|
.moment-actions {
|
||||||
|
display: flex; gap: 16px; padding-top: 8px;
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.action-btn {
|
||||||
|
font-size: 13px; cursor: pointer; color: var(--color-text-secondary);
|
||||||
|
display: flex; align-items: center; gap: 3px; transition: color 0.2s;
|
||||||
|
}
|
||||||
|
.action-btn:hover { color: var(--color-primary); }
|
||||||
|
.action-btn.liked { color: #E53935; }
|
||||||
|
|
||||||
|
.comments-section { margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--color-border); }
|
||||||
|
.comments-list { margin-bottom: 8px; }
|
||||||
|
.comment-item {
|
||||||
|
font-size: 13px; padding: 4px 0; line-height: 1.5;
|
||||||
|
color: var(--color-text-primary);
|
||||||
|
}
|
||||||
|
.comment-author { color: var(--color-primary); font-weight: 500; cursor: pointer; }
|
||||||
|
.comment-reply { color: var(--color-text-hint); }
|
||||||
|
.comment-text { color: var(--color-text-primary); }
|
||||||
|
|
||||||
|
.comment-input { display: flex; gap: 6px; margin-top: 6px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
<template>
|
||||||
|
<div class="moments-feed">
|
||||||
|
<div class="panel-header">
|
||||||
|
<h3 class="panel-title">朋友圈</h3>
|
||||||
|
</div>
|
||||||
|
<div class="feed-content">
|
||||||
|
<!-- 发布入口 -->
|
||||||
|
<div class="compose-trigger" @click="showCompose = true">
|
||||||
|
<span class="compose-icon">✏️</span>
|
||||||
|
<span>发布新动态...</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 加载状态 -->
|
||||||
|
<div v-if="momentsStore.isLoading && momentsStore.feed.length === 0" class="loading">
|
||||||
|
加载中...
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 空状态 -->
|
||||||
|
<div v-else-if="momentsStore.feed.length === 0" class="empty-moments">
|
||||||
|
<div style="font-size: 48px">🌿</div>
|
||||||
|
<p style="color: var(--color-text-secondary)">还没有动态</p>
|
||||||
|
<p style="font-size: 13px; color: var(--color-text-hint)">发布第一条动态吧</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 动态列表 -->
|
||||||
|
<div v-else class="moment-list">
|
||||||
|
<MomentCard
|
||||||
|
v-for="moment in momentsStore.feed"
|
||||||
|
:key="moment.id"
|
||||||
|
:moment="moment"
|
||||||
|
@toggle-like="handleToggleLike"
|
||||||
|
@comment="handleComment"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 加载更多 -->
|
||||||
|
<div v-if="momentsStore.hasMore && momentsStore.feed.length > 0" class="load-more">
|
||||||
|
<n-button text size="small" @click="momentsStore.fetchFeed()">加载更多</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 发布弹窗 -->
|
||||||
|
<div v-if="showCompose" class="modal-overlay" @click.self="showCompose = false">
|
||||||
|
<div class="compose-modal">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>发布动态</h3>
|
||||||
|
<span class="close-btn" @click="showCompose = false">✕</span>
|
||||||
|
</div>
|
||||||
|
<div class="compose-body">
|
||||||
|
<n-input v-model:value="composeText" type="textarea" :rows="4"
|
||||||
|
placeholder="分享你的想法..." maxlength="1000" show-count />
|
||||||
|
<div class="compose-options">
|
||||||
|
<div class="visibility-select">
|
||||||
|
<span class="option-label">可见范围:</span>
|
||||||
|
<n-button-group size="tiny">
|
||||||
|
<n-button :type="composeVisibility === 'friends' ? 'primary' : 'default'" @click="composeVisibility = 'friends'">好友</n-button>
|
||||||
|
<n-button :type="composeVisibility === 'public' ? 'primary' : 'default'" @click="composeVisibility = 'public'">公开</n-button>
|
||||||
|
<n-button :type="composeVisibility === 'private' ? 'primary' : 'default'" @click="composeVisibility = 'private'">仅自己</n-button>
|
||||||
|
</n-button-group>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="compose-footer">
|
||||||
|
<n-button @click="showCompose = false">取消</n-button>
|
||||||
|
<n-button type="primary" :loading="publishing" :disabled="!composeText.trim()" @click="publishMoment">发布</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { useMomentsStore } from '@/stores/moments'
|
||||||
|
import { useMessage } from 'naive-ui'
|
||||||
|
import MomentCard from './MomentCard.vue'
|
||||||
|
|
||||||
|
const momentsStore = useMomentsStore()
|
||||||
|
const message = useMessage()
|
||||||
|
|
||||||
|
const showCompose = ref(false)
|
||||||
|
const composeText = ref('')
|
||||||
|
const composeVisibility = ref('friends')
|
||||||
|
const publishing = ref(false)
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
momentsStore.fetchFeed(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
async function publishMoment() {
|
||||||
|
if (!composeText.value.trim()) return
|
||||||
|
publishing.value = true
|
||||||
|
try {
|
||||||
|
await momentsStore.createMoment(composeText.value.trim(), undefined, composeVisibility.value)
|
||||||
|
message.success('动态发布成功')
|
||||||
|
composeText.value = ''
|
||||||
|
showCompose.value = false
|
||||||
|
} catch {
|
||||||
|
message.error('发布失败')
|
||||||
|
} finally {
|
||||||
|
publishing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleToggleLike(momentId: string) {
|
||||||
|
try {
|
||||||
|
await momentsStore.toggleLike(momentId)
|
||||||
|
} catch {
|
||||||
|
message.error('操作失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleComment(momentId: string, content: string) {
|
||||||
|
try {
|
||||||
|
await momentsStore.addComment(momentId, content)
|
||||||
|
message.success('评论成功')
|
||||||
|
} catch {
|
||||||
|
message.error('评论失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.moments-feed { display: flex; flex-direction: column; height: 100%; }
|
||||||
|
.panel-header { padding: 16px; border-bottom: 1px solid var(--color-border); }
|
||||||
|
.panel-title { margin: 0; font-size: 16px; font-weight: 600; }
|
||||||
|
.feed-content { flex: 1; overflow-y: auto; padding: 12px; }
|
||||||
|
|
||||||
|
.compose-trigger {
|
||||||
|
display: flex; align-items: center; gap: 8px; padding: 12px 16px;
|
||||||
|
background: var(--color-surface); border-radius: 10px;
|
||||||
|
border: 1px dashed var(--color-border); cursor: pointer;
|
||||||
|
color: var(--color-text-secondary); font-size: 14px; transition: all 0.2s; margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.compose-trigger:hover { border-color: var(--color-primary-lighter); color: var(--color-primary); background: var(--color-primary-lightest); }
|
||||||
|
.compose-icon { font-size: 18px; }
|
||||||
|
|
||||||
|
.loading { text-align: center; padding: 40px; color: var(--color-text-hint); }
|
||||||
|
.empty-moments { text-align: center; padding: 60px 20px; }
|
||||||
|
|
||||||
|
.moment-list { display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.load-more { text-align: center; padding: 12px; }
|
||||||
|
|
||||||
|
/* 发布弹窗 */
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed; inset: 0; background: rgba(0,0,0,0.4);
|
||||||
|
display: flex; align-items: center; justify-content: center; z-index: 1000;
|
||||||
|
}
|
||||||
|
.compose-modal {
|
||||||
|
width: 500px; background: var(--color-surface); border-radius: 16px;
|
||||||
|
box-shadow: 0 12px 40px rgba(0,0,0,0.15);
|
||||||
|
}
|
||||||
|
.modal-header {
|
||||||
|
display: flex; justify-content: space-between; align-items: center;
|
||||||
|
padding: 20px 24px 16px; border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.modal-header h3 { margin: 0; font-size: 18px; }
|
||||||
|
.close-btn { cursor: pointer; font-size: 18px; color: var(--color-text-hint); padding: 4px; }
|
||||||
|
.close-btn:hover { color: var(--color-text-primary); }
|
||||||
|
.compose-body { padding: 16px 24px; }
|
||||||
|
.compose-options { margin-top: 12px; }
|
||||||
|
.visibility-select { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.option-label { font-size: 13px; color: var(--color-text-secondary); }
|
||||||
|
.compose-footer {
|
||||||
|
display: flex; justify-content: flex-end; gap: 8px;
|
||||||
|
padding: 16px 24px; border-top: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
<template>
|
||||||
|
<div class="settings-page">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>关于青叶</h2>
|
||||||
|
</div>
|
||||||
|
<div class="settings-content">
|
||||||
|
<div class="about-card">
|
||||||
|
<div class="about-logo">🌿</div>
|
||||||
|
<h3 class="about-name">青叶 QingYe</h3>
|
||||||
|
<p class="about-version">版本 0.1.0</p>
|
||||||
|
<p class="about-desc">清新社交,畅快聊天</p>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="info-label">技术栈</span>
|
||||||
|
<span class="info-value">Vue 3 + FastAPI + PostgreSQL</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="info-label">部署方式</span>
|
||||||
|
<span class="info-value">Docker Compose</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="info-label">开源协议</span>
|
||||||
|
<span class="info-value">MIT License</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<n-button v-if="auth.user?.is_admin" block @click="$router.push('/admin/dashboard')">
|
||||||
|
进入管理后台
|
||||||
|
</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.settings-page { padding: 24px; max-width: 600px; }
|
||||||
|
.page-header { margin-bottom: 24px; }
|
||||||
|
.page-header h2 { margin: 0; font-size: 20px; color: var(--color-primary-dark); }
|
||||||
|
.settings-content { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.about-card {
|
||||||
|
text-align: center;
|
||||||
|
padding: 32px 20px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.about-logo { font-size: 56px; margin-bottom: 8px; }
|
||||||
|
.about-name { margin: 0; font-size: 22px; font-weight: 700; color: var(--color-primary-dark); }
|
||||||
|
.about-version { font-size: 13px; color: var(--color-text-hint); margin-top: 4px; }
|
||||||
|
.about-desc { font-size: 14px; color: var(--color-text-secondary); margin-top: 8px; }
|
||||||
|
.card {
|
||||||
|
background: var(--color-surface);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 4px 20px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.info-item {
|
||||||
|
display: flex; justify-content: space-between; align-items: center;
|
||||||
|
padding: 12px 0;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.info-item:last-child { border-bottom: none; }
|
||||||
|
.info-label { font-size: 14px; color: var(--color-text-secondary); }
|
||||||
|
.info-value { font-size: 14px; color: var(--color-text-primary); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
<template>
|
||||||
|
<div class="settings-page">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>账号安全</h2>
|
||||||
|
</div>
|
||||||
|
<div class="settings-content">
|
||||||
|
<!-- 修改密码 -->
|
||||||
|
<div class="card">
|
||||||
|
<h3 class="card-title">修改密码</h3>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>当前密码</label>
|
||||||
|
<n-input v-model:value="pwdForm.old_password" type="password" show-password-on="click" placeholder="输入当前密码" />
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>新密码</label>
|
||||||
|
<n-input v-model:value="pwdForm.new_password" type="password" show-password-on="click" placeholder="至少6位" />
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>确认新密码</label>
|
||||||
|
<n-input v-model:value="pwdForm.confirm" type="password" show-password-on="click" placeholder="再次输入新密码" />
|
||||||
|
</div>
|
||||||
|
<n-button type="primary" :loading="changingPwd" @click="changePassword">修改密码</n-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 绑定邮箱 -->
|
||||||
|
<div class="card">
|
||||||
|
<h3 class="card-title">绑定邮箱</h3>
|
||||||
|
<div class="current-email">
|
||||||
|
<span class="label">当前邮箱</span>
|
||||||
|
<span class="value">{{ auth.user?.email || '未绑定' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>新邮箱</label>
|
||||||
|
<n-input v-model:value="emailForm.new_email" placeholder="输入新的邮箱地址" />
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>确认密码</label>
|
||||||
|
<n-input v-model:value="emailForm.password" type="password" show-password-on="click" placeholder="输入当前密码以确认" />
|
||||||
|
</div>
|
||||||
|
<n-button type="primary" :loading="changingEmail" @click="changeEmail">更换邮箱</n-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 退出登录 -->
|
||||||
|
<div class="card">
|
||||||
|
<h3 class="card-title">账号操作</h3>
|
||||||
|
<n-button type="error" ghost block @click="handleLogout">退出登录</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { reactive, ref } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { useMessage } from 'naive-ui'
|
||||||
|
import api from '@/api/client'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const message = useMessage()
|
||||||
|
|
||||||
|
const changingPwd = ref(false)
|
||||||
|
const changingEmail = ref(false)
|
||||||
|
|
||||||
|
const pwdForm = reactive({ old_password: '', new_password: '', confirm: '' })
|
||||||
|
const emailForm = reactive({ new_email: '', password: '' })
|
||||||
|
|
||||||
|
async function changePassword() {
|
||||||
|
if (!pwdForm.old_password || !pwdForm.new_password) {
|
||||||
|
message.warning('请填写完整')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (pwdForm.new_password.length < 6) {
|
||||||
|
message.warning('新密码至少6位')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (pwdForm.new_password !== pwdForm.confirm) {
|
||||||
|
message.warning('两次输入的密码不一致')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
changingPwd.value = true
|
||||||
|
try {
|
||||||
|
await api.put('/users/me/password', {
|
||||||
|
old_password: pwdForm.old_password,
|
||||||
|
new_password: pwdForm.new_password,
|
||||||
|
})
|
||||||
|
message.success('密码修改成功,请重新登录')
|
||||||
|
auth.logout()
|
||||||
|
router.push('/login')
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e.response?.data?.detail || '密码修改失败')
|
||||||
|
} finally {
|
||||||
|
changingPwd.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function changeEmail() {
|
||||||
|
if (!emailForm.new_email || !emailForm.password) {
|
||||||
|
message.warning('请填写完整')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
changingEmail.value = true
|
||||||
|
try {
|
||||||
|
await api.put('/users/me/email', {
|
||||||
|
email: emailForm.new_email,
|
||||||
|
password: emailForm.password,
|
||||||
|
})
|
||||||
|
await auth.fetchProfile()
|
||||||
|
message.success('邮箱已更新')
|
||||||
|
emailForm.new_email = ''
|
||||||
|
emailForm.password = ''
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e.response?.data?.detail || '邮箱更换失败')
|
||||||
|
} finally {
|
||||||
|
changingEmail.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleLogout() {
|
||||||
|
auth.logout()
|
||||||
|
router.push('/login')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.settings-page { padding: 24px; max-width: 600px; }
|
||||||
|
.page-header { margin-bottom: 24px; }
|
||||||
|
.page-header h2 { margin: 0; font-size: 20px; color: var(--color-primary-dark); }
|
||||||
|
.settings-content { display: flex; flex-direction: column; gap: 24px; }
|
||||||
|
.card {
|
||||||
|
background: var(--color-surface);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 20px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.card-title { margin: 0 0 16px; font-size: 16px; font-weight: 600; }
|
||||||
|
.form-group { margin-bottom: 12px; }
|
||||||
|
.form-group label {
|
||||||
|
display: block; font-size: 13px; color: var(--color-text-secondary);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
.current-email {
|
||||||
|
display: flex; align-items: center; gap: 8px;
|
||||||
|
padding: 10px 0; margin-bottom: 12px;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.current-email .label { font-size: 13px; color: var(--color-text-secondary); }
|
||||||
|
.current-email .value { font-size: 14px; font-weight: 500; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
<template>
|
||||||
|
<div class="settings-page">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>通知设置</h2>
|
||||||
|
</div>
|
||||||
|
<div class="settings-content">
|
||||||
|
<div class="card">
|
||||||
|
<div class="toggle-item">
|
||||||
|
<div class="toggle-info">
|
||||||
|
<span class="toggle-label">新消息通知</span>
|
||||||
|
<span class="toggle-desc">收到新消息时显示通知</span>
|
||||||
|
</div>
|
||||||
|
<n-switch v-model:value="settings.messageNotif" @update:value="save" />
|
||||||
|
</div>
|
||||||
|
<div class="toggle-item">
|
||||||
|
<div class="toggle-info">
|
||||||
|
<span class="toggle-label">好友请求通知</span>
|
||||||
|
<span class="toggle-desc">收到好友请求时显示通知</span>
|
||||||
|
</div>
|
||||||
|
<n-switch v-model:value="settings.friendNotif" @update:value="save" />
|
||||||
|
</div>
|
||||||
|
<div class="toggle-item">
|
||||||
|
<div class="toggle-info">
|
||||||
|
<span class="toggle-label">朋友圈动态通知</span>
|
||||||
|
<span class="toggle-desc">好友发布新动态时通知</span>
|
||||||
|
</div>
|
||||||
|
<n-switch v-model:value="settings.momentNotif" @update:value="save" />
|
||||||
|
</div>
|
||||||
|
<div class="toggle-item">
|
||||||
|
<div class="toggle-info">
|
||||||
|
<span class="toggle-label">消息提示音</span>
|
||||||
|
<span class="toggle-desc">收到消息时播放提示音</span>
|
||||||
|
</div>
|
||||||
|
<n-switch v-model:value="settings.sound" @update:value="save" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { reactive, onMounted } from 'vue'
|
||||||
|
import { useMessage } from 'naive-ui'
|
||||||
|
|
||||||
|
const message = useMessage()
|
||||||
|
|
||||||
|
const settings = reactive({
|
||||||
|
messageNotif: true,
|
||||||
|
friendNotif: true,
|
||||||
|
momentNotif: true,
|
||||||
|
sound: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
const saved = localStorage.getItem('notification_settings')
|
||||||
|
if (saved) Object.assign(settings, JSON.parse(saved))
|
||||||
|
})
|
||||||
|
|
||||||
|
function save() {
|
||||||
|
localStorage.setItem('notification_settings', JSON.stringify(settings))
|
||||||
|
message.success('设置已保存')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.settings-page { padding: 24px; max-width: 600px; }
|
||||||
|
.page-header { margin-bottom: 24px; }
|
||||||
|
.page-header h2 { margin: 0; font-size: 20px; color: var(--color-primary-dark); }
|
||||||
|
.settings-content { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.card {
|
||||||
|
background: var(--color-surface);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 4px 20px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.toggle-item {
|
||||||
|
display: flex; align-items: center; justify-content: space-between;
|
||||||
|
padding: 14px 0;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.toggle-item:last-child { border-bottom: none; }
|
||||||
|
.toggle-info { display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.toggle-label { font-size: 14px; font-weight: 500; }
|
||||||
|
.toggle-desc { font-size: 12px; color: var(--color-text-hint); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
<template>
|
||||||
|
<div class="settings-page">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>个人资料</h2>
|
||||||
|
</div>
|
||||||
|
<div class="settings-content">
|
||||||
|
<!-- 头像 -->
|
||||||
|
<div class="avatar-section">
|
||||||
|
<n-avatar v-if="auth.user?.avatar_url" :src="auth.user.avatar_url" :size="80" round />
|
||||||
|
<n-avatar v-else :size="80" round style="background: var(--color-primary); font-size: 32px">
|
||||||
|
{{ displayName.charAt(0).toUpperCase() }}
|
||||||
|
</n-avatar>
|
||||||
|
<n-button size="small" @click="triggerUpload" style="margin-top: 8px">更换头像</n-button>
|
||||||
|
<input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleAvatarUpload" />
|
||||||
|
</div>
|
||||||
|
<!-- 资料表单 -->
|
||||||
|
<div class="form-section">
|
||||||
|
<div class="form-item">
|
||||||
|
<label>用户名</label>
|
||||||
|
<span class="form-value">{{ auth.user?.username }}</span>
|
||||||
|
<span class="form-hint">(登录名,不可修改)</span>
|
||||||
|
</div>
|
||||||
|
<div class="form-item">
|
||||||
|
<label>昵称</label>
|
||||||
|
<n-input v-model:value="form.nickname" placeholder="设置你的显示名称" size="small" style="flex: 1" />
|
||||||
|
</div>
|
||||||
|
<div class="form-item">
|
||||||
|
<label>邮箱</label>
|
||||||
|
<span class="form-value">{{ auth.user?.email }}</span>
|
||||||
|
<n-button text size="small" type="primary" @click="$router.push('/settings/account')">修改</n-button>
|
||||||
|
</div>
|
||||||
|
<div class="form-item">
|
||||||
|
<label>个性签名</label>
|
||||||
|
<n-input v-model:value="form.bio" type="textarea" :rows="2" placeholder="介绍一下自己..." size="small" style="flex: 1" />
|
||||||
|
</div>
|
||||||
|
<n-button type="primary" :loading="saving" @click="saveProfile">保存修改</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, computed, onMounted } from 'vue'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { useMessage } from 'naive-ui'
|
||||||
|
import api from '@/api/client'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const message = useMessage()
|
||||||
|
const saving = ref(false)
|
||||||
|
const fileInput = ref<HTMLInputElement>()
|
||||||
|
|
||||||
|
const displayName = computed(() => auth.user?.nickname || auth.user?.username || '?')
|
||||||
|
|
||||||
|
const form = reactive({
|
||||||
|
nickname: auth.user?.nickname || '',
|
||||||
|
bio: auth.user?.bio || '',
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
form.nickname = auth.user?.nickname || ''
|
||||||
|
form.bio = auth.user?.bio || ''
|
||||||
|
})
|
||||||
|
|
||||||
|
function triggerUpload() {
|
||||||
|
fileInput.value?.click()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAvatarUpload(event: Event) {
|
||||||
|
const target = event.target as HTMLInputElement
|
||||||
|
const file = target.files?.[0]
|
||||||
|
if (!file) return
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('file', file)
|
||||||
|
try {
|
||||||
|
const { data } = await api.post('/uploads/avatar', formData, {
|
||||||
|
headers: { 'Content-Type': 'multipart/form-data' },
|
||||||
|
})
|
||||||
|
await api.put('/users/me', { avatar_url: data.url })
|
||||||
|
await auth.fetchProfile()
|
||||||
|
message.success('头像已更新')
|
||||||
|
} catch {
|
||||||
|
message.error('头像上传失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveProfile() {
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
await api.put('/users/me', { nickname: form.nickname, bio: form.bio })
|
||||||
|
await auth.fetchProfile()
|
||||||
|
message.success('资料已保存')
|
||||||
|
} catch {
|
||||||
|
message.error('保存失败')
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.settings-page { padding: 24px; max-width: 600px; }
|
||||||
|
.page-header { margin-bottom: 24px; }
|
||||||
|
.page-header h2 { margin: 0; font-size: 20px; color: var(--color-primary-dark); }
|
||||||
|
.settings-content { display: flex; flex-direction: column; gap: 24px; }
|
||||||
|
.avatar-section { text-align: center; padding: 16px; }
|
||||||
|
.form-section { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.form-item {
|
||||||
|
display: flex; align-items: center; gap: 12px;
|
||||||
|
padding: 8px 0; border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.form-item label {
|
||||||
|
width: 80px; font-size: 14px; color: var(--color-text-secondary);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.form-value { font-size: 14px; color: var(--color-text-primary); }
|
||||||
|
.form-hint { font-size: 12px; color: var(--color-text-hint); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
<template>
|
||||||
|
<div class="settings-sidebar">
|
||||||
|
<div class="panel-header">
|
||||||
|
<h3 class="panel-title">设置</h3>
|
||||||
|
</div>
|
||||||
|
<div class="menu-list">
|
||||||
|
<router-link to="/settings/profile" class="menu-item" active-class="active">
|
||||||
|
<span class="menu-icon">👤</span>
|
||||||
|
<span class="menu-label">个人资料</span>
|
||||||
|
</router-link>
|
||||||
|
<router-link to="/settings/account" class="menu-item" active-class="active">
|
||||||
|
<span class="menu-icon">🔒</span>
|
||||||
|
<span class="menu-label">账号安全</span>
|
||||||
|
</router-link>
|
||||||
|
<router-link to="/settings/notifications" class="menu-item" active-class="active">
|
||||||
|
<span class="menu-icon">🔔</span>
|
||||||
|
<span class="menu-label">通知设置</span>
|
||||||
|
</router-link>
|
||||||
|
<router-link to="/settings/about" class="menu-item" active-class="active">
|
||||||
|
<span class="menu-icon">ℹ️</span>
|
||||||
|
<span class="menu-label">关于青叶</span>
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
<div class="sidebar-bottom">
|
||||||
|
<div class="user-card" @click="$router.push('/settings/profile')">
|
||||||
|
<n-avatar v-if="auth.user?.avatar_url" :src="auth.user.avatar_url" :size="40" round />
|
||||||
|
<n-avatar v-else :size="40" round style="background: var(--color-primary)">
|
||||||
|
{{ displayName.charAt(0).toUpperCase() }}
|
||||||
|
</n-avatar>
|
||||||
|
<div class="user-meta">
|
||||||
|
<span class="user-name">{{ displayName }}</span>
|
||||||
|
<span class="user-id">@{{ auth.user?.username }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const displayName = computed(() => auth.user?.nickname || auth.user?.username || '?')
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.settings-sidebar {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
.panel-header {
|
||||||
|
padding: 16px;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.panel-title { margin: 0; font-size: 16px; font-weight: 600; }
|
||||||
|
.menu-list { flex: 1; padding: 8px 0; }
|
||||||
|
.menu-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px 16px;
|
||||||
|
text-decoration: none;
|
||||||
|
color: var(--color-text-primary);
|
||||||
|
font-size: 14px;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
.menu-item:hover { background: var(--color-primary-lightest); }
|
||||||
|
.menu-item.active {
|
||||||
|
background: var(--color-primary-lightest);
|
||||||
|
color: var(--color-primary);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.menu-icon { font-size: 18px; }
|
||||||
|
.sidebar-bottom {
|
||||||
|
padding: 12px;
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.user-card {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 8px;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
.user-card:hover { background: var(--color-primary-lightest); }
|
||||||
|
.user-meta { display: flex; flex-direction: column; }
|
||||||
|
.user-name { font-weight: 500; font-size: 14px; }
|
||||||
|
.user-id { font-size: 12px; color: var(--color-text-hint); }
|
||||||
|
</style>
|
||||||
@@ -6,4 +6,10 @@
|
|||||||
|
|
||||||
前端的用户和管理员界面,都看不到登录界面。用户界面目前一片空白。请检查。此外,需要实现热挂载,即修改了前端或后端代码后,不需要重启docker(除非必要),刷新就能看到效果。
|
前端的用户和管理员界面,都看不到登录界面。用户界面目前一片空白。请检查。此外,需要实现热挂载,即修改了前端或后端代码后,不需要重启docker(除非必要),刷新就能看到效果。
|
||||||
|
|
||||||
这三个页面目前都变成一片空白了
|
这三个页面目前都变成一片空白了
|
||||||
|
|
||||||
|
功能太少,操作不方便,过于简洁,没有基础的功能,设置页面加入修改密码等,用户名和昵称可以分开,简化加好友功能,加入群聊,左边固定栏,选择功能,内容丰富一点,加入好友圈。
|
||||||
|
|
||||||
|
账号绑定邮箱
|
||||||
|
|
||||||
|
不要列表卡片瀑布流,功能丰富一点,不要太单调,界面也丰富一点
|
||||||
Reference in New Issue
Block a user