feat: 实时消息与管理端运营能力
新增群聊/私信与公共 WebSocket 总线,站长用户内容档案,并将通知与待审角标改为推送驱动;同步精简管理仪表盘并修复主题换肤 DOM 冲突。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -23,6 +23,7 @@ require (
|
|||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||||
github.com/goccy/go-json v0.10.2 // indirect
|
github.com/goccy/go-json v0.10.2 // indirect
|
||||||
|
github.com/gorilla/websocket v1.5.3 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVI
|
|||||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||||
|
|||||||
@@ -105,6 +105,65 @@ func (h *Handlers) AdminUserLoginLogs(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, gin.H{"logs": logs, "total": total, "page": page})
|
c.JSON(http.StatusOK, gin.H{"logs": logs, "total": total, "page": page})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AdminGetUserAudit 站长:用户内容档案摘要
|
||||||
|
func (h *Handlers) AdminGetUserAudit(c *gin.Context) {
|
||||||
|
id, ok := parseAdminUserID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
profile, err := h.AdminUser.GetAuditProfile(middleware.CurrentActor(c), id)
|
||||||
|
if err != nil {
|
||||||
|
respondAdminUserError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminUserAuditPosts 站长:用户帖子(含驳回/软删)
|
||||||
|
func (h *Handlers) AdminUserAuditPosts(c *gin.Context) {
|
||||||
|
id, ok := parseAdminUserID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
|
items, total, page, err := h.AdminUser.ListAuditPosts(middleware.CurrentActor(c), id, page, 20)
|
||||||
|
if err != nil {
|
||||||
|
respondAdminUserError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"items": items, "total": total, "page": page})
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminUserAuditComments 站长:用户评论(含驳回/软删)
|
||||||
|
func (h *Handlers) AdminUserAuditComments(c *gin.Context) {
|
||||||
|
id, ok := parseAdminUserID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
|
items, total, page, err := h.AdminUser.ListAuditComments(middleware.CurrentActor(c), id, page, 20)
|
||||||
|
if err != nil {
|
||||||
|
respondAdminUserError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"items": items, "total": total, "page": page})
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminUserAuditMessages 站长:用户聊天消息(含撤回/软删)
|
||||||
|
func (h *Handlers) AdminUserAuditMessages(c *gin.Context) {
|
||||||
|
id, ok := parseAdminUserID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
|
items, total, page, err := h.AdminUser.ListAuditMessages(middleware.CurrentActor(c), id, page, 20)
|
||||||
|
if err != nil {
|
||||||
|
respondAdminUserError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"items": items, "total": total, "page": page})
|
||||||
|
}
|
||||||
|
|
||||||
// parseAdminUserID 解析路径中的用户 ID,失败时直接写出 400
|
// parseAdminUserID 解析路径中的用户 ID,失败时直接写出 400
|
||||||
func parseAdminUserID(c *gin.Context) (uint, bool) {
|
func parseAdminUserID(c *gin.Context) (uint, bool) {
|
||||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
@@ -120,8 +179,8 @@ func respondAdminUserError(c *gin.Context, err error) {
|
|||||||
switch {
|
switch {
|
||||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
|
||||||
case errors.Is(err, service.ErrProtectedOwner):
|
case errors.Is(err, service.ErrProtectedOwner),
|
||||||
// 站长保护属于权限边界而非参数错误
|
errors.Is(err, service.ErrOwnerOnly):
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
case errors.Is(err, service.ErrAdminSelfAction),
|
case errors.Is(err, service.ErrAdminSelfAction),
|
||||||
errors.Is(err, service.ErrInvalidRole),
|
errors.Is(err, service.ErrInvalidRole),
|
||||||
|
|||||||
@@ -117,6 +117,7 @@ func (h *Handlers) Register(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
_ = h.Chat.EnsureDefaultMembership(user.ID)
|
||||||
// 自动登录:走与 Login 相同的 token 签发链路
|
// 自动登录:走与 Login 相同的 token 签发链路
|
||||||
accessToken, refreshToken, loginUser, err := h.Auth.Login(req.Username, req.Password)
|
accessToken, refreshToken, loginUser, err := h.Auth.Login(req.Username, req.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -263,7 +264,7 @@ func meUserBody(user *model.User, boardIDs []uint) gin.H {
|
|||||||
func (h *Handlers) Me(c *gin.Context) {
|
func (h *Handlers) Me(c *gin.Context) {
|
||||||
claims := middleware.CurrentUser(c)
|
claims := middleware.CurrentUser(c)
|
||||||
if claims == nil {
|
if claims == nil {
|
||||||
resp := gin.H{"user": nil, "unread_count": 0}
|
resp := gin.H{"user": nil, "unread_count": 0, "chat_unread_count": 0}
|
||||||
// OptionalAuth 识别到封禁:HTTP 仍为 200(/me 不阻断页面),
|
// OptionalAuth 识别到封禁:HTTP 仍为 200(/me 不阻断页面),
|
||||||
// 但带 banned/code,客户端静默校正时据此强制下线并弹告知
|
// 但带 banned/code,客户端静默校正时据此强制下线并弹告知
|
||||||
if c.GetBool(middleware.AccountBannedKey) {
|
if c.GetBool(middleware.AccountBannedKey) {
|
||||||
@@ -275,17 +276,22 @@ func (h *Handlers) Me(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
user, err := h.Auth.GetUserByID(claims.ID)
|
user, err := h.Auth.GetUserByID(claims.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusOK, gin.H{"user": nil, "unread_count": 0})
|
c.JSON(http.StatusOK, gin.H{"user": nil, "unread_count": 0, "chat_unread_count": 0})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var unread int64
|
var unread int64
|
||||||
if n, err := h.Notification.UnreadCount(claims.ID); err == nil {
|
if n, err := h.Notification.UnreadCount(claims.ID); err == nil {
|
||||||
unread = n
|
unread = n
|
||||||
}
|
}
|
||||||
|
chatUnread := h.Chat.TotalUnread(claims.ID)
|
||||||
// 板块管理员带出授权板块,供前端菜单/按钮按板块范围渲染
|
// 板块管理员带出授权板块,供前端菜单/按钮按板块范围渲染
|
||||||
var boardIDs []uint
|
var boardIDs []uint
|
||||||
if user.Role == model.RoleBoardAdmin {
|
if user.Role == model.RoleBoardAdmin {
|
||||||
boardIDs, _ = h.Auth.GetUserBoardIDs(claims.ID)
|
boardIDs, _ = h.Auth.GetUserBoardIDs(claims.ID)
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"user": meUserBody(user, boardIDs), "unread_count": unread})
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"user": meUserBody(user, boardIDs),
|
||||||
|
"unread_count": unread,
|
||||||
|
"chat_unread_count": chatUnread,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
459
backend/handler/chat.go
Normal file
459
backend/handler/chat.go
Normal file
@@ -0,0 +1,459 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/freefire/jiang13-bbs/middleware"
|
||||||
|
"github.com/freefire/jiang13-bbs/realtime"
|
||||||
|
"github.com/freefire/jiang13-bbs/service"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// chatErrToStatus 群聊业务错误 → HTTP 状态
|
||||||
|
func chatErrToStatus(err error) int {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, service.ErrChatNotFound), errors.Is(err, service.ErrChatMsgNotFound):
|
||||||
|
return http.StatusNotFound
|
||||||
|
case errors.Is(err, service.ErrChatNotMember), errors.Is(err, service.ErrChatMuted),
|
||||||
|
errors.Is(err, service.ErrChatOwnerOnly), errors.Is(err, service.ErrChatPrivateInvite),
|
||||||
|
errors.Is(err, service.ErrChatRecallDenied), errors.Is(err, service.ErrChatDefaultLeave),
|
||||||
|
errors.Is(err, service.ErrChatDefaultDissolve), errors.Is(err, service.ErrChatDMDissolve),
|
||||||
|
errors.Is(err, service.ErrChatHallPinFixed):
|
||||||
|
return http.StatusForbidden
|
||||||
|
case errors.Is(err, service.ErrChatDMSelf), errors.Is(err, service.ErrChatUserGone):
|
||||||
|
return http.StatusBadRequest
|
||||||
|
default:
|
||||||
|
return http.StatusBadRequest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func chatRoomID(c *gin.Context) (uint, bool) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "群 ID 无效"})
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return uint(id), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) chatOversee(userID uint) bool {
|
||||||
|
actor, err := h.Auth.LoadActor(userID)
|
||||||
|
if err != nil || actor == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return service.CanOverseeChat(actor.Role)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateChatRoom 建群(可公开/私密,私密可带初始成员)
|
||||||
|
func (h *Handlers) CreateChatRoom(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
IsPrivate bool `json:"is_private"`
|
||||||
|
MemberIDs []uint `json:"member_ids"`
|
||||||
|
MemberUsernames []string `json:"member_usernames"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
memberIDs := append([]uint{}, req.MemberIDs...)
|
||||||
|
for _, name := range req.MemberUsernames {
|
||||||
|
if uid := h.Auth.GetUserIDByUsername(name); uid > 0 && uid != claims.ID {
|
||||||
|
memberIDs = append(memberIDs, uid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
room, err := h.Chat.CreateRoom(claims.ID, req.Name, req.Description, req.IsPrivate, memberIDs)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 通知被拉入的初始成员
|
||||||
|
seen := map[uint]bool{}
|
||||||
|
for _, uid := range memberIDs {
|
||||||
|
if uid == 0 || uid == claims.ID || seen[uid] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[uid] = true
|
||||||
|
h.Hub.BroadcastUser(uid, realtime.Envelope{
|
||||||
|
Type: realtime.EventChatMembership,
|
||||||
|
Data: gin.H{"room_id": room.ID, "status": "invited"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"room": room})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListChatRooms 会话列表(默认 IM 侧栏仅已加入;scope=all 可浏览公开群)
|
||||||
|
func (h *Handlers) ListChatRooms(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
|
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||||
|
joinedOnly := c.DefaultQuery("scope", "joined") != "all"
|
||||||
|
oversee := h.chatOversee(claims.ID)
|
||||||
|
rooms, total, err := h.Chat.ListRooms(claims.ID, oversee, joinedOnly, c.Query("q"), page, size)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取会话列表失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"rooms": rooms, "total": total, "page": page, "size": size})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetChatRoom 群详情(公开非成员可预览;私密非成员 404)
|
||||||
|
func (h *Handlers) GetChatRoom(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
oversee := h.chatOversee(claims.ID)
|
||||||
|
room, err := h.Chat.RoomDetail(claims.ID, roomID, oversee)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"room": room})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateChatRoom 群主改群名/简介
|
||||||
|
func (h *Handlers) UpdateChatRoom(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
room, err := h.Chat.UpdateRoom(claims.ID, roomID, req.Name, req.Description)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"room": room})
|
||||||
|
}
|
||||||
|
|
||||||
|
// PinChatRoom 当前用户置顶/取消置顶会话
|
||||||
|
func (h *Handlers) PinChatRoom(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req struct {
|
||||||
|
Pinned bool `json:"pinned"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
room, err := h.Chat.SetRoomPinned(claims.ID, roomID, req.Pinned)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"room": room})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DissolveChatRoom 群主/监管解散群
|
||||||
|
func (h *Handlers) DissolveChatRoom(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
oversee := h.chatOversee(claims.ID)
|
||||||
|
members, err := h.Chat.ListMembers(claims.ID, roomID, oversee)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.Chat.Dissolve(claims.ID, roomID, oversee); err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
roomName := realtime.RoomChat(roomID)
|
||||||
|
for _, m := range members {
|
||||||
|
h.Hub.RemoveUserRoom(m.UserID, roomName)
|
||||||
|
h.Hub.BroadcastUser(m.UserID, realtime.Envelope{
|
||||||
|
Type: realtime.EventChatMembership,
|
||||||
|
Data: gin.H{"room_id": roomID, "status": "dissolved"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinChatRoom 加入公开群
|
||||||
|
func (h *Handlers) JoinChatRoom(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _, err := h.Chat.Join(claims.ID, roomID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// LeaveChatRoom 退出群
|
||||||
|
func (h *Handlers) LeaveChatRoom(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.Chat.Leave(claims.ID, roomID); err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.Hub.RemoveUserRoom(claims.ID, realtime.RoomChat(roomID))
|
||||||
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteChatMembers 群主/监管邀请入群
|
||||||
|
func (h *Handlers) InviteChatMembers(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req struct {
|
||||||
|
UserIDs []uint `json:"user_ids"`
|
||||||
|
Usernames []string `json:"usernames"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择要邀请的用户"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ids := append([]uint{}, req.UserIDs...)
|
||||||
|
for _, name := range req.Usernames {
|
||||||
|
if uid := h.Auth.GetUserIDByUsername(name); uid > 0 {
|
||||||
|
ids = append(ids, uid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择要邀请的用户"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
oversee := h.chatOversee(claims.ID)
|
||||||
|
added, err := h.Chat.InviteMembers(claims.ID, roomID, ids, oversee)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, uid := range added {
|
||||||
|
h.Hub.BroadcastUser(uid, realtime.Envelope{
|
||||||
|
Type: realtime.EventChatMembership,
|
||||||
|
Data: gin.H{"room_id": roomID, "status": "invited"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"added": added})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListChatMembers 成员列表
|
||||||
|
func (h *Handlers) ListChatMembers(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
oversee := h.chatOversee(claims.ID)
|
||||||
|
list, err := h.Chat.ListMembers(claims.ID, roomID, oversee)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"members": list})
|
||||||
|
}
|
||||||
|
|
||||||
|
// KickChatMember 群主踢人
|
||||||
|
func (h *Handlers) KickChatMember(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
targetID, err := strconv.ParseUint(c.Param("uid"), 10, 64)
|
||||||
|
if err != nil || targetID == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "用户 ID 无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.Chat.Kick(claims.ID, roomID, uint(targetID)); err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.Hub.RemoveUserRoom(uint(targetID), realtime.RoomChat(roomID))
|
||||||
|
h.Hub.BroadcastUser(uint(targetID), realtime.Envelope{
|
||||||
|
Type: realtime.EventChatMembership,
|
||||||
|
Data: gin.H{"room_id": roomID, "status": "kicked"},
|
||||||
|
})
|
||||||
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListChatMessages 历史消息
|
||||||
|
func (h *Handlers) ListChatMessages(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
beforeID, _ := strconv.ParseUint(c.Query("before_id"), 10, 64)
|
||||||
|
size, _ := strconv.Atoi(c.DefaultQuery("size", "30"))
|
||||||
|
oversee := h.chatOversee(claims.ID)
|
||||||
|
msgs, hasMore, err := h.Chat.ListMessages(claims.ID, roomID, uint(beforeID), size, oversee)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"messages": msgs, "has_more": hasMore})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendChatMessage 发消息
|
||||||
|
func (h *Handlers) SendChatMessage(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
ReplyToID uint `json:"reply_to_id"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
msg, _, err := h.Chat.SendMessage(claims.ID, roomID, req.Content, req.ReplyToID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
|
||||||
|
Type: realtime.EventChatMessage,
|
||||||
|
Data: msg,
|
||||||
|
})
|
||||||
|
// 向未在房内订阅的成员推未读增量(Header / 会话列表实时角标)
|
||||||
|
if memberIDs, mErr := h.Chat.ListMemberIDs(roomID); mErr == nil {
|
||||||
|
preview := req.Content
|
||||||
|
runes := []rune(preview)
|
||||||
|
if len(runes) > 80 {
|
||||||
|
preview = string(runes[:80])
|
||||||
|
}
|
||||||
|
for _, uid := range memberIDs {
|
||||||
|
if uid == claims.ID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
h.Hub.BroadcastUser(uid, realtime.Envelope{
|
||||||
|
Type: realtime.EventChatUnread,
|
||||||
|
Data: gin.H{
|
||||||
|
"room_id": roomID,
|
||||||
|
"message_id": msg.ID,
|
||||||
|
"sender_id": claims.ID,
|
||||||
|
"preview": preview,
|
||||||
|
"delta": 1,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// @ 通知的 WS 红点由 Notification.CreateMention → OnNotifyNew 统一推送
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": msg})
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecallChatMessage 撤回消息
|
||||||
|
func (h *Handlers) RecallChatMessage(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mid, err := strconv.ParseUint(c.Param("mid"), 10, 64)
|
||||||
|
if err != nil || mid == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "消息 ID 无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
oversee := h.chatOversee(claims.ID)
|
||||||
|
msg, err := h.Chat.RecallMessage(claims.ID, roomID, uint(mid), oversee)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
|
||||||
|
Type: realtime.EventChatRecalled,
|
||||||
|
Data: gin.H{
|
||||||
|
"id": msg.ID,
|
||||||
|
"room_id": roomID,
|
||||||
|
"sender_id": msg.SenderID,
|
||||||
|
"recalled_by": msg.RecalledBy,
|
||||||
|
"recalled_at": msg.RecalledAt,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": msg})
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkChatRead 推进已读水位
|
||||||
|
func (h *Handlers) MarkChatRead(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
roomID, ok := chatRoomID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req struct {
|
||||||
|
MessageID uint `json:"message_id"`
|
||||||
|
}
|
||||||
|
_ = c.ShouldBindJSON(&req)
|
||||||
|
if err := h.Chat.MarkRead(claims.ID, roomID, req.MessageID); err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenDirectChat 获取或创建与指定用户的私聊
|
||||||
|
func (h *Handlers) OpenDirectChat(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
var req struct {
|
||||||
|
UserID uint `json:"user_id"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil || req.UserID == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请指定用户"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
room, err := h.Chat.GetOrCreateDM(claims.ID, req.UserID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"room": room})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SearchChatUsers 消息页搜索用户以发起私聊
|
||||||
|
func (h *Handlers) SearchChatUsers(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
users, err := h.Chat.SearchUsersForChat(claims.ID, c.Query("q"), 10)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "搜索失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"users": users})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatUnreadSummary 未读汇总
|
||||||
|
func (h *Handlers) ChatUnreadSummary(c *gin.Context) {
|
||||||
|
claims := middleware.CurrentUser(c)
|
||||||
|
total, rooms, err := h.Chat.UnreadSummary(claims.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取未读失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"total": total, "rooms": rooms})
|
||||||
|
}
|
||||||
@@ -23,17 +23,22 @@ func (h *Handlers) PostComments(c *gin.Context) {
|
|||||||
|
|
||||||
// 待审/被拒帖子的评论不对公众开放
|
// 待审/被拒帖子的评论不对公众开放
|
||||||
var viewerID uint
|
var viewerID uint
|
||||||
|
var actor *service.Actor
|
||||||
var loadActor func() *service.Actor
|
var loadActor func() *service.Actor
|
||||||
if claims := middleware.CurrentUser(c); claims != nil {
|
if claims := middleware.CurrentUser(c); claims != nil {
|
||||||
viewerID = claims.ID
|
viewerID = claims.ID
|
||||||
loadActor = h.actorLoader(claims.ID)
|
loadActor = h.actorLoader(claims.ID)
|
||||||
|
if a, err := h.Auth.LoadActor(claims.ID); err == nil {
|
||||||
|
actor = a
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err := h.Post.EnsurePostVisible(uint(id), viewerID, loadActor); err != nil {
|
if err := h.Post.EnsurePostVisible(uint(id), viewerID, loadActor); err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
boardID, _ := h.Post.GetBoardID(uint(id))
|
||||||
|
|
||||||
comments, floors, totalComments, err := h.Comment.ListFloorPaged(uint(id), page, size)
|
comments, floors, totalComments, err := h.Comment.ListFloorPaged(uint(id), boardID, viewerID, actor, page, size)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
@@ -86,6 +91,13 @@ func (h *Handlers) CreateComment(c *gin.Context) {
|
|||||||
// 子回复:通知父评论作者(Notification.Create 内部排除自我通知)
|
// 子回复:通知父评论作者(Notification.Create 内部排除自我通知)
|
||||||
h.Notification.Create(parent.UserID, claims.ID, model.NotificationTypeReply, uint(id), comment.ID, req.Content)
|
h.Notification.Create(parent.UserID, claims.ID, model.NotificationTypeReply, uint(id), comment.ID, req.Content)
|
||||||
}
|
}
|
||||||
|
if boardID, e := h.Post.GetBoardID(uint(id)); e == nil {
|
||||||
|
h.broadcastFeedChanged("comment", uint(id), boardID, claims.ID)
|
||||||
|
}
|
||||||
|
} else if comment.Status == model.ContentStatusPending {
|
||||||
|
if boardID, e := h.Post.GetBoardID(uint(id)); e == nil {
|
||||||
|
h.notifyPendingReview(boardID, claims.ID, uint(id), comment.ID, "有新评论待审核")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"comment": comment})
|
c.JSON(http.StatusOK, gin.H{"comment": comment})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,16 @@ package handler
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/freefire/jiang13-bbs/config"
|
"github.com/freefire/jiang13-bbs/config"
|
||||||
|
"github.com/freefire/jiang13-bbs/model"
|
||||||
|
"github.com/freefire/jiang13-bbs/realtime"
|
||||||
"github.com/freefire/jiang13-bbs/service"
|
"github.com/freefire/jiang13-bbs/service"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Handlers 聚合所有服务引用
|
// Handlers 聚合所有服务引用
|
||||||
type Handlers struct {
|
type Handlers struct {
|
||||||
Cfg *config.Config
|
Cfg *config.Config
|
||||||
|
Hub *realtime.Hub
|
||||||
Auth *service.AuthService
|
Auth *service.AuthService
|
||||||
Board *service.BoardService
|
Board *service.BoardService
|
||||||
Post *service.PostService
|
Post *service.PostService
|
||||||
@@ -21,4 +25,46 @@ type Handlers struct {
|
|||||||
Setting *service.SettingService
|
Setting *service.SettingService
|
||||||
AdminUser *service.AdminUserService
|
AdminUser *service.AdminUserService
|
||||||
Moderation *service.ModerationService
|
Moderation *service.ModerationService
|
||||||
|
Chat *service.ChatService
|
||||||
|
}
|
||||||
|
|
||||||
|
// broadcastFeedChanged 帖子流有公开发布内容时全员广播(三期)
|
||||||
|
func (h *Handlers) broadcastFeedChanged(kind string, postID, boardID, actorID uint) {
|
||||||
|
if h.Hub == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.Hub.BroadcastAll(realtime.Envelope{
|
||||||
|
Type: realtime.EventFeedChanged,
|
||||||
|
Data: gin.H{
|
||||||
|
"kind": kind,
|
||||||
|
"post_id": postID,
|
||||||
|
"board_id": boardID,
|
||||||
|
"actor_id": actorID,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// notifyPendingReview 待审内容通知该板可审者(WS 红点由 Notification.OnNotifyNew 统一推送)
|
||||||
|
func (h *Handlers) notifyPendingReview(boardID, actorID, postID, commentID uint, preview string) {
|
||||||
|
ids, err := h.Auth.ListBoardModeratorIDs(boardID)
|
||||||
|
if err != nil || len(ids) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, uid := range ids {
|
||||||
|
if uid == actorID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
h.Notification.Create(uid, actorID, model.NotificationTypePendingReview, postID, commentID, preview)
|
||||||
|
}
|
||||||
|
h.broadcastModerationChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
// broadcastModerationChanged 通知管理团队待审队列有变化(角标由客户端按权限再拉一次)
|
||||||
|
func (h *Handlers) broadcastModerationChanged() {
|
||||||
|
if h.Hub == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.Hub.BroadcastRoom(realtime.RoomStaff, realtime.Envelope{
|
||||||
|
Type: realtime.EventModerationChanged,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,20 @@ func (h *Handlers) AdminPendingCounts(c *gin.Context) {
|
|||||||
|
|
||||||
// AdminApprovePost 通过帖子
|
// AdminApprovePost 通过帖子
|
||||||
func (h *Handlers) AdminApprovePost(c *gin.Context) {
|
func (h *Handlers) AdminApprovePost(c *gin.Context) {
|
||||||
h.execModeration(c, h.Moderation.ApprovePost)
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的 ID"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor := middleware.CurrentActor(c)
|
||||||
|
boardID, err := h.Moderation.ApprovePost(actor, uint(id))
|
||||||
|
if err != nil {
|
||||||
|
h.writeModerationError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.broadcastFeedChanged("post", uint(id), boardID, actor.ID)
|
||||||
|
h.broadcastModerationChanged()
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "操作成功"})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AdminRejectPost 拒绝帖子
|
// AdminRejectPost 拒绝帖子
|
||||||
@@ -53,7 +66,20 @@ func (h *Handlers) AdminRejectPost(c *gin.Context) {
|
|||||||
|
|
||||||
// AdminApproveComment 通过评论
|
// AdminApproveComment 通过评论
|
||||||
func (h *Handlers) AdminApproveComment(c *gin.Context) {
|
func (h *Handlers) AdminApproveComment(c *gin.Context) {
|
||||||
h.execModeration(c, h.Moderation.ApproveComment)
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的 ID"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor := middleware.CurrentActor(c)
|
||||||
|
postID, boardID, err := h.Moderation.ApproveComment(actor, uint(id))
|
||||||
|
if err != nil {
|
||||||
|
h.writeModerationError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.broadcastFeedChanged("comment", postID, boardID, actor.ID)
|
||||||
|
h.broadcastModerationChanged()
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "操作成功"})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AdminRejectComment 拒绝评论
|
// AdminRejectComment 拒绝评论
|
||||||
@@ -61,7 +87,21 @@ func (h *Handlers) AdminRejectComment(c *gin.Context) {
|
|||||||
h.execModeration(c, h.Moderation.RejectComment)
|
h.execModeration(c, h.Moderation.RejectComment)
|
||||||
}
|
}
|
||||||
|
|
||||||
// execModeration 统一解析 :id 并映射审核业务错误
|
// writeModerationError 映射审核业务错误为 HTTP 响应
|
||||||
|
func (h *Handlers) writeModerationError(c *gin.Context, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "内容不存在"})
|
||||||
|
case errors.Is(err, service.ErrModerationForbidden):
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
case errors.Is(err, service.ErrNotPending):
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
default:
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "操作失败"})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// execModeration 统一解析 :id 并映射审核业务错误(拒绝等无额外副作用的操作)
|
||||||
func (h *Handlers) execModeration(c *gin.Context, fn func(*service.Actor, uint) error) {
|
func (h *Handlers) execModeration(c *gin.Context, fn func(*service.Actor, uint) error) {
|
||||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
if err != nil || id == 0 {
|
if err != nil || id == 0 {
|
||||||
@@ -69,17 +109,9 @@ func (h *Handlers) execModeration(c *gin.Context, fn func(*service.Actor, uint)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := fn(middleware.CurrentActor(c), uint(id)); err != nil {
|
if err := fn(middleware.CurrentActor(c), uint(id)); err != nil {
|
||||||
switch {
|
h.writeModerationError(c, err)
|
||||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "内容不存在"})
|
|
||||||
case errors.Is(err, service.ErrModerationForbidden):
|
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
|
||||||
case errors.Is(err, service.ErrNotPending):
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
default:
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "操作失败"})
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
h.broadcastModerationChanged()
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "操作成功"})
|
c.JSON(http.StatusOK, gin.H{"message": "操作成功"})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,15 @@ func (h *Handlers) Posts(c *gin.Context) {
|
|||||||
keyword := c.Query("keyword")
|
keyword := c.Query("keyword")
|
||||||
recommended := c.Query("recommended") == "true"
|
recommended := c.Query("recommended") == "true"
|
||||||
|
|
||||||
|
var viewerID uint
|
||||||
|
var actor *service.Actor
|
||||||
|
if claims := middleware.CurrentUser(c); claims != nil {
|
||||||
|
viewerID = claims.ID
|
||||||
|
if a, err := h.Auth.LoadActor(claims.ID); err == nil {
|
||||||
|
actor = a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
items, total, err := h.Post.List(service.PostListQuery{
|
items, total, err := h.Post.List(service.PostListQuery{
|
||||||
BoardID: uint(boardID),
|
BoardID: uint(boardID),
|
||||||
Page: page,
|
Page: page,
|
||||||
@@ -27,6 +36,8 @@ func (h *Handlers) Posts(c *gin.Context) {
|
|||||||
Sort: sort,
|
Sort: sort,
|
||||||
Keyword: keyword,
|
Keyword: keyword,
|
||||||
Recommended: recommended,
|
Recommended: recommended,
|
||||||
|
ViewerID: viewerID,
|
||||||
|
Actor: actor,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
@@ -109,6 +120,11 @@ func (h *Handlers) CreatePost(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if post.Status == model.ContentStatusPublished {
|
||||||
|
h.broadcastFeedChanged("post", post.ID, post.BoardID, claims.ID)
|
||||||
|
} else if post.Status == model.ContentStatusPending {
|
||||||
|
h.notifyPendingReview(post.BoardID, claims.ID, post.ID, 0, "有新帖待审核:"+post.Title)
|
||||||
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"post": post})
|
c.JSON(http.StatusOK, gin.H{"post": post})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
126
backend/handler/realtime.go
Normal file
126
backend/handler/realtime.go
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/freefire/jiang13-bbs/realtime"
|
||||||
|
"github.com/freefire/jiang13-bbs/service"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
// parseWSChatRoom 解析 WS 房间名 chat:{roomID}
|
||||||
|
func parseWSChatRoom(room string) (uint, bool) {
|
||||||
|
idStr := strings.TrimPrefix(room, "chat:")
|
||||||
|
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return uint(id), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 实时总线 WebSocket 入口:GET /api/ws
|
||||||
|
//
|
||||||
|
// 鉴权:与 REST 一致,优先读 HttpOnly 的 j13_token cookie(浏览器握手自动携带),
|
||||||
|
// 回退 Authorization 头;ParseToken + ValidateClaims 实时校验 token_version 与封禁。
|
||||||
|
// WebSocket 握手是 GET 请求,天然不受 CSRF 约束,但必须严格校验 Origin,
|
||||||
|
// 防止跨站页面在用户浏览器中发起握手。
|
||||||
|
func (h *Handlers) RealtimeWS(c *gin.Context) {
|
||||||
|
tokenStr, err := c.Cookie(service.CookieName)
|
||||||
|
if err != nil || tokenStr == "" {
|
||||||
|
if auth := c.GetHeader("Authorization"); strings.HasPrefix(auth, "Bearer ") {
|
||||||
|
tokenStr = strings.TrimPrefix(auth, "Bearer ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tokenStr == "" {
|
||||||
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
claims, err := h.Auth.ParseToken(tokenStr)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "登录态无效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := h.Auth.ValidateClaims(claims); err != nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "登录态已失效"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
upgrader := websocket.Upgrader{
|
||||||
|
HandshakeTimeout: 5 * time.Second,
|
||||||
|
CheckOrigin: h.checkWSOrigin,
|
||||||
|
// 子协议不传:鉴权完全走 cookie,禁止 Sec-WebSocket-Protocol 携带 token
|
||||||
|
}
|
||||||
|
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||||
|
if err != nil {
|
||||||
|
return // Upgrade 内部已写错误响应
|
||||||
|
}
|
||||||
|
|
||||||
|
// 建连时取实时角色快照决定能否进入 staff 房间(角色变更后旧 JWT 会失效,
|
||||||
|
// 用户重连即按新角色重新入房)
|
||||||
|
isStaff := false
|
||||||
|
canOverseeChat := false
|
||||||
|
if actor, loadErr := h.Auth.LoadActor(claims.ID); loadErr == nil {
|
||||||
|
isStaff = actor.IsStaff()
|
||||||
|
canOverseeChat = service.CanOverseeChat(actor.Role)
|
||||||
|
}
|
||||||
|
|
||||||
|
client := realtime.NewClient(
|
||||||
|
h.Hub,
|
||||||
|
conn,
|
||||||
|
claims.ID,
|
||||||
|
isStaff,
|
||||||
|
func() bool {
|
||||||
|
_, verr := h.Auth.ValidateClaims(claims)
|
||||||
|
return verr == nil
|
||||||
|
},
|
||||||
|
func() { h.Auth.TouchLastSeen(claims.ID) },
|
||||||
|
// 动态房间订阅鉴权:成员可订阅;站长/超管旁路可订阅任意群
|
||||||
|
func(room string) bool {
|
||||||
|
roomID, ok := parseWSChatRoom(room)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if canOverseeChat {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
_, err := h.Chat.Membership(roomID, claims.ID)
|
||||||
|
return err == nil
|
||||||
|
},
|
||||||
|
)
|
||||||
|
client.Serve(func(cl *realtime.Client) {
|
||||||
|
// hello 帧:全员带 user_id/ts;staff 额外带在线用户快照用于校正绿点
|
||||||
|
data := gin.H{
|
||||||
|
"user_id": claims.ID,
|
||||||
|
"ts": time.Now().Unix(),
|
||||||
|
}
|
||||||
|
if isStaff {
|
||||||
|
data["online_user_ids"] = h.Hub.OnlineUserIDs()
|
||||||
|
}
|
||||||
|
cl.Send(realtime.Envelope{Type: realtime.EventHello, Data: data})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkWSOrigin 校验握手 Origin:
|
||||||
|
// - 无 Origin(非浏览器/native 客户端)放行
|
||||||
|
// - dev:允许 localhost / 127.0.0.1 任意端口(前端 :3000 直连后端 :3001)
|
||||||
|
// - 生产:Origin 主机必须与请求 Host 同源
|
||||||
|
func (h *Handlers) checkWSOrigin(r *http.Request) bool {
|
||||||
|
origin := r.Header.Get("Origin")
|
||||||
|
if origin == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
u, err := url.Parse(origin)
|
||||||
|
if err != nil || u.Scheme != "http" && u.Scheme != "https" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if h.Cfg.DevMode {
|
||||||
|
host := u.Hostname()
|
||||||
|
return host == "localhost" || host == "127.0.0.1"
|
||||||
|
}
|
||||||
|
return u.Host == r.Host
|
||||||
|
}
|
||||||
@@ -3,7 +3,9 @@ package handler
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/freefire/jiang13-bbs/realtime"
|
||||||
"github.com/freefire/jiang13-bbs/service"
|
"github.com/freefire/jiang13-bbs/service"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -40,5 +42,11 @@ func (h *Handlers) UpdateSettings(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存站点设置失败"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存站点设置失败"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"ok": true, "accent": req.Accent})
|
// 归一化后的值实时广播:所有在线客户端立即热换肤,无需 F5 或等轮询
|
||||||
|
saved := strings.ToLower(strings.TrimSpace(req.Accent))
|
||||||
|
h.Hub.BroadcastAll(realtime.Envelope{
|
||||||
|
Type: realtime.EventSettingsChanged,
|
||||||
|
Data: map[string]string{"accent": saved},
|
||||||
|
})
|
||||||
|
c.JSON(http.StatusOK, gin.H{"ok": true, "accent": saved})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"github.com/freefire/jiang13-bbs/middleware"
|
"github.com/freefire/jiang13-bbs/middleware"
|
||||||
"github.com/freefire/jiang13-bbs/model"
|
"github.com/freefire/jiang13-bbs/model"
|
||||||
|
"github.com/freefire/jiang13-bbs/service"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -62,18 +63,27 @@ func (h *Handlers) UserProfile(c *gin.Context) {
|
|||||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||||
|
|
||||||
posts, postsTotal, err := h.Post.ListByUser(user.ID, page, size)
|
var viewerID uint
|
||||||
|
var actor *service.Actor
|
||||||
|
if claims := middleware.CurrentUser(c); claims != nil {
|
||||||
|
viewerID = claims.ID
|
||||||
|
if a, err := h.Auth.LoadActor(claims.ID); err == nil {
|
||||||
|
actor = a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
posts, postsTotal, err := h.Post.ListByUser(user.ID, viewerID, actor, page, size)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 填充点赞状态(仅登录用户)
|
// 填充点赞状态(仅登录用户)
|
||||||
if claims := middleware.CurrentUser(c); claims != nil {
|
if viewerID > 0 {
|
||||||
ids := make([]uint, 0, len(posts))
|
ids := make([]uint, 0, len(posts))
|
||||||
for _, p := range posts {
|
for _, p := range posts {
|
||||||
ids = append(ids, p.ID)
|
ids = append(ids, p.ID)
|
||||||
}
|
}
|
||||||
likedMap := h.Like.BatchHasLiked(ids, claims.ID)
|
likedMap := h.Like.BatchHasLiked(ids, viewerID)
|
||||||
for i := range posts {
|
for i := range posts {
|
||||||
posts[i].Liked = likedMap[posts[i].ID]
|
posts[i].Liked = likedMap[posts[i].ID]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package model
|
|||||||
import (
|
import (
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
@@ -29,9 +30,15 @@ func InitDB(dsn string) error {
|
|||||||
return fmt.Errorf("refresh token 旧数据迁移失败: %w", err)
|
return fmt.Errorf("refresh token 旧数据迁移失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 清理前次失败迁移遗留的 FK 约束(constraint:- 标签防止新建,但不删旧的)
|
||||||
|
if err := dropStaleChatFKConstraints(db); err != nil {
|
||||||
|
return fmt.Errorf("清理遗留 FK 约束失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
if err := db.AutoMigrate(
|
if err := db.AutoMigrate(
|
||||||
&User{}, &Board{}, &Post{}, &Comment{}, &RefreshToken{}, &Like{}, &Notification{}, &Checkin{},
|
&User{}, &Board{}, &Post{}, &Comment{}, &RefreshToken{}, &Like{}, &Notification{}, &Checkin{},
|
||||||
&Announcement{}, &SiteSetting{}, &Attachment{}, &UserBoard{}, &LoginLog{},
|
&Announcement{}, &SiteSetting{}, &Attachment{}, &UserBoard{}, &LoginLog{},
|
||||||
|
&ChatRoom{}, &ChatRoomMember{}, &ChatMessage{},
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return fmt.Errorf("自动迁移失败: %w", err)
|
return fmt.Errorf("自动迁移失败: %w", err)
|
||||||
}
|
}
|
||||||
@@ -54,7 +61,20 @@ func InitDB(dsn string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
DB = db
|
DB = db
|
||||||
|
if err := db.Exec(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_chat_direct_key
|
||||||
|
ON chat_rooms (direct_key)
|
||||||
|
WHERE room_type = 'direct' AND deleted_at IS NULL AND direct_key <> ''
|
||||||
|
`).Error; err != nil {
|
||||||
|
return fmt.Errorf("私聊唯一索引创建失败: %w", err)
|
||||||
|
}
|
||||||
seedDefaultBoards(db)
|
seedDefaultBoards(db)
|
||||||
|
if err := seedDefaultChatRoom(db); err != nil {
|
||||||
|
return fmt.Errorf("默认群聊大厅初始化失败: %w", err)
|
||||||
|
}
|
||||||
|
if err := ensureDefaultChatMemberships(db); err != nil {
|
||||||
|
return fmt.Errorf("默认群聊入群补齐失败: %w", err)
|
||||||
|
}
|
||||||
log.Println("[model] PostgreSQL 数据库初始化完成")
|
log.Println("[model] PostgreSQL 数据库初始化完成")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -71,6 +91,22 @@ func PingDB() error {
|
|||||||
return sqlDB.Ping()
|
return sqlDB.Ping()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dropStaleChatFKConstraints 清理前次迁移失败遗留的 FK 约束。
|
||||||
|
// GORM AutoMigrate 先建表再加约束:首次迁移时 Notification.Room 的 FK 添加失败,
|
||||||
|
// 但 chat_rooms 表已建好且带 fk_chat_rooms_last_message 约束。
|
||||||
|
// 模型已改用 constraint:- 防止新建,但 GORM 不会删除已存在的约束,需手动清理。
|
||||||
|
func dropStaleChatFKConstraints(db *gorm.DB) error {
|
||||||
|
// 对每个遗留约束名,在可能的两张表上都尝试删除(IF EXISTS 保证幂等)
|
||||||
|
pairs := []struct{ table, constraint string }{
|
||||||
|
{"chat_rooms", "fk_chat_rooms_last_message"},
|
||||||
|
{"notifications", "fk_notifications_room"},
|
||||||
|
}
|
||||||
|
for _, p := range pairs {
|
||||||
|
db.Exec(fmt.Sprintf(`ALTER TABLE IF EXISTS %s DROP CONSTRAINT IF EXISTS %s`, p.table, p.constraint))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// prepareRefreshTokenMigration 旧版 refresh_tokens 表把明文存在 token 列,
|
// prepareRefreshTokenMigration 旧版 refresh_tokens 表把明文存在 token 列,
|
||||||
// 新版改为 token_hash(SHA-256,NOT NULL+唯一索引)。在 AutoMigrate 之前:
|
// 新版改为 token_hash(SHA-256,NOT NULL+唯一索引)。在 AutoMigrate 之前:
|
||||||
// 1. 新增可带默认值的 token_hash 列(避免对存量行加 NOT NULL 列失败)
|
// 1. 新增可带默认值的 token_hash 列(避免对存量行加 NOT NULL 列失败)
|
||||||
@@ -193,3 +229,92 @@ func seedDefaultBoards(db *gorm.DB) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seedDefaultChatRoom 确保存在唯一的全站大厅(公开默认群)
|
||||||
|
func seedDefaultChatRoom(db *gorm.DB) error {
|
||||||
|
var n int64
|
||||||
|
if err := db.Model(&ChatRoom{}).Where("is_default = ?", true).Count(&n).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var owner User
|
||||||
|
if err := db.Where("role = ?", RoleOwner).Order("id ASC").First(&owner).Error; err != nil {
|
||||||
|
// 尚无用户时跳过,等有站长后再由下次启动补齐
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// 尝试任意用户
|
||||||
|
if err2 := db.Order("id ASC").First(&owner).Error; err2 != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
room := ChatRoom{
|
||||||
|
Name: "全站大厅",
|
||||||
|
Description: "所有成员默认加入的公开群聊",
|
||||||
|
OwnerID: owner.ID,
|
||||||
|
RoomType: ChatRoomTypeGroup,
|
||||||
|
IsPrivate: false,
|
||||||
|
IsDefault: true,
|
||||||
|
MemberCount: 0,
|
||||||
|
}
|
||||||
|
if err := db.Create(&room).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
log.Println("[model] 已创建默认群聊「全站大厅」")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureDefaultChatMemberships 把未封禁用户补进默认大厅(幂等)
|
||||||
|
func ensureDefaultChatMemberships(db *gorm.DB) error {
|
||||||
|
var room ChatRoom
|
||||||
|
if err := db.Where("is_default = ?", true).First(&room).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var userIDs []uint
|
||||||
|
if err := db.Model(&User{}).
|
||||||
|
Where("deleted_at IS NULL AND banned = ?", false).
|
||||||
|
Pluck("id", &userIDs).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(userIDs) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var existing []uint
|
||||||
|
if err := db.Model(&ChatRoomMember{}).
|
||||||
|
Where("room_id = ?", room.ID).
|
||||||
|
Pluck("user_id", &existing).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
have := make(map[uint]struct{}, len(existing))
|
||||||
|
for _, id := range existing {
|
||||||
|
have[id] = struct{}{}
|
||||||
|
}
|
||||||
|
added := 0
|
||||||
|
for _, uid := range userIDs {
|
||||||
|
if _, ok := have[uid]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
role := ChatRoleMember
|
||||||
|
if uid == room.OwnerID {
|
||||||
|
role = ChatRoleOwner
|
||||||
|
}
|
||||||
|
m := ChatRoomMember{RoomID: room.ID, UserID: uid, Role: role}
|
||||||
|
if err := db.Create(&m).Error; err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
added++
|
||||||
|
}
|
||||||
|
if added > 0 {
|
||||||
|
_ = db.Model(&ChatRoom{}).Where("id = ?", room.ID).
|
||||||
|
UpdateColumn("member_count", gorm.Expr(
|
||||||
|
"(SELECT count(*) FROM chat_room_members WHERE room_id = ?)", room.ID,
|
||||||
|
)).Error
|
||||||
|
log.Printf("[model] 默认群聊补齐入群 %d 人", added)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -169,27 +169,32 @@ type Checkin struct {
|
|||||||
|
|
||||||
// 通知类型
|
// 通知类型
|
||||||
const (
|
const (
|
||||||
NotificationTypeComment = "comment" // 评论了你的帖子
|
NotificationTypeComment = "comment" // 评论了你的帖子
|
||||||
NotificationTypeReply = "reply" // 回复了你的评论
|
NotificationTypeReply = "reply" // 回复了你的评论
|
||||||
NotificationTypeLike = "like" // 点赞了你的帖子
|
NotificationTypeLike = "like" // 点赞了你的帖子
|
||||||
NotificationTypeApproved = "approved" // 内容审核通过
|
NotificationTypeApproved = "approved" // 内容审核通过
|
||||||
NotificationTypeRejected = "rejected" // 内容审核未通过
|
NotificationTypeRejected = "rejected" // 内容审核未通过
|
||||||
|
NotificationTypeMention = "mention" // 群聊中 @ 了你(PostID=0,用 RoomID/MessageID)
|
||||||
|
NotificationTypePendingReview = "pending_review" // 有新内容待审核(发给可审者)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Notification 站内通知
|
// Notification 站内通知
|
||||||
type Notification struct {
|
type Notification struct {
|
||||||
ID uint `gorm:"primaryKey" json:"id"`
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
UserID uint `gorm:"index;not null" json:"user_id"` // 接收通知的用户
|
UserID uint `gorm:"index;not null" json:"user_id"` // 接收通知的用户
|
||||||
ActorID uint `gorm:"not null" json:"actor_id"` // 触发通知的用户
|
ActorID uint `gorm:"not null" json:"actor_id"` // 触发通知的用户
|
||||||
Type string `gorm:"size:16;not null;index" json:"type"` // comment | like
|
Type string `gorm:"size:16;not null;index" json:"type"` // comment | like | mention ...
|
||||||
PostID uint `gorm:"index;not null" json:"post_id"` // 关联帖子
|
PostID uint `gorm:"index;not null;default:0" json:"post_id"` // 关联帖子(mention 类为 0)
|
||||||
CommentID uint `gorm:"index" json:"comment_id"` // 关联评论(点赞时为 0)
|
CommentID uint `gorm:"index" json:"comment_id"` // 关联评论(点赞时为 0)
|
||||||
Content string `gorm:"size:256" json:"content"` // 内容预览
|
RoomID uint `gorm:"index;not null;default:0" json:"room_id"` // 关联群聊(mention)
|
||||||
|
MessageID uint `gorm:"not null;default:0" json:"message_id"` // 关联群聊消息(mention)
|
||||||
|
Content string `gorm:"size:256" json:"content"` // 内容预览
|
||||||
IsRead bool `gorm:"default:false;index" json:"is_read"`
|
IsRead bool `gorm:"default:false;index" json:"is_read"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
|
||||||
Actor User `gorm:"foreignKey:ActorID" json:"actor,omitempty"`
|
Actor User `gorm:"foreignKey:ActorID" json:"actor,omitempty"`
|
||||||
Post Post `gorm:"foreignKey:PostID" json:"post,omitempty"`
|
Post Post `gorm:"foreignKey:PostID" json:"post,omitempty"`
|
||||||
|
Room *ChatRoom `gorm:"foreignKey:RoomID;constraint:-" json:"room,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Announcement 站点公告(后台文章管理:支持草稿、标签与标签预设色)
|
// Announcement 站点公告(后台文章管理:支持草稿、标签与标签预设色)
|
||||||
@@ -252,3 +257,66 @@ type LoginLog struct {
|
|||||||
Success bool `gorm:"index;not null;default:false" json:"success"`
|
Success bool `gorm:"index;not null;default:false" json:"success"`
|
||||||
CreatedAt time.Time `gorm:"index" json:"created_at"`
|
CreatedAt time.Time `gorm:"index" json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 群聊成员角色
|
||||||
|
const (
|
||||||
|
ChatRoleOwner = "owner" // 群主(建群者,每群唯一):改名/解散/踢人/禁言
|
||||||
|
ChatRoleMember = "member" // 普通成员
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatRoom 会话房间:群聊或一对一私聊(RoomType);IsDefault 为全站大厅
|
||||||
|
type ChatRoom struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
Name string `gorm:"size:64;not null;default:''" json:"name"`
|
||||||
|
Description string `gorm:"size:256;not null;default:''" json:"description"`
|
||||||
|
OwnerID uint `gorm:"index;not null" json:"owner_id"`
|
||||||
|
RoomType string `gorm:"size:16;not null;default:group;index" json:"room_type"` // group | direct
|
||||||
|
DirectKey string `gorm:"size:64;not null;default:'';index" json:"-"` // 私聊双方 ID 排序键 "min:max"
|
||||||
|
IsPrivate bool `gorm:"not null;default:false;index" json:"is_private"`
|
||||||
|
IsDefault bool `gorm:"not null;default:false;index" json:"is_default"`
|
||||||
|
MemberCount int `gorm:"not null;default:0" json:"member_count"`
|
||||||
|
LastMessageID uint `gorm:"index;not null;default:0" json:"last_message_id"` // 最后一条消息(列表排序/未读基准)
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||||
|
|
||||||
|
Owner User `gorm:"foreignKey:OwnerID" json:"owner,omitempty"`
|
||||||
|
LastMessage *ChatMessage `gorm:"foreignKey:LastMessageID;constraint:-" json:"last_message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
ChatRoomTypeGroup = "group"
|
||||||
|
ChatRoomTypeDirect = "direct"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatRoomMember 群成员(房间+用户联合唯一;LastReadMessageID 为未读对账水位)
|
||||||
|
type ChatRoomMember struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
RoomID uint `gorm:"uniqueIndex:idx_chat_member;index;not null" json:"room_id"`
|
||||||
|
UserID uint `gorm:"uniqueIndex:idx_chat_member;not null" json:"user_id"`
|
||||||
|
Role string `gorm:"size:16;not null;default:member" json:"role"`
|
||||||
|
LastReadMessageID uint `gorm:"not null;default:0" json:"last_read_message_id"`
|
||||||
|
Muted bool `gorm:"not null;default:false" json:"muted"` // 被群主禁言
|
||||||
|
PinnedAt *time.Time `json:"pinned_at,omitempty"` // 该用户个人置顶时间;大厅强制置顶不依赖此字段
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
|
||||||
|
User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatMessage 群聊消息(先落库再经 WS 广播,WS 不承担可靠投递;撤回保留行供审计)
|
||||||
|
type ChatMessage struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
RoomID uint `gorm:"index:idx_chat_room_created,priority:1;not null" json:"room_id"`
|
||||||
|
SenderID uint `gorm:"index;not null" json:"sender_id"`
|
||||||
|
Content string `gorm:"type:varchar(2000);not null" json:"content"`
|
||||||
|
ReplyToID uint `gorm:"not null;default:0;index" json:"reply_to_id"` // 引用的消息 ID,0 表示无引用
|
||||||
|
ReplySnap string `gorm:"size:512;not null;default:''" json:"reply_snap"` // 引用快照「昵称: 摘要」,原文撤回后仍可展示
|
||||||
|
MentionIDs string `gorm:"size:512;not null;default:''" json:"-"` // 被@用户 ID 逗号分隔(落通知用)
|
||||||
|
RecalledAt *time.Time `json:"recalled_at,omitempty"`
|
||||||
|
RecalledBy uint `gorm:"not null;default:0" json:"recalled_by"`
|
||||||
|
CreatedAt time.Time `gorm:"index:idx_chat_room_created,priority:2" json:"created_at"`
|
||||||
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||||
|
|
||||||
|
Sender User `gorm:"foreignKey:SenderID" json:"sender,omitempty"`
|
||||||
|
}
|
||||||
|
|||||||
206
backend/realtime/client.go
Normal file
206
backend/realtime/client.go
Normal file
@@ -0,0 +1,206 @@
|
|||||||
|
package realtime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json/v2"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
func uintToString(n uint) string {
|
||||||
|
return strconv.FormatUint(uint64(n), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
// writeWait 单次写帧超时
|
||||||
|
writeWait = 10 * time.Second
|
||||||
|
// pongWait 无 Pong 超时:浏览器自动响应协议层 Ping,超时即判定断连
|
||||||
|
pongWait = 70 * time.Second
|
||||||
|
// pingPeriod 协议层 Ping 周期(须小于 pongWait)
|
||||||
|
pingPeriod = 30 * time.Second
|
||||||
|
// maxMessageSize 仅接收应用层心跳,限制 4KiB 足够
|
||||||
|
maxMessageSize = 4 << 10
|
||||||
|
// sendBufferSize 慢消费保护阈值
|
||||||
|
sendBufferSize = 32
|
||||||
|
// CloseAuthInvalid 鉴权失效(封禁/强制下线)自定义关闭码,前端不自动重连
|
||||||
|
CloseAuthInvalid = 4401
|
||||||
|
)
|
||||||
|
|
||||||
|
// Client 一条 WebSocket 连接
|
||||||
|
type Client struct {
|
||||||
|
hub *Hub
|
||||||
|
conn *websocket.Conn
|
||||||
|
userID uint
|
||||||
|
// staff 建连时按 DB 实时 Actor 判定,决定是否加入管理团队房间
|
||||||
|
staff bool
|
||||||
|
// validate 应用层心跳时复查 token_version / 封禁状态,失效则立即断连
|
||||||
|
validate func() bool
|
||||||
|
// onHeartbeat 心跳顺带刷新 last_seen_at(SQL 60s 限频),
|
||||||
|
// 让只挂着 WS、不发 HTTP 请求的标签页也保持在线统计准确
|
||||||
|
onHeartbeat func()
|
||||||
|
// authorizeRoom 客户端动态订阅房间前的业务鉴权(如校验群成员身份);
|
||||||
|
// 仅 "chat:" 前缀房间允许订阅,user:/staff 等内部房间禁止
|
||||||
|
authorizeRoom func(room string) bool
|
||||||
|
|
||||||
|
send chan []byte
|
||||||
|
rooms map[string]struct{}
|
||||||
|
closed atomic.Bool
|
||||||
|
closeCh chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewClient(
|
||||||
|
hub *Hub,
|
||||||
|
conn *websocket.Conn,
|
||||||
|
userID uint,
|
||||||
|
staff bool,
|
||||||
|
validate func() bool,
|
||||||
|
onHeartbeat func(),
|
||||||
|
authorizeRoom func(room string) bool,
|
||||||
|
) *Client {
|
||||||
|
return &Client{
|
||||||
|
hub: hub,
|
||||||
|
conn: conn,
|
||||||
|
userID: userID,
|
||||||
|
staff: staff,
|
||||||
|
validate: validate,
|
||||||
|
onHeartbeat: onHeartbeat,
|
||||||
|
authorizeRoom: authorizeRoom,
|
||||||
|
send: make(chan []byte, sendBufferSize),
|
||||||
|
rooms: make(map[string]struct{}),
|
||||||
|
closeCh: make(chan struct{}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve 注册到 Hub 后阻塞运行读写泵,断开时注销(调用方在升级成功后调用一次)。
|
||||||
|
func (c *Client) Serve(sendHello func(*Client)) {
|
||||||
|
cameOnline := c.hub.register(c)
|
||||||
|
sendHello(c)
|
||||||
|
if cameOnline {
|
||||||
|
c.hub.BroadcastPresence(c.userID, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
go c.writePump()
|
||||||
|
c.readPump() // 阻塞至断连
|
||||||
|
|
||||||
|
wentOffline := c.hub.unregister(c)
|
||||||
|
c.forceClose()
|
||||||
|
if wentOffline {
|
||||||
|
c.hub.BroadcastPresence(c.userID, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// forceClose 幂等关闭连接并触发 closeCh
|
||||||
|
func (c *Client) forceClose() {
|
||||||
|
if c.closed.CompareAndSwap(false, true) {
|
||||||
|
_ = c.conn.Close()
|
||||||
|
close(c.closeCh)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// clientInbound 浏览器→服务端帧:ping 心跳;join/leave 动态订阅/退订房间
|
||||||
|
type clientInbound struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Room string `json:"room,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// readPump 单读泵:Pong 续期 + 应用层心跳鉴权复查 + 房间订阅
|
||||||
|
func (c *Client) readPump() {
|
||||||
|
c.conn.SetReadLimit(maxMessageSize)
|
||||||
|
_ = c.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||||
|
c.conn.SetPongHandler(func(string) error {
|
||||||
|
return c.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||||
|
})
|
||||||
|
|
||||||
|
for {
|
||||||
|
_, raw, err := c.conn.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var msg clientInbound
|
||||||
|
if err := json.Unmarshal(raw, &msg); err != nil {
|
||||||
|
continue // 非法帧忽略,不踢连接
|
||||||
|
}
|
||||||
|
switch msg.Type {
|
||||||
|
case "ping":
|
||||||
|
// 心跳鉴权复查:被封禁/改密/降级强制下线后 ~25s 内断开
|
||||||
|
if c.validate != nil && !c.validate() {
|
||||||
|
_ = c.conn.WriteControl(
|
||||||
|
websocket.CloseMessage,
|
||||||
|
websocket.FormatCloseMessage(CloseAuthInvalid, "auth invalid"),
|
||||||
|
time.Now().Add(writeWait),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if c.onHeartbeat != nil {
|
||||||
|
c.onHeartbeat()
|
||||||
|
}
|
||||||
|
c.enqueueMustMarshal(Envelope{Type: EventPong, Data: map[string]int64{
|
||||||
|
"ts": time.Now().Unix(),
|
||||||
|
}})
|
||||||
|
case "join", "leave":
|
||||||
|
c.handleRoomFrame(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleRoomFrame 处理房间订阅:只允许 chat:{id},且实时校验调用方业务身份
|
||||||
|
func (c *Client) handleRoomFrame(msg clientInbound) {
|
||||||
|
room := msg.Room
|
||||||
|
if room == "" || len(room) > 32 || !strings.HasPrefix(room, "chat:") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
idStr := strings.TrimPrefix(room, "chat:")
|
||||||
|
roomID, err := strconv.ParseUint(idStr, 10, 64)
|
||||||
|
if err != nil || roomID == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if c.authorizeRoom != nil && !c.authorizeRoom(room) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if msg.Type == "join" {
|
||||||
|
c.hub.JoinClientRoom(c, room)
|
||||||
|
} else {
|
||||||
|
c.hub.LeaveClientRoom(c, room)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// writePump 单写泵:唯一持有连接写权限;协议层 Ping + 业务帧都从这里发出
|
||||||
|
func (c *Client) writePump() {
|
||||||
|
ticker := time.NewTicker(pingPeriod)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case payload := <-c.send:
|
||||||
|
_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||||
|
if err := c.conn.WriteMessage(websocket.TextMessage, payload); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case <-ticker.C:
|
||||||
|
_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||||
|
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case <-c.closeCh:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send 业务帧入队(由唯一 writePump 发出);连接已关闭时静默丢弃
|
||||||
|
func (c *Client) Send(env Envelope) {
|
||||||
|
c.enqueueMustMarshal(env)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) enqueueMustMarshal(env Envelope) {
|
||||||
|
payload, err := json.Marshal(env)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case c.send <- payload:
|
||||||
|
case <-c.closeCh:
|
||||||
|
}
|
||||||
|
}
|
||||||
233
backend/realtime/hub.go
Normal file
233
backend/realtime/hub.go
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
// Package realtime 全站实时通信总线(一期)。
|
||||||
|
//
|
||||||
|
// 设计:
|
||||||
|
// - 单条 WebSocket 连接(GET /api/ws,cookie 鉴权)复用承载所有实时事件,
|
||||||
|
// 后续群聊、通知、审核角标等都接入本 Hub,而不是各开连接。
|
||||||
|
// - Hub 维护连接表、房间(主题订阅)表与每用户连接计数;房间用于定向广播
|
||||||
|
// (user:{id} 个人房间、staff 管理团队房间)。
|
||||||
|
// - 所有写操作投递到 client.send 缓冲通道,由唯一的 writePump 消费,
|
||||||
|
// 杜绝多 goroutine 并发写 WebSocket。
|
||||||
|
// - 在线判定 = 拥有至少 1 条活跃 WS 连接,比 last_seen_at 5 分钟启发式精确;
|
||||||
|
// 上线/下线事件只推送给 staff 房间。
|
||||||
|
package realtime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json/v2"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 事件类型:前后端共享的单层 JSON 协议契约,禁止手拼 JSON / 双重编码
|
||||||
|
const (
|
||||||
|
EventHello = "hello" // 建连欢迎帧(含在线用户快照)
|
||||||
|
EventPong = "pong" // 应用层心跳应答
|
||||||
|
EventSettingsChanged = "settings:changed" // 站点设置(主题色)变更,全员广播
|
||||||
|
EventPresenceUpdate = "presence:update" // 用户上/下线,仅 staff 房间
|
||||||
|
EventChatMessage = "chat:message" // 群聊新消息,推 chat:{roomID}
|
||||||
|
EventChatMembership = "chat:membership" // 群成员关系变更(被踢/群解散/被邀请),推 user:{id}
|
||||||
|
EventNotificationNew = "notification:new" // 新站内通知(如群聊 @),推 user:{id}
|
||||||
|
EventFeedChanged = "feed:changed" // 帖子流有公开新内容(三期),全员广播
|
||||||
|
EventChatRecalled = "chat:message_recalled" // 消息撤回,推 chat:{roomID}
|
||||||
|
EventChatUnread = "chat:unread" // 未读增量,推 user:{id}(未订阅房间也能实时角标)
|
||||||
|
EventModerationChanged = "moderation:changed" // 待审队列变化,推 staff 房间(客户端各自 HTTP 校准角标)
|
||||||
|
)
|
||||||
|
|
||||||
|
// RoomStaff 管理团队房间(板块管理员及以上)
|
||||||
|
const RoomStaff = "staff"
|
||||||
|
|
||||||
|
// RoomChat 群聊房间(仅群成员可通过 join 帧订阅)
|
||||||
|
func RoomChat(roomID uint) string {
|
||||||
|
return "chat:" + uintToString(roomID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func roomUser(userID uint) string {
|
||||||
|
return "user:" + uintToString(userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RoomUser 个人房间(导出供按用户定向推送)
|
||||||
|
func RoomUser(userID uint) string {
|
||||||
|
return roomUser(userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Envelope 实时消息统一信封
|
||||||
|
type Envelope struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Data interface{} `json:"data,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hub 连接与房间注册中心(单实例内存版;多实例时由 PG LISTEN/NOTIFY 桥接)
|
||||||
|
type Hub struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
// 全部活跃连接
|
||||||
|
clients map[*Client]struct{}
|
||||||
|
// 房间 -> 连接集合
|
||||||
|
rooms map[string]map[*Client]struct{}
|
||||||
|
// 用户 -> 活跃连接数(同一用户多标签页)
|
||||||
|
userConnCnt map[uint]int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHub() *Hub {
|
||||||
|
return &Hub{
|
||||||
|
clients: make(map[*Client]struct{}),
|
||||||
|
rooms: make(map[string]map[*Client]struct{}),
|
||||||
|
userConnCnt: make(map[uint]int),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// register 注册新连接。返回 cameOnline=true 表示该用户 0→1 首次上线。
|
||||||
|
func (h *Hub) register(c *Client) (cameOnline bool) {
|
||||||
|
h.mu.Lock()
|
||||||
|
h.clients[c] = struct{}{}
|
||||||
|
n := h.userConnCnt[c.userID]
|
||||||
|
h.userConnCnt[c.userID] = n + 1
|
||||||
|
h.joinLocked(c, roomUser(c.userID))
|
||||||
|
if c.staff {
|
||||||
|
h.joinLocked(c, RoomStaff)
|
||||||
|
}
|
||||||
|
h.mu.Unlock()
|
||||||
|
return n == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// unregister 注销连接,返回 wentOffline=true 表示该用户最后一条连接断开。
|
||||||
|
func (h *Hub) unregister(c *Client) (wentOffline bool) {
|
||||||
|
h.mu.Lock()
|
||||||
|
if _, ok := h.clients[c]; !ok {
|
||||||
|
h.mu.Unlock()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
delete(h.clients, c)
|
||||||
|
for room := range c.rooms {
|
||||||
|
h.leaveLocked(c, room)
|
||||||
|
}
|
||||||
|
clear(c.rooms)
|
||||||
|
n := h.userConnCnt[c.userID] - 1
|
||||||
|
if n <= 0 {
|
||||||
|
delete(h.userConnCnt, c.userID)
|
||||||
|
wentOffline = true
|
||||||
|
} else {
|
||||||
|
h.userConnCnt[c.userID] = n
|
||||||
|
}
|
||||||
|
h.mu.Unlock()
|
||||||
|
return wentOffline
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hub) joinLocked(c *Client, room string) {
|
||||||
|
m := h.rooms[room]
|
||||||
|
if m == nil {
|
||||||
|
m = make(map[*Client]struct{})
|
||||||
|
h.rooms[room] = m
|
||||||
|
}
|
||||||
|
m[c] = struct{}{}
|
||||||
|
c.rooms[room] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hub) leaveLocked(c *Client, room string) {
|
||||||
|
if m := h.rooms[room]; m != nil {
|
||||||
|
delete(m, c)
|
||||||
|
if len(m) == 0 {
|
||||||
|
delete(h.rooms, room)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delete(c.rooms, room)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BroadcastAll 向全部连接广播
|
||||||
|
func (h *Hub) BroadcastAll(env Envelope) {
|
||||||
|
h.mu.RLock()
|
||||||
|
clients := make([]*Client, 0, len(h.clients))
|
||||||
|
for c := range h.clients {
|
||||||
|
clients = append(clients, c)
|
||||||
|
}
|
||||||
|
h.mu.RUnlock()
|
||||||
|
h.dispatch(clients, env)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BroadcastRoom 向指定房间广播
|
||||||
|
func (h *Hub) BroadcastRoom(room string, env Envelope) {
|
||||||
|
h.mu.RLock()
|
||||||
|
m := h.rooms[room]
|
||||||
|
clients := make([]*Client, 0, len(m))
|
||||||
|
for c := range m {
|
||||||
|
clients = append(clients, c)
|
||||||
|
}
|
||||||
|
h.mu.RUnlock()
|
||||||
|
h.dispatch(clients, env)
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinClientRoom 连接动态加入房间(群聊订阅;调用方必须先完成成员鉴权)。
|
||||||
|
// 返回 false 表示连接已注销。
|
||||||
|
func (h *Hub) JoinClientRoom(c *Client, room string) bool {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
if _, ok := h.clients[c]; !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
h.joinLocked(c, room)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// LeaveClientRoom 连接动态离开房间
|
||||||
|
func (h *Hub) LeaveClientRoom(c *Client, room string) {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
h.leaveLocked(c, room)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveUserRoom 把某用户的全部活跃连接移出房间(群主踢人后立即停止实时投递)
|
||||||
|
func (h *Hub) RemoveUserRoom(userID uint, room string) {
|
||||||
|
h.mu.Lock()
|
||||||
|
var targets []*Client
|
||||||
|
for c := range h.rooms[room] {
|
||||||
|
if c.userID == userID {
|
||||||
|
targets = append(targets, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range targets {
|
||||||
|
h.leaveLocked(c, room)
|
||||||
|
}
|
||||||
|
h.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// BroadcastUser 向某用户的全部活跃连接(多标签页)单播
|
||||||
|
func (h *Hub) BroadcastUser(userID uint, env Envelope) {
|
||||||
|
h.BroadcastRoom(roomUser(userID), env)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BroadcastPresence 上/下线事件推送给管理团队
|
||||||
|
func (h *Hub) BroadcastPresence(userID uint, online bool) {
|
||||||
|
h.BroadcastRoom(RoomStaff, Envelope{
|
||||||
|
Type: EventPresenceUpdate,
|
||||||
|
Data: map[string]interface{}{
|
||||||
|
"user_id": userID,
|
||||||
|
"online": online,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// OnlineUserIDs 当前在线用户快照(供 staff 建连时校正绿点)
|
||||||
|
func (h *Hub) OnlineUserIDs() []uint {
|
||||||
|
h.mu.RLock()
|
||||||
|
defer h.mu.RUnlock()
|
||||||
|
ids := make([]uint, 0, len(h.userConnCnt))
|
||||||
|
for id := range h.userConnCnt {
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hub) dispatch(clients []*Client, env Envelope) {
|
||||||
|
if len(clients) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
payload, err := json.Marshal(env)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, c := range clients {
|
||||||
|
select {
|
||||||
|
case c.send <- payload:
|
||||||
|
default:
|
||||||
|
// 慢消费者:缓冲已满直接关闭连接,等客户端指数退避重连补齐
|
||||||
|
c.forceClose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"github.com/freefire/jiang13-bbs/handler"
|
"github.com/freefire/jiang13-bbs/handler"
|
||||||
"github.com/freefire/jiang13-bbs/middleware"
|
"github.com/freefire/jiang13-bbs/middleware"
|
||||||
"github.com/freefire/jiang13-bbs/model"
|
"github.com/freefire/jiang13-bbs/model"
|
||||||
|
"github.com/freefire/jiang13-bbs/realtime"
|
||||||
"github.com/freefire/jiang13-bbs/service"
|
"github.com/freefire/jiang13-bbs/service"
|
||||||
"github.com/gin-contrib/cors"
|
"github.com/gin-contrib/cors"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -51,6 +52,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
settingSvc := service.NewSettingService(model.DB)
|
settingSvc := service.NewSettingService(model.DB)
|
||||||
adminUserSvc := service.NewAdminUserService(model.DB)
|
adminUserSvc := service.NewAdminUserService(model.DB)
|
||||||
moderationSvc := service.NewModerationService(model.DB, notifSvc)
|
moderationSvc := service.NewModerationService(model.DB, notifSvc)
|
||||||
|
chatSvc := service.NewChatService(model.DB, notifSvc)
|
||||||
if err := uploadSvc.EnsureDir(); err != nil {
|
if err := uploadSvc.EnsureDir(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -58,6 +60,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
|
|
||||||
h := &handler.Handlers{
|
h := &handler.Handlers{
|
||||||
Cfg: cfg,
|
Cfg: cfg,
|
||||||
|
Hub: realtime.NewHub(),
|
||||||
Auth: authSvc,
|
Auth: authSvc,
|
||||||
Board: boardSvc,
|
Board: boardSvc,
|
||||||
Post: postSvc,
|
Post: postSvc,
|
||||||
@@ -71,6 +74,16 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
Setting: settingSvc,
|
Setting: settingSvc,
|
||||||
AdminUser: adminUserSvc,
|
AdminUser: adminUserSvc,
|
||||||
Moderation: moderationSvc,
|
Moderation: moderationSvc,
|
||||||
|
Chat: chatSvc,
|
||||||
|
}
|
||||||
|
// 通知落库后统一推 WS 红点(点赞/评论/审核/@ 等共用)
|
||||||
|
notifSvc.OnNotifyNew = func(userID uint) {
|
||||||
|
if h.Hub == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.Hub.BroadcastUser(userID, realtime.Envelope{
|
||||||
|
Type: realtime.EventNotificationNew,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
authMW := middleware.NewAuthMiddleware(authSvc)
|
authMW := middleware.NewAuthMiddleware(authSvc)
|
||||||
@@ -83,6 +96,9 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
r.GET("/robots.txt", h.RobotsTxt)
|
r.GET("/robots.txt", h.RobotsTxt)
|
||||||
r.GET("/sitemap.xml", h.SitemapXML)
|
r.GET("/sitemap.xml", h.SitemapXML)
|
||||||
|
|
||||||
|
// 实时通信总线(WebSocket,cookie 鉴权 + Origin 校验,处理器内部完成鉴权升级)
|
||||||
|
r.GET("/api/ws", h.RealtimeWS)
|
||||||
|
|
||||||
// 公开 API(可选登录)
|
// 公开 API(可选登录)
|
||||||
pubAPI := r.Group("/api", authMW.OptionalAuth())
|
pubAPI := r.Group("/api", authMW.OptionalAuth())
|
||||||
{
|
{
|
||||||
@@ -131,6 +147,26 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
api.PUT("/avatar/use", h.UseAvatar)
|
api.PUT("/avatar/use", h.UseAvatar)
|
||||||
api.GET("/my/media", h.MyMedia)
|
api.GET("/my/media", h.MyMedia)
|
||||||
api.DELETE("/my/attachments/:id", h.DeleteAttachment)
|
api.DELETE("/my/attachments/:id", h.DeleteAttachment)
|
||||||
|
|
||||||
|
// 群聊(二期):建群/成员/消息/未读
|
||||||
|
api.GET("/chat/rooms", h.ListChatRooms)
|
||||||
|
api.POST("/chat/rooms", h.CreateChatRoom)
|
||||||
|
api.POST("/chat/direct", h.OpenDirectChat)
|
||||||
|
api.GET("/chat/users", h.SearchChatUsers)
|
||||||
|
api.GET("/chat/rooms/:id", h.GetChatRoom)
|
||||||
|
api.PUT("/chat/rooms/:id", h.UpdateChatRoom)
|
||||||
|
api.PUT("/chat/rooms/:id/pin", h.PinChatRoom)
|
||||||
|
api.DELETE("/chat/rooms/:id", h.DissolveChatRoom)
|
||||||
|
api.POST("/chat/rooms/:id/join", h.JoinChatRoom)
|
||||||
|
api.POST("/chat/rooms/:id/leave", h.LeaveChatRoom)
|
||||||
|
api.GET("/chat/rooms/:id/members", h.ListChatMembers)
|
||||||
|
api.POST("/chat/rooms/:id/members", h.InviteChatMembers)
|
||||||
|
api.DELETE("/chat/rooms/:id/members/:uid", h.KickChatMember)
|
||||||
|
api.GET("/chat/rooms/:id/messages", h.ListChatMessages)
|
||||||
|
api.POST("/chat/rooms/:id/messages", middleware.RateLimitMiddleware(limiter, service.RateChat), h.SendChatMessage)
|
||||||
|
api.DELETE("/chat/rooms/:id/messages/:mid", h.RecallChatMessage)
|
||||||
|
api.PUT("/chat/rooms/:id/read", h.MarkChatRead)
|
||||||
|
api.GET("/chat/unread-summary", h.ChatUnreadSummary)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 管理后台 API:RequireStaff 基础鉴权(板块管理员及以上,Actor 实时从 DB 现取),
|
// 管理后台 API:RequireStaff 基础鉴权(板块管理员及以上,Actor 实时从 DB 现取),
|
||||||
@@ -166,6 +202,11 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
usersAPI.PUT("/users/:id/role", h.AdminUpdateUserRole)
|
usersAPI.PUT("/users/:id/role", h.AdminUpdateUserRole)
|
||||||
usersAPI.PUT("/users/:id/ban", h.AdminSetUserBan)
|
usersAPI.PUT("/users/:id/ban", h.AdminSetUserBan)
|
||||||
usersAPI.GET("/users/:id/login-logs", h.AdminUserLoginLogs)
|
usersAPI.GET("/users/:id/login-logs", h.AdminUserLoginLogs)
|
||||||
|
// 站长内容档案(handler 内再校验 owner)
|
||||||
|
usersAPI.GET("/users/:id", h.AdminGetUserAudit)
|
||||||
|
usersAPI.GET("/users/:id/posts", h.AdminUserAuditPosts)
|
||||||
|
usersAPI.GET("/users/:id/comments", h.AdminUserAuditComments)
|
||||||
|
usersAPI.GET("/users/:id/messages", h.AdminUserAuditMessages)
|
||||||
}
|
}
|
||||||
|
|
||||||
r.NoRoute(func(c *gin.Context) {
|
r.NoRoute(func(c *gin.Context) {
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package service
|
package service
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/freefire/jiang13-bbs/model"
|
"github.com/freefire/jiang13-bbs/model"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -107,9 +109,53 @@ func (s *AuthService) GetUserBoardIDs(id uint) ([]uint, error) {
|
|||||||
|
|
||||||
// GetUserIDByUsername 按用户名查 ID(登录失败审计用),用户不存在返回 0
|
// GetUserIDByUsername 按用户名查 ID(登录失败审计用),用户不存在返回 0
|
||||||
func (s *AuthService) GetUserIDByUsername(username string) uint {
|
func (s *AuthService) GetUserIDByUsername(username string) uint {
|
||||||
|
username = strings.TrimSpace(username)
|
||||||
|
if username == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
var u model.User
|
var u model.User
|
||||||
if err := s.db.Select("id").Where("username = ?", username).First(&u).Error; err != nil {
|
if err := s.db.Select("id").Where("username = ?", username).First(&u).Error; err != nil {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
return u.ID
|
return u.ID
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListBoardModeratorIDs 可审核指定板块的用户 ID:
|
||||||
|
// 站长/超管/全站管理员 + 被授权该板的板块管理员(未封禁、未删除)
|
||||||
|
func (s *AuthService) ListBoardModeratorIDs(boardID uint) ([]uint, error) {
|
||||||
|
var ids []uint
|
||||||
|
// 全站可审:admin / super_admin / owner
|
||||||
|
if err := s.db.Model(&model.User{}).
|
||||||
|
Where("deleted_at IS NULL AND banned = ? AND role IN ?", false,
|
||||||
|
[]string{string(model.RoleAdmin), string(model.RoleSuperAdmin), string(model.RoleOwner)}).
|
||||||
|
Pluck("id", &ids).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// 板块管理员(授权该板)
|
||||||
|
var boardAdminIDs []uint
|
||||||
|
if err := s.db.Model(&model.UserBoard{}).
|
||||||
|
Select("user_boards.user_id").
|
||||||
|
Joins("JOIN users ON users.id = user_boards.user_id").
|
||||||
|
Where("user_boards.board_id = ? AND users.deleted_at IS NULL AND users.banned = ? AND users.role = ?",
|
||||||
|
boardID, false, string(model.RoleBoardAdmin)).
|
||||||
|
Pluck("user_boards.user_id", &boardAdminIDs).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
seen := make(map[uint]struct{}, len(ids)+len(boardAdminIDs))
|
||||||
|
out := make([]uint, 0, len(ids)+len(boardAdminIDs))
|
||||||
|
for _, id := range ids {
|
||||||
|
if _, ok := seen[id]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
out = append(out, id)
|
||||||
|
}
|
||||||
|
for _, id := range boardAdminIDs {
|
||||||
|
if _, ok := seen[id]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
out = append(out, id)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ var (
|
|||||||
ErrBoardRequired = errors.New("板块管理员至少需要授权一个板块")
|
ErrBoardRequired = errors.New("板块管理员至少需要授权一个板块")
|
||||||
// ErrBoardNotFound 授权的板块不存在
|
// ErrBoardNotFound 授权的板块不存在
|
||||||
ErrBoardNotFound = errors.New("部分板块不存在")
|
ErrBoardNotFound = errors.New("部分板块不存在")
|
||||||
|
// ErrOwnerOnly 仅站长可访问用户内容档案
|
||||||
|
ErrOwnerOnly = errors.New("仅站长可查看用户内容档案")
|
||||||
)
|
)
|
||||||
|
|
||||||
// onlineThreshold last_seen_at 在该窗口内视为在线
|
// onlineThreshold last_seen_at 在该窗口内视为在线
|
||||||
@@ -197,9 +199,10 @@ func (s *AdminUserService) toItems(users []model.User) []AdminUserItem {
|
|||||||
commentCounts := map[uint]int64{}
|
commentCounts := map[uint]int64{}
|
||||||
|
|
||||||
var postRows []countRow
|
var postRows []countRow
|
||||||
|
// 列表计数统一为「已发布」口径,与评论一致;全量含驳回/软删见内容档案
|
||||||
s.db.Model(&model.Post{}).
|
s.db.Model(&model.Post{}).
|
||||||
Select("user_id, COUNT(*) AS cnt").
|
Select("user_id, COUNT(*) AS cnt").
|
||||||
Where("user_id IN ?", ids).
|
Where("user_id IN ? AND status = ?", ids, model.ContentStatusPublished).
|
||||||
Group("user_id").Scan(&postRows)
|
Group("user_id").Scan(&postRows)
|
||||||
for _, r := range postRows {
|
for _, r := range postRows {
|
||||||
postCounts[r.UserID] = r.Cnt
|
postCounts[r.UserID] = r.Cnt
|
||||||
@@ -433,3 +436,240 @@ func invalidateUserSessions(tx *gorm.DB, userID uint) error {
|
|||||||
return tx.Model(&model.RefreshToken{}).Where("user_id = ? AND revoked = ?", userID, false).
|
return tx.Model(&model.RefreshToken{}).Where("user_id = ? AND revoked = ?", userID, false).
|
||||||
Updates(map[string]any{"revoked": true, "token_cipher": ""}).Error
|
Updates(map[string]any{"revoked": true, "token_cipher": ""}).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== 站长用户内容档案(仅 owner) =====
|
||||||
|
|
||||||
|
func requireOwnerActor(actor *Actor) error {
|
||||||
|
if actor == nil || actor.Role != model.RoleOwner {
|
||||||
|
return ErrOwnerOnly
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeAuditPage(page, size int) (int, int) {
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if size < 1 || size > 50 {
|
||||||
|
size = 20
|
||||||
|
}
|
||||||
|
return page, size
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminUserAuditProfile 站长查看用户档案摘要
|
||||||
|
type AdminUserAuditProfile struct {
|
||||||
|
User AdminUserItem `json:"user"`
|
||||||
|
PostsTotal int64 `json:"posts_total"` // 含各状态与软删
|
||||||
|
CommentsTotal int64 `json:"comments_total"` // 含各状态与软删
|
||||||
|
MessagesTotal int64 `json:"messages_total"` // 含撤回与软删
|
||||||
|
PublishedPosts int64 `json:"published_posts"`
|
||||||
|
PublishedComments int64 `json:"published_comments"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminAuditPostItem 审计帖子行
|
||||||
|
type AdminAuditPostItem struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
BoardID uint `json:"board_id"`
|
||||||
|
BoardName string `json:"board_name"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminAuditCommentItem 审计评论行
|
||||||
|
type AdminAuditCommentItem struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
PostID uint `json:"post_id"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminAuditMessageItem 审计聊天消息行
|
||||||
|
type AdminAuditMessageItem struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
RoomID uint `json:"room_id"`
|
||||||
|
RoomName string `json:"room_name"`
|
||||||
|
RoomType string `json:"room_type"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Recalled bool `json:"recalled"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAuditProfile 站长:用户摘要 + 全量计数
|
||||||
|
func (s *AdminUserService) GetAuditProfile(actor *Actor, userID uint) (*AdminUserAuditProfile, error) {
|
||||||
|
if err := requireOwnerActor(actor); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
item, err := s.getItem(s.db, userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := &AdminUserAuditProfile{User: *item}
|
||||||
|
s.db.Unscoped().Model(&model.Post{}).Where("user_id = ?", userID).Count(&out.PostsTotal)
|
||||||
|
s.db.Unscoped().Model(&model.Comment{}).Where("user_id = ?", userID).Count(&out.CommentsTotal)
|
||||||
|
s.db.Unscoped().Model(&model.ChatMessage{}).Where("sender_id = ?", userID).Count(&out.MessagesTotal)
|
||||||
|
s.db.Model(&model.Post{}).Where("user_id = ? AND status = ?", userID, model.ContentStatusPublished).Count(&out.PublishedPosts)
|
||||||
|
s.db.Model(&model.Comment{}).Where("user_id = ? AND status = ?", userID, model.ContentStatusPublished).Count(&out.PublishedComments)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListAuditPosts 站长:用户全部帖子(含软删)
|
||||||
|
func (s *AdminUserService) ListAuditPosts(actor *Actor, userID uint, page, size int) ([]AdminAuditPostItem, int64, int, error) {
|
||||||
|
if err := requireOwnerActor(actor); err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
page, size = normalizeAuditPage(page, size)
|
||||||
|
if err := s.db.First(&model.User{}, userID).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
q := s.db.Unscoped().Model(&model.Post{}).Where("user_id = ?", userID)
|
||||||
|
var total int64
|
||||||
|
if err := q.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
var posts []model.Post
|
||||||
|
if err := q.Preload("Board").Order("id DESC").
|
||||||
|
Offset((page - 1) * size).Limit(size).Find(&posts).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
items := make([]AdminAuditPostItem, 0, len(posts))
|
||||||
|
for _, p := range posts {
|
||||||
|
it := AdminAuditPostItem{
|
||||||
|
ID: p.ID,
|
||||||
|
Title: p.Title,
|
||||||
|
Content: truncateStr(p.Content, 240),
|
||||||
|
Status: p.Status,
|
||||||
|
BoardID: p.BoardID,
|
||||||
|
BoardName: p.Board.Name,
|
||||||
|
CreatedAt: p.CreatedAt,
|
||||||
|
}
|
||||||
|
if p.DeletedAt.Valid {
|
||||||
|
it.Deleted = true
|
||||||
|
t := p.DeletedAt.Time
|
||||||
|
it.DeletedAt = &t
|
||||||
|
}
|
||||||
|
items = append(items, it)
|
||||||
|
}
|
||||||
|
return items, total, page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListAuditComments 站长:用户全部评论(含软删)
|
||||||
|
func (s *AdminUserService) ListAuditComments(actor *Actor, userID uint, page, size int) ([]AdminAuditCommentItem, int64, int, error) {
|
||||||
|
if err := requireOwnerActor(actor); err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
page, size = normalizeAuditPage(page, size)
|
||||||
|
if err := s.db.First(&model.User{}, userID).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
q := s.db.Unscoped().Model(&model.Comment{}).Where("user_id = ?", userID)
|
||||||
|
var total int64
|
||||||
|
if err := q.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
var comments []model.Comment
|
||||||
|
if err := q.Order("id DESC").
|
||||||
|
Offset((page - 1) * size).Limit(size).Find(&comments).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
items := make([]AdminAuditCommentItem, 0, len(comments))
|
||||||
|
for _, c := range comments {
|
||||||
|
it := AdminAuditCommentItem{
|
||||||
|
ID: c.ID,
|
||||||
|
PostID: c.PostID,
|
||||||
|
Content: truncateStr(c.Content, 240),
|
||||||
|
Status: c.Status,
|
||||||
|
CreatedAt: c.CreatedAt,
|
||||||
|
}
|
||||||
|
if c.DeletedAt.Valid {
|
||||||
|
it.Deleted = true
|
||||||
|
t := c.DeletedAt.Time
|
||||||
|
it.DeletedAt = &t
|
||||||
|
}
|
||||||
|
items = append(items, it)
|
||||||
|
}
|
||||||
|
return items, total, page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListAuditMessages 站长:用户发出的全部聊天消息(含撤回/软删)
|
||||||
|
func (s *AdminUserService) ListAuditMessages(actor *Actor, userID uint, page, size int) ([]AdminAuditMessageItem, int64, int, error) {
|
||||||
|
if err := requireOwnerActor(actor); err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
page, size = normalizeAuditPage(page, size)
|
||||||
|
if err := s.db.First(&model.User{}, userID).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
q := s.db.Unscoped().Model(&model.ChatMessage{}).Where("sender_id = ?", userID)
|
||||||
|
var total int64
|
||||||
|
if err := q.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
var msgs []model.ChatMessage
|
||||||
|
if err := q.Order("id DESC").
|
||||||
|
Offset((page - 1) * size).Limit(size).Find(&msgs).Error; err != nil {
|
||||||
|
return nil, 0, page, err
|
||||||
|
}
|
||||||
|
|
||||||
|
roomIDs := make([]uint, 0, len(msgs))
|
||||||
|
seen := map[uint]struct{}{}
|
||||||
|
for _, m := range msgs {
|
||||||
|
if _, ok := seen[m.RoomID]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[m.RoomID] = struct{}{}
|
||||||
|
roomIDs = append(roomIDs, m.RoomID)
|
||||||
|
}
|
||||||
|
roomMap := map[uint]model.ChatRoom{}
|
||||||
|
if len(roomIDs) > 0 {
|
||||||
|
var rooms []model.ChatRoom
|
||||||
|
_ = s.db.Unscoped().Where("id IN ?", roomIDs).Find(&rooms)
|
||||||
|
for _, r := range rooms {
|
||||||
|
roomMap[r.ID] = r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
items := make([]AdminAuditMessageItem, 0, len(msgs))
|
||||||
|
for _, m := range msgs {
|
||||||
|
room := roomMap[m.RoomID]
|
||||||
|
name := room.Name
|
||||||
|
if name == "" {
|
||||||
|
if room.RoomType == model.ChatRoomTypeDirect {
|
||||||
|
name = "私聊"
|
||||||
|
} else if room.IsDefault {
|
||||||
|
name = "全站大厅"
|
||||||
|
} else {
|
||||||
|
name = "群聊"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
content := m.Content
|
||||||
|
recalled := m.RecalledAt != nil
|
||||||
|
if recalled && content == "" {
|
||||||
|
content = "(已撤回的消息)"
|
||||||
|
}
|
||||||
|
it := AdminAuditMessageItem{
|
||||||
|
ID: m.ID,
|
||||||
|
RoomID: m.RoomID,
|
||||||
|
RoomName: name,
|
||||||
|
RoomType: room.RoomType,
|
||||||
|
Content: truncateStr(content, 240),
|
||||||
|
Recalled: recalled,
|
||||||
|
CreatedAt: m.CreatedAt,
|
||||||
|
}
|
||||||
|
if m.DeletedAt.Valid {
|
||||||
|
it.Deleted = true
|
||||||
|
t := m.DeletedAt.Time
|
||||||
|
it.DeletedAt = &t
|
||||||
|
}
|
||||||
|
items = append(items, it)
|
||||||
|
}
|
||||||
|
return items, total, page, nil
|
||||||
|
}
|
||||||
|
|||||||
992
backend/service/chat.go
Normal file
992
backend/service/chat.go
Normal file
@@ -0,0 +1,992 @@
|
|||||||
|
// Package service 群聊业务(二期)。
|
||||||
|
//
|
||||||
|
// 铁律:消息先落库再由 handler 经 WS 广播,WS 不承担可靠投递;
|
||||||
|
// 未读数以成员行 last_read_message_id 为水位做 SQL 对账,离线期间不丢消息。
|
||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/freefire/jiang13-bbs/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrChatNotFound = errors.New("会话不存在")
|
||||||
|
ErrChatNotMember = errors.New("不是会话成员")
|
||||||
|
ErrChatNameInvalid = errors.New("群名称需为 2-32 个字符")
|
||||||
|
ErrChatDescInvalid = errors.New("群简介不能超过 200 个字符")
|
||||||
|
ErrChatContentEmpty = errors.New("消息内容不能为空")
|
||||||
|
ErrChatContentTooLong = errors.New("单条消息不能超过 2000 个字符")
|
||||||
|
ErrChatMuted = errors.New("你已被群主禁言")
|
||||||
|
ErrChatOwnerOnly = errors.New("仅群主可执行该操作")
|
||||||
|
ErrChatOwnerLeave = errors.New("群主不能直接退出,请先解散该群")
|
||||||
|
ErrChatPrivateInvite = errors.New("私密群需邀请才能加入")
|
||||||
|
ErrChatDefaultLeave = errors.New("默认大厅不可退出")
|
||||||
|
ErrChatDefaultDissolve = errors.New("默认大厅不可解散")
|
||||||
|
ErrChatRecallDenied = errors.New("无权撤回该消息")
|
||||||
|
ErrChatMsgNotFound = errors.New("消息不存在")
|
||||||
|
ErrChatDMSelf = errors.New("不能与自己私聊")
|
||||||
|
ErrChatDMDissolve = errors.New("私聊会话不可解散")
|
||||||
|
ErrChatUserGone = errors.New("用户不存在或已封禁")
|
||||||
|
ErrChatHallPinFixed = errors.New("大厅已置顶且不可取消")
|
||||||
|
)
|
||||||
|
|
||||||
|
// CanOverseeChat 站长/超管可旁路查看全部群并撤回任意消息
|
||||||
|
func CanOverseeChat(role model.Role) bool {
|
||||||
|
return role == model.RoleOwner || role == model.RoleSuperAdmin
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
chatNameMinRune = 2
|
||||||
|
chatNameMaxRune = 32
|
||||||
|
chatDescMaxRune = 200
|
||||||
|
chatMsgMaxRune = 2000
|
||||||
|
chatMentionMax = 20
|
||||||
|
)
|
||||||
|
|
||||||
|
// chatMentionRe @提醒匹配:用户名 3-32 位字母/数字/下划线/连字符;
|
||||||
|
// 是否有效最终以"群成员精确匹配"为准,名单外的 @ 原样当普通文本
|
||||||
|
var chatMentionRe = regexp.MustCompile(`@([A-Za-z0-9_-]{3,32})`)
|
||||||
|
|
||||||
|
// ChatService 群聊服务
|
||||||
|
type ChatService struct {
|
||||||
|
db *gorm.DB
|
||||||
|
notif *NotificationService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewChatService(db *gorm.DB, notif *NotificationService) *ChatService {
|
||||||
|
return &ChatService{db: db, notif: notif}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RoomView 会话列表/详情聚合视图
|
||||||
|
type RoomView struct {
|
||||||
|
model.ChatRoom
|
||||||
|
Joined bool `json:"joined"`
|
||||||
|
MyRole string `json:"my_role"`
|
||||||
|
UnreadCount int64 `json:"unread_count"`
|
||||||
|
Pinned bool `json:"pinned"` // 对当前用户是否置顶(含大厅强制)
|
||||||
|
PinForced bool `json:"pin_forced"` // 大厅强制置顶,不可取消
|
||||||
|
Peer *model.User `json:"peer,omitempty"` // 私聊对方(仅 direct)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnreadRoom 单个会话的未读计数
|
||||||
|
type UnreadRoom struct {
|
||||||
|
RoomID uint `gorm:"column:room_id" json:"room_id"`
|
||||||
|
Count int64 `gorm:"column:cnt" json:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func directKey(a, b uint) string {
|
||||||
|
if a > b {
|
||||||
|
a, b = b, a
|
||||||
|
}
|
||||||
|
return strconv.FormatUint(uint64(a), 10) + ":" + strconv.FormatUint(uint64(b), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ChatService) getRoom(roomID uint) (*model.ChatRoom, error) {
|
||||||
|
var room model.ChatRoom
|
||||||
|
err := s.db.First(&room, roomID).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrChatNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &room, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ChatService) membership(tx *gorm.DB, roomID, userID uint) (*model.ChatRoomMember, error) {
|
||||||
|
var m model.ChatRoomMember
|
||||||
|
err := tx.Where("room_id = ? AND user_id = ?", roomID, userID).First(&m).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrChatNotMember
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Membership 供 WS 握手后动态订阅房间鉴权
|
||||||
|
func (s *ChatService) Membership(roomID, userID uint) (*model.ChatRoomMember, error) {
|
||||||
|
return s.membership(s.db, roomID, userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// unreadCounts 批量计算访问者在给定群集合中的未读数(消息 ID 大于已读水位即未读)
|
||||||
|
func (s *ChatService) unreadCounts(userID uint, roomIDs []uint) map[uint]int64 {
|
||||||
|
out := make(map[uint]int64)
|
||||||
|
if userID == 0 || len(roomIDs) == 0 {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
var rows []UnreadRoom
|
||||||
|
s.db.Table("chat_messages AS m").
|
||||||
|
Select("m.room_id AS room_id, count(*) AS cnt").
|
||||||
|
Joins("JOIN chat_room_members AS rm ON rm.room_id = m.room_id AND rm.user_id = ?", userID).
|
||||||
|
Where("m.room_id IN ? AND m.id > rm.last_read_message_id AND m.deleted_at IS NULL AND m.recalled_at IS NULL", roomIDs).
|
||||||
|
Group("m.room_id").
|
||||||
|
Scan(&rows)
|
||||||
|
for _, r := range rows {
|
||||||
|
out[r.RoomID] = r.Count
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// toViews 批量填充 joined/角色/未读(避免 N+1)
|
||||||
|
func (s *ChatService) toViews(rooms []model.ChatRoom, userID uint) []RoomView {
|
||||||
|
ids := make([]uint, 0, len(rooms))
|
||||||
|
for i := range rooms {
|
||||||
|
ids = append(ids, rooms[i].ID)
|
||||||
|
}
|
||||||
|
memberMap := make(map[uint]model.ChatRoomMember)
|
||||||
|
if userID != 0 && len(ids) > 0 {
|
||||||
|
var ms []model.ChatRoomMember
|
||||||
|
s.db.Where("user_id = ? AND room_id IN ?", userID, ids).Find(&ms)
|
||||||
|
for _, m := range ms {
|
||||||
|
memberMap[m.RoomID] = m
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unread := s.unreadCounts(userID, ids)
|
||||||
|
views := make([]RoomView, 0, len(rooms))
|
||||||
|
for _, r := range rooms {
|
||||||
|
v := RoomView{ChatRoom: r, UnreadCount: unread[r.ID]}
|
||||||
|
if r.IsDefault {
|
||||||
|
v.Pinned = true
|
||||||
|
v.PinForced = true
|
||||||
|
}
|
||||||
|
if m, ok := memberMap[r.ID]; ok {
|
||||||
|
v.Joined = true
|
||||||
|
v.MyRole = m.Role
|
||||||
|
if m.PinnedAt != nil {
|
||||||
|
v.Pinned = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
views = append(views, v)
|
||||||
|
}
|
||||||
|
s.attachPeers(views, userID)
|
||||||
|
sortRoomViews(views, memberMap)
|
||||||
|
return views
|
||||||
|
}
|
||||||
|
|
||||||
|
// sortRoomViews:大厅强制置顶 > 个人置顶(pinned_at DESC) > last_message_id DESC
|
||||||
|
func sortRoomViews(views []RoomView, memberMap map[uint]model.ChatRoomMember) {
|
||||||
|
sort.SliceStable(views, func(i, j int) bool {
|
||||||
|
a, b := views[i], views[j]
|
||||||
|
if a.IsDefault != b.IsDefault {
|
||||||
|
return a.IsDefault
|
||||||
|
}
|
||||||
|
aPin, bPin := !a.IsDefault && a.Pinned, !b.IsDefault && b.Pinned
|
||||||
|
if aPin != bPin {
|
||||||
|
return aPin
|
||||||
|
}
|
||||||
|
if aPin && bPin {
|
||||||
|
var at, bt time.Time
|
||||||
|
if m, ok := memberMap[a.ID]; ok && m.PinnedAt != nil {
|
||||||
|
at = *m.PinnedAt
|
||||||
|
}
|
||||||
|
if m, ok := memberMap[b.ID]; ok && m.PinnedAt != nil {
|
||||||
|
bt = *m.PinnedAt
|
||||||
|
}
|
||||||
|
if !at.Equal(bt) {
|
||||||
|
return at.After(bt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.LastMessageID != b.LastMessageID {
|
||||||
|
return a.LastMessageID > b.LastMessageID
|
||||||
|
}
|
||||||
|
return a.ID > b.ID
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// attachPeers 为私聊会话填充对方用户信息
|
||||||
|
func (s *ChatService) attachPeers(views []RoomView, viewerID uint) {
|
||||||
|
directIDs := make([]uint, 0)
|
||||||
|
for i := range views {
|
||||||
|
if views[i].RoomType == model.ChatRoomTypeDirect {
|
||||||
|
directIDs = append(directIDs, views[i].ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(directIDs) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var members []model.ChatRoomMember
|
||||||
|
s.db.Where("room_id IN ? AND user_id <> ?", directIDs, viewerID).Preload("User").Find(&members)
|
||||||
|
peerByRoom := make(map[uint]*model.User, len(members))
|
||||||
|
for i := range members {
|
||||||
|
u := members[i].User
|
||||||
|
peerByRoom[members[i].RoomID] = &u
|
||||||
|
}
|
||||||
|
for i := range views {
|
||||||
|
if p, ok := peerByRoom[views[i].ID]; ok {
|
||||||
|
views[i].Peer = p
|
||||||
|
if views[i].Name == "" && p != nil {
|
||||||
|
views[i].Name = p.Nickname
|
||||||
|
if views[i].Name == "" {
|
||||||
|
views[i].Name = p.Username
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateRoom 建群:任意登录用户可建;isPrivate 时仅邀请可进;memberIDs 为初始成员(不含创建者)
|
||||||
|
func (s *ChatService) CreateRoom(creatorID uint, name, description string, isPrivate bool, memberIDs []uint) (*RoomView, error) {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
description = strings.TrimSpace(description)
|
||||||
|
if l := len([]rune(name)); l < chatNameMinRune || l > chatNameMaxRune {
|
||||||
|
return nil, ErrChatNameInvalid
|
||||||
|
}
|
||||||
|
if len([]rune(description)) > chatDescMaxRune {
|
||||||
|
return nil, ErrChatDescInvalid
|
||||||
|
}
|
||||||
|
// 去重、排除自己
|
||||||
|
seen := map[uint]struct{}{creatorID: {}}
|
||||||
|
cleanIDs := make([]uint, 0, len(memberIDs))
|
||||||
|
for _, id := range memberIDs {
|
||||||
|
if id == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seen[id]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
cleanIDs = append(cleanIDs, id)
|
||||||
|
}
|
||||||
|
room := model.ChatRoom{
|
||||||
|
Name: name,
|
||||||
|
Description: description,
|
||||||
|
OwnerID: creatorID,
|
||||||
|
RoomType: model.ChatRoomTypeGroup,
|
||||||
|
IsPrivate: isPrivate,
|
||||||
|
MemberCount: 1 + len(cleanIDs),
|
||||||
|
}
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Create(&room).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
m := model.ChatRoomMember{RoomID: room.ID, UserID: creatorID, Role: model.ChatRoleOwner}
|
||||||
|
if err := tx.Create(&m).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, uid := range cleanIDs {
|
||||||
|
mm := model.ChatRoomMember{RoomID: room.ID, UserID: uid, Role: model.ChatRoleMember}
|
||||||
|
if err := tx.Create(&mm).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var full model.ChatRoom
|
||||||
|
if err := s.db.Preload("Owner").First(&full, room.ID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
v := RoomView{ChatRoom: full, Joined: true, MyRole: model.ChatRoleOwner}
|
||||||
|
return &v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRooms 会话列表。joinedOnly=true 时仅已加入(IM 侧栏);否则公开群 + 已加入私密(站长旁路可见全部)
|
||||||
|
func (s *ChatService) ListRooms(userID uint, oversee, joinedOnly bool, q string, page, size int) ([]RoomView, int64, error) {
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if size < 1 || size > 50 {
|
||||||
|
size = 20
|
||||||
|
}
|
||||||
|
query := s.db.Model(&model.ChatRoom{})
|
||||||
|
if joinedOnly && userID > 0 {
|
||||||
|
query = query.Where("id IN (SELECT room_id FROM chat_room_members WHERE user_id = ?)", userID)
|
||||||
|
} else if !oversee {
|
||||||
|
if userID == 0 {
|
||||||
|
query = query.Where("is_private = ? AND room_type = ?", false, model.ChatRoomTypeGroup)
|
||||||
|
} else {
|
||||||
|
query = query.Where(
|
||||||
|
"(is_private = ? AND room_type = ?) OR id IN (SELECT room_id FROM chat_room_members WHERE user_id = ?)",
|
||||||
|
false, model.ChatRoomTypeGroup, userID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if q = strings.TrimSpace(q); q != "" {
|
||||||
|
esc := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(q)
|
||||||
|
query = query.Where(`name ILIKE ? ESCAPE '\'`, "%"+esc+"%")
|
||||||
|
}
|
||||||
|
var total int64
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
var rooms []model.ChatRoom
|
||||||
|
// 已加入列表需按个人置顶排序:先全量取出再内存排序分页(会话量通常很小)
|
||||||
|
if joinedOnly && userID > 0 {
|
||||||
|
if err := query.
|
||||||
|
Preload("Owner").Preload("LastMessage.Sender").
|
||||||
|
Find(&rooms).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
views := s.toViews(rooms, userID)
|
||||||
|
start := (page - 1) * size
|
||||||
|
if start >= len(views) {
|
||||||
|
return []RoomView{}, total, nil
|
||||||
|
}
|
||||||
|
end := start + size
|
||||||
|
if end > len(views) {
|
||||||
|
end = len(views)
|
||||||
|
}
|
||||||
|
return views[start:end], total, nil
|
||||||
|
}
|
||||||
|
if err := query.
|
||||||
|
Order("is_default DESC, last_message_id DESC, id DESC").
|
||||||
|
Offset((page - 1) * size).Limit(size).
|
||||||
|
Preload("Owner").Preload("LastMessage.Sender").
|
||||||
|
Find(&rooms).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
return s.toViews(rooms, userID), total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRoomPinned 当前用户置顶/取消置顶(大厅强制置顶不可取消)
|
||||||
|
func (s *ChatService) SetRoomPinned(userID, roomID uint, pinned bool) (*RoomView, error) {
|
||||||
|
room, err := s.getRoom(roomID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if room.IsDefault {
|
||||||
|
return nil, ErrChatHallPinFixed
|
||||||
|
}
|
||||||
|
m, err := s.membership(s.db, roomID, userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pinned {
|
||||||
|
now := time.Now()
|
||||||
|
if err := s.db.Model(m).Update("pinned_at", now).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := s.db.Model(m).Update("pinned_at", nil).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s.RoomDetail(userID, roomID, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOrCreateDM 获取或创建与对方的一对一私聊(幂等)
|
||||||
|
func (s *ChatService) GetOrCreateDM(meID, peerID uint) (*RoomView, error) {
|
||||||
|
if peerID == 0 || peerID == meID {
|
||||||
|
return nil, ErrChatDMSelf
|
||||||
|
}
|
||||||
|
var peer model.User
|
||||||
|
if err := s.db.Where("id = ? AND banned = ? AND deleted_at IS NULL", peerID, false).First(&peer).Error; err != nil {
|
||||||
|
return nil, ErrChatUserGone
|
||||||
|
}
|
||||||
|
key := directKey(meID, peerID)
|
||||||
|
var existing model.ChatRoom
|
||||||
|
err := s.db.Where("room_type = ? AND direct_key = ?", model.ChatRoomTypeDirect, key).First(&existing).Error
|
||||||
|
if err == nil {
|
||||||
|
_ = s.ensureMember(existing.ID, meID)
|
||||||
|
_ = s.ensureMember(existing.ID, peerID)
|
||||||
|
return s.RoomDetail(meID, existing.ID, false)
|
||||||
|
}
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
room := model.ChatRoom{
|
||||||
|
Name: "",
|
||||||
|
OwnerID: meID,
|
||||||
|
RoomType: model.ChatRoomTypeDirect,
|
||||||
|
DirectKey: key,
|
||||||
|
IsPrivate: true,
|
||||||
|
MemberCount: 2,
|
||||||
|
}
|
||||||
|
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if e := tx.Create(&room).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
ms := []model.ChatRoomMember{
|
||||||
|
{RoomID: room.ID, UserID: meID, Role: model.ChatRoleMember},
|
||||||
|
{RoomID: room.ID, UserID: peerID, Role: model.ChatRoleMember},
|
||||||
|
}
|
||||||
|
return tx.Create(&ms).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if e2 := s.db.Where("room_type = ? AND direct_key = ?", model.ChatRoomTypeDirect, key).First(&existing).Error; e2 == nil {
|
||||||
|
return s.RoomDetail(meID, existing.ID, false)
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return s.RoomDetail(meID, room.ID, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ChatService) ensureMember(roomID, userID uint) error {
|
||||||
|
_, err := s.membership(s.db, roomID, userID)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, ErrChatNotMember) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
m := model.ChatRoomMember{RoomID: roomID, UserID: userID, Role: model.ChatRoleMember}
|
||||||
|
if e := s.db.Create(&m).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
return s.db.Model(&model.ChatRoom{}).Where("id = ?", roomID).
|
||||||
|
UpdateColumn("member_count", gorm.Expr("GREATEST(member_count + 1, 0)")).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListMemberIDs 房间全部成员 ID(发消息后推未读角标用)
|
||||||
|
func (s *ChatService) ListMemberIDs(roomID uint) ([]uint, error) {
|
||||||
|
var ids []uint
|
||||||
|
err := s.db.Model(&model.ChatRoomMember{}).Where("room_id = ?", roomID).Pluck("user_id", &ids).Error
|
||||||
|
return ids, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SearchUsersForChat 按用户名/昵称搜索可发起私聊的用户(排除自己、封禁)
|
||||||
|
func (s *ChatService) SearchUsersForChat(meID uint, q string, limit int) ([]model.User, error) {
|
||||||
|
q = strings.TrimSpace(q)
|
||||||
|
if q == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if limit < 1 || limit > 20 {
|
||||||
|
limit = 10
|
||||||
|
}
|
||||||
|
esc := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(q)
|
||||||
|
like := "%" + esc + "%"
|
||||||
|
var users []model.User
|
||||||
|
err := s.db.Select("id", "username", "nickname", "avatar", "role").
|
||||||
|
Where("id <> ? AND banned = ? AND deleted_at IS NULL AND (username ILIKE ? ESCAPE '\\' OR nickname ILIKE ? ESCAPE '\\')",
|
||||||
|
meID, false, like, like).
|
||||||
|
Order("username ASC").Limit(limit).Find(&users).Error
|
||||||
|
return users, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// RoomDetail 群详情:成员或监管者可读;公开非成员返回 joined=false(可预览元数据)
|
||||||
|
func (s *ChatService) RoomDetail(userID, roomID uint, oversee bool) (*RoomView, error) {
|
||||||
|
room, err := s.getRoom(roomID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_, memErr := s.membership(s.db, roomID, userID)
|
||||||
|
isMember := memErr == nil
|
||||||
|
if !isMember && !oversee {
|
||||||
|
if room.IsPrivate {
|
||||||
|
return nil, ErrChatNotFound // 私密非成员伪装不存在
|
||||||
|
}
|
||||||
|
// 公开非成员:允许预览
|
||||||
|
} else if memErr != nil && !oversee && !errors.Is(memErr, ErrChatNotMember) {
|
||||||
|
return nil, memErr
|
||||||
|
}
|
||||||
|
if err := s.db.Preload("Owner").Preload("LastMessage.Sender").First(room, roomID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
views := s.toViews([]model.ChatRoom{*room}, userID)
|
||||||
|
v := views[0]
|
||||||
|
if oversee && !v.Joined {
|
||||||
|
v.Joined = true // 监管旁路按已加入展示,可看历史
|
||||||
|
v.MyRole = "overseer"
|
||||||
|
}
|
||||||
|
return &v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Join 加入公开群(私密/私聊拒绝;幂等)
|
||||||
|
func (s *ChatService) Join(userID, roomID uint) (member *model.ChatRoomMember, joined bool, err error) {
|
||||||
|
room, err := s.getRoom(roomID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
if room.RoomType == model.ChatRoomTypeDirect {
|
||||||
|
return nil, false, ErrChatNotFound
|
||||||
|
}
|
||||||
|
if room.IsPrivate {
|
||||||
|
return nil, false, ErrChatPrivateInvite
|
||||||
|
}
|
||||||
|
if m, mErr := s.membership(s.db, roomID, userID); mErr == nil {
|
||||||
|
return m, false, nil
|
||||||
|
} else if !errors.Is(mErr, ErrChatNotMember) {
|
||||||
|
return nil, false, mErr
|
||||||
|
}
|
||||||
|
m := model.ChatRoomMember{RoomID: roomID, UserID: userID, Role: model.ChatRoleMember}
|
||||||
|
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if e := tx.Create(&m).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
return tx.Model(&model.ChatRoom{}).Where("id = ?", roomID).
|
||||||
|
UpdateColumn("member_count", gorm.Expr("GREATEST(member_count + 1, 0)")).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if existing, qErr := s.membership(s.db, roomID, userID); qErr == nil {
|
||||||
|
return existing, false, nil
|
||||||
|
}
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
return &m, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteMembers 群主(或监管)拉人入群;返回实际新加入的用户 ID
|
||||||
|
func (s *ChatService) InviteMembers(operatorID, roomID uint, userIDs []uint, oversee bool) ([]uint, error) {
|
||||||
|
room, err := s.getRoom(roomID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if room.RoomType == model.ChatRoomTypeDirect {
|
||||||
|
return nil, ErrChatOwnerOnly
|
||||||
|
}
|
||||||
|
if !oversee {
|
||||||
|
op, err := s.membership(s.db, roomID, operatorID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if op.Role != model.ChatRoleOwner {
|
||||||
|
return nil, ErrChatOwnerOnly
|
||||||
|
}
|
||||||
|
}
|
||||||
|
added := make([]uint, 0)
|
||||||
|
for _, uid := range userIDs {
|
||||||
|
if uid == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, mErr := s.membership(s.db, roomID, uid); mErr == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var u model.User
|
||||||
|
if err := s.db.Select("id").Where("id = ? AND banned = ? AND deleted_at IS NULL", uid, false).First(&u).Error; err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
m := model.ChatRoomMember{RoomID: roomID, UserID: uid, Role: model.ChatRoleMember}
|
||||||
|
if room.OwnerID == uid {
|
||||||
|
m.Role = model.ChatRoleOwner
|
||||||
|
}
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if e := tx.Create(&m).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
return tx.Model(&model.ChatRoom{}).Where("id = ?", roomID).
|
||||||
|
UpdateColumn("member_count", gorm.Expr("GREATEST(member_count + 1, 0)")).Error
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
added = append(added, uid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return added, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureDefaultMembership 将用户加入默认大厅(注册后调用,幂等)
|
||||||
|
func (s *ChatService) EnsureDefaultMembership(userID uint) error {
|
||||||
|
var room model.ChatRoom
|
||||||
|
if err := s.db.Where("is_default = ?", true).First(&room).Error; err != nil {
|
||||||
|
return nil // 尚无大厅则跳过
|
||||||
|
}
|
||||||
|
if _, err := s.membership(s.db, room.ID, userID); err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m := model.ChatRoomMember{RoomID: room.ID, UserID: userID, Role: model.ChatRoleMember}
|
||||||
|
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if e := tx.Create(&m).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
return tx.Model(&model.ChatRoom{}).Where("id = ?", room.ID).
|
||||||
|
UpdateColumn("member_count", gorm.Expr("GREATEST(member_count + 1, 0)")).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leave 普通成员退出群聊(群主不可退出;默认大厅不可退出;私聊可退出)
|
||||||
|
func (s *ChatService) Leave(userID, roomID uint) error {
|
||||||
|
room, err := s.getRoom(roomID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if room.IsDefault {
|
||||||
|
return ErrChatDefaultLeave
|
||||||
|
}
|
||||||
|
m, err := s.membership(s.db, roomID, userID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if room.RoomType != model.ChatRoomTypeDirect && m.Role == model.ChatRoleOwner {
|
||||||
|
return ErrChatOwnerLeave
|
||||||
|
}
|
||||||
|
return s.removeMember(roomID, userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// removeMember 删除成员行并把群人数 -1(不小于 0)
|
||||||
|
func (s *ChatService) removeMember(roomID, userID uint) error {
|
||||||
|
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
res := tx.Where("room_id = ? AND user_id = ?", roomID, userID).Delete(&model.ChatRoomMember{})
|
||||||
|
if res.Error != nil {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
if res.RowsAffected == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return tx.Model(&model.ChatRoom{}).Where("id = ?", roomID).
|
||||||
|
UpdateColumn("member_count", gorm.Expr("GREATEST(member_count - 1, 0)")).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dissolve 群主解散群(默认大厅/私聊不可解散)
|
||||||
|
func (s *ChatService) Dissolve(userID, roomID uint, oversee bool) error {
|
||||||
|
room, err := s.getRoom(roomID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if room.IsDefault {
|
||||||
|
return ErrChatDefaultDissolve
|
||||||
|
}
|
||||||
|
if room.RoomType == model.ChatRoomTypeDirect {
|
||||||
|
return ErrChatDMDissolve
|
||||||
|
}
|
||||||
|
if !oversee {
|
||||||
|
m, err := s.membership(s.db, roomID, userID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if m.Role != model.ChatRoleOwner {
|
||||||
|
return ErrChatOwnerOnly
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Delete(&model.ChatRoom{}, roomID).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Where("room_id = ?", roomID).Delete(&model.ChatRoomMember{}).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateRoom 群主修改群名称/简介
|
||||||
|
func (s *ChatService) UpdateRoom(userID, roomID uint, name, description string) (*model.ChatRoom, error) {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
description = strings.TrimSpace(description)
|
||||||
|
if l := len([]rune(name)); l < chatNameMinRune || l > chatNameMaxRune {
|
||||||
|
return nil, ErrChatNameInvalid
|
||||||
|
}
|
||||||
|
if len([]rune(description)) > chatDescMaxRune {
|
||||||
|
return nil, ErrChatDescInvalid
|
||||||
|
}
|
||||||
|
room, err := s.getRoom(roomID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
m, err := s.membership(s.db, roomID, userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if m.Role != model.ChatRoleOwner {
|
||||||
|
return nil, ErrChatOwnerOnly
|
||||||
|
}
|
||||||
|
if err := s.db.Model(room).Updates(map[string]interface{}{
|
||||||
|
"name": name,
|
||||||
|
"description": description,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return s.getRoom(roomID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListMembers 成员名单:成员或监管者可查看
|
||||||
|
func (s *ChatService) ListMembers(userID, roomID uint, oversee bool) ([]model.ChatRoomMember, error) {
|
||||||
|
if _, err := s.getRoom(roomID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !oversee {
|
||||||
|
if _, err := s.membership(s.db, roomID, userID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var list []model.ChatRoomMember
|
||||||
|
err := s.db.Where("room_id = ?", roomID).
|
||||||
|
Order("CASE WHEN role = 'owner' THEN 0 ELSE 1 END, created_at ASC").
|
||||||
|
Preload("User").
|
||||||
|
Find(&list).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return list, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kick 群主踢人(不能踢群主)
|
||||||
|
func (s *ChatService) Kick(operatorID, roomID, targetID uint) error {
|
||||||
|
if _, err := s.getRoom(roomID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
op, err := s.membership(s.db, roomID, operatorID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if op.Role != model.ChatRoleOwner {
|
||||||
|
return ErrChatOwnerOnly
|
||||||
|
}
|
||||||
|
target, err := s.membership(s.db, roomID, targetID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if target.Role == model.ChatRoleOwner {
|
||||||
|
return ErrChatOwnerOnly
|
||||||
|
}
|
||||||
|
return s.removeMember(roomID, targetID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendMessage 发送群消息:成员且未被禁言;可选引用回复;解析@并落提醒通知。
|
||||||
|
func (s *ChatService) SendMessage(senderID, roomID uint, content string, replyToID uint) (*model.ChatMessage, []uint, error) {
|
||||||
|
content = strings.TrimSpace(content)
|
||||||
|
if content == "" {
|
||||||
|
return nil, nil, ErrChatContentEmpty
|
||||||
|
}
|
||||||
|
if len([]rune(content)) > chatMsgMaxRune {
|
||||||
|
return nil, nil, ErrChatContentTooLong
|
||||||
|
}
|
||||||
|
if _, err := s.getRoom(roomID); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
m, err := s.membership(s.db, roomID, senderID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if m.Muted {
|
||||||
|
return nil, nil, ErrChatMuted
|
||||||
|
}
|
||||||
|
|
||||||
|
replySnap := ""
|
||||||
|
if replyToID > 0 {
|
||||||
|
var quoted model.ChatMessage
|
||||||
|
if err := s.db.Where("id = ? AND room_id = ?", replyToID, roomID).
|
||||||
|
Preload("Sender").First("ed).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, nil, ErrChatMsgNotFound
|
||||||
|
}
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
name := quoted.Sender.Nickname
|
||||||
|
if name == "" {
|
||||||
|
name = quoted.Sender.Username
|
||||||
|
}
|
||||||
|
if quoted.RecalledAt != nil {
|
||||||
|
replySnap = name + ": (已撤回的消息)"
|
||||||
|
} else {
|
||||||
|
snippet := quoted.Content
|
||||||
|
rs := []rune(snippet)
|
||||||
|
if len(rs) > 80 {
|
||||||
|
snippet = string(rs[:80]) + "…"
|
||||||
|
}
|
||||||
|
replySnap = name + ": " + snippet
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mentionIDs := s.resolveMentions(roomID, senderID, content)
|
||||||
|
|
||||||
|
msg := &model.ChatMessage{
|
||||||
|
RoomID: roomID,
|
||||||
|
SenderID: senderID,
|
||||||
|
Content: content,
|
||||||
|
ReplyToID: replyToID,
|
||||||
|
ReplySnap: replySnap,
|
||||||
|
MentionIDs: joinMentionIDs(mentionIDs),
|
||||||
|
}
|
||||||
|
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Create(msg).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Model(&model.ChatRoom{}).Where("id = ?", roomID).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"last_message_id": msg.ID,
|
||||||
|
"updated_at": time.Now(),
|
||||||
|
}).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if err := s.db.Preload("Sender").First(msg, msg.ID).Error; err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
for _, uid := range mentionIDs {
|
||||||
|
s.notif.CreateMention(uid, senderID, roomID, msg.ID, content)
|
||||||
|
}
|
||||||
|
return msg, mentionIDs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveMentions 文本中 @用户名 → 群成员用户 ID(去重、排除自己、上限 20)
|
||||||
|
func (s *ChatService) resolveMentions(roomID, senderID uint, content string) []uint {
|
||||||
|
matches := chatMentionRe.FindAllStringSubmatch(content, -1)
|
||||||
|
if len(matches) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
nameSet := make(map[string]struct{}, len(matches))
|
||||||
|
names := make([]string, 0, len(matches))
|
||||||
|
for _, mt := range matches {
|
||||||
|
name := strings.ToLower(mt[1])
|
||||||
|
if _, ok := nameSet[name]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
nameSet[name] = struct{}{}
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
if len(names) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// 用户名大小写不敏感匹配(注册名唯一但比较时统一 lower)
|
||||||
|
var users []model.User
|
||||||
|
s.db.Where("LOWER(username) IN ? AND banned = ?", names, false).Find(&users)
|
||||||
|
if len(users) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
userIDs := make([]uint, 0, len(users))
|
||||||
|
for _, u := range users {
|
||||||
|
userIDs = append(userIDs, u.ID)
|
||||||
|
}
|
||||||
|
var memberIDs []uint
|
||||||
|
s.db.Model(&model.ChatRoomMember{}).
|
||||||
|
Where("room_id = ? AND user_id IN ?", roomID, userIDs).
|
||||||
|
Pluck("user_id", &memberIDs)
|
||||||
|
seen := make(map[uint]struct{}, len(memberIDs))
|
||||||
|
out := make([]uint, 0, len(memberIDs))
|
||||||
|
for _, id := range memberIDs {
|
||||||
|
if id == senderID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seen[id]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
out = append(out, id)
|
||||||
|
if len(out) >= chatMentionMax {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func joinMentionIDs(ids []uint) string {
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
parts := make([]string, len(ids))
|
||||||
|
for i, id := range ids {
|
||||||
|
parts[i] = strconv.FormatUint(uint64(id), 10)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ",")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListMessages 历史消息分页:成员或监管者可取;已撤回消息仍返回(前端显示占位)
|
||||||
|
func (s *ChatService) ListMessages(userID, roomID, beforeID uint, size int, oversee bool) ([]model.ChatMessage, bool, error) {
|
||||||
|
if size < 1 || size > 50 {
|
||||||
|
size = 30
|
||||||
|
}
|
||||||
|
if _, err := s.getRoom(roomID); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
if !oversee {
|
||||||
|
if _, err := s.membership(s.db, roomID, userID); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
q := s.db.Where("room_id = ?", roomID)
|
||||||
|
if beforeID > 0 {
|
||||||
|
q = q.Where("id < ?", beforeID)
|
||||||
|
}
|
||||||
|
var msgs []model.ChatMessage
|
||||||
|
if err := q.Order("id DESC").Limit(size + 1).Preload("Sender").Find(&msgs).Error; err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
hasMore := len(msgs) > size
|
||||||
|
if hasMore {
|
||||||
|
msgs = msgs[:size]
|
||||||
|
}
|
||||||
|
for i, j := 0, len(msgs)-1; i < j; i, j = i+1, j-1 {
|
||||||
|
msgs[i], msgs[j] = msgs[j], msgs[i]
|
||||||
|
}
|
||||||
|
// 对非监管者清空已撤回正文
|
||||||
|
if !oversee {
|
||||||
|
for i := range msgs {
|
||||||
|
if msgs[i].RecalledAt != nil {
|
||||||
|
msgs[i].Content = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return msgs, hasMore, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecallMessage 撤回消息:群主可撤自己的;监管者可撤任意;标记 RecalledAt 不清行
|
||||||
|
func (s *ChatService) RecallMessage(operatorID, roomID, messageID uint, oversee bool) (*model.ChatMessage, error) {
|
||||||
|
if _, err := s.getRoom(roomID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var msg model.ChatMessage
|
||||||
|
if err := s.db.Where("id = ? AND room_id = ?", messageID, roomID).First(&msg).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrChatMsgNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if msg.RecalledAt != nil {
|
||||||
|
return &msg, nil // 幂等
|
||||||
|
}
|
||||||
|
if !oversee {
|
||||||
|
m, err := s.membership(s.db, roomID, operatorID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// 群主/成员仅可撤回自己的消息;监管者可撤任意
|
||||||
|
if msg.SenderID != operatorID {
|
||||||
|
_ = m // 成员校验已通过
|
||||||
|
return nil, ErrChatRecallDenied
|
||||||
|
}
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
if err := s.db.Model(&msg).Updates(map[string]interface{}{
|
||||||
|
"recalled_at": now,
|
||||||
|
"recalled_by": operatorID,
|
||||||
|
"content": "",
|
||||||
|
}).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
msg.RecalledAt = &now
|
||||||
|
msg.RecalledBy = operatorID
|
||||||
|
msg.Content = ""
|
||||||
|
_ = s.db.Preload("Sender").First(&msg, msg.ID)
|
||||||
|
return &msg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkRead 把已读水位推进到指定消息(单调不减;messageID=0 或超过最新则取最新)
|
||||||
|
func (s *ChatService) MarkRead(userID, roomID, messageID uint) error {
|
||||||
|
room, err := s.getRoom(roomID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := s.membership(s.db, roomID, userID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if messageID == 0 || messageID > room.LastMessageID {
|
||||||
|
messageID = room.LastMessageID
|
||||||
|
}
|
||||||
|
return s.db.Model(&model.ChatRoomMember{}).
|
||||||
|
Where("room_id = ? AND user_id = ? AND last_read_message_id < ?", roomID, userID, messageID).
|
||||||
|
Update("last_read_message_id", messageID).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnreadSummary 当前用户所有群的未读明细与总数
|
||||||
|
func (s *ChatService) UnreadSummary(userID uint) (int64, []UnreadRoom, error) {
|
||||||
|
var rows []UnreadRoom
|
||||||
|
err := s.db.Table("chat_messages AS m").
|
||||||
|
Select("m.room_id AS room_id, count(*) AS cnt").
|
||||||
|
Joins("JOIN chat_room_members AS rm ON rm.room_id = m.room_id AND rm.user_id = ?", userID).
|
||||||
|
Where("m.id > rm.last_read_message_id AND m.deleted_at IS NULL AND m.recalled_at IS NULL").
|
||||||
|
Group("m.room_id").
|
||||||
|
Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
var total int64
|
||||||
|
for _, r := range rows {
|
||||||
|
total += r.Count
|
||||||
|
}
|
||||||
|
return total, rows, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TotalUnread 供 /me SSR 一次调用(Header 红点直出)
|
||||||
|
func (s *ChatService) TotalUnread(userID uint) int64 {
|
||||||
|
total, _, _ := s.UnreadSummary(userID)
|
||||||
|
return total
|
||||||
|
}
|
||||||
@@ -35,16 +35,16 @@ const maxReplyDepth = 10
|
|||||||
|
|
||||||
// ListFloorPaged 楼层分页获取帖子评论树:
|
// ListFloorPaged 楼层分页获取帖子评论树:
|
||||||
// 分页与楼层号只针对主评论(parent_id IS NULL),每楼附带全部子评论(时间正序)。
|
// 分页与楼层号只针对主评论(parent_id IS NULL),每楼附带全部子评论(时间正序)。
|
||||||
|
// viewer 可为作者本人或该板可审者时并入 pending;游客仅 published。
|
||||||
// 返回:树根列表、楼层数、全部评论数(含回复)。
|
// 返回:树根列表、楼层数、全部评论数(含回复)。
|
||||||
func (s *CommentService) ListFloorPaged(postID uint, page, size int) ([]CommentNode, int64, int64, error) {
|
func (s *CommentService) ListFloorPaged(postID, boardID, viewerID uint, actor *Actor, page, size int) ([]CommentNode, int64, int64, error) {
|
||||||
if page < 1 {
|
if page < 1 {
|
||||||
page = 1
|
page = 1
|
||||||
}
|
}
|
||||||
if size < 1 || size > 100 {
|
if size < 1 || size > 100 {
|
||||||
size = 20
|
size = 20
|
||||||
}
|
}
|
||||||
base := s.db.Model(&model.Comment{}).
|
base := applyCommentListVisibility(s.db.Model(&model.Comment{}).Where("post_id = ?", postID), boardID, viewerID, actor)
|
||||||
Where("post_id = ? AND status = ?", postID, model.ContentStatusPublished)
|
|
||||||
|
|
||||||
var floors, totalComments int64
|
var floors, totalComments int64
|
||||||
if err := base.Session(&gorm.Session{}).
|
if err := base.Session(&gorm.Session{}).
|
||||||
@@ -75,11 +75,9 @@ func (s *CommentService) ListFloorPaged(postID uint, page, size int) ([]CommentN
|
|||||||
for i, r := range roots {
|
for i, r := range roots {
|
||||||
rootIDs[i] = r.ID
|
rootIDs[i] = r.ID
|
||||||
}
|
}
|
||||||
|
replyQ := applyCommentListVisibility(s.db.Where("root_id IN (?)", rootIDs), boardID, viewerID, actor)
|
||||||
var replies []model.Comment
|
var replies []model.Comment
|
||||||
if err := s.db.Where("root_id IN (?) AND status = ?", rootIDs, model.ContentStatusPublished).
|
if err := replyQ.Order("created_at ASC").Preload("User").Find(&replies).Error; err != nil {
|
||||||
Order("created_at ASC").
|
|
||||||
Preload("User").
|
|
||||||
Find(&replies).Error; err != nil {
|
|
||||||
return nil, 0, 0, err
|
return nil, 0, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,6 +118,20 @@ func (s *CommentService) ListFloorPaged(postID uint, page, size int) ([]CommentN
|
|||||||
return result, floors, totalComments, nil
|
return result, floors, totalComments, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// applyCommentListVisibility 评论流可见性:published,或 pending 且(作者 / 该板可审)
|
||||||
|
func applyCommentListVisibility(db *gorm.DB, boardID, viewerID uint, actor *Actor) *gorm.DB {
|
||||||
|
if viewerID == 0 || actor == nil {
|
||||||
|
return db.Where("status = ?", model.ContentStatusPublished)
|
||||||
|
}
|
||||||
|
if actor.CanModerateBoard(boardID) {
|
||||||
|
return db.Where("status IN ?", []string{model.ContentStatusPublished, model.ContentStatusPending})
|
||||||
|
}
|
||||||
|
return db.Where(
|
||||||
|
"status = ? OR (status = ? AND user_id = ?)",
|
||||||
|
model.ContentStatusPublished, model.ContentStatusPending, viewerID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// Create 创建评论(parentID 为 nil 时发主评论/楼层,否则发为对应评论的子回复)。
|
// Create 创建评论(parentID 为 nil 时发主评论/楼层,否则发为对应评论的子回复)。
|
||||||
// status 由 handler 按角色计算:管理团队直发 published,普通用户进入 pending;
|
// status 由 handler 按角色计算:管理团队直发 published,普通用户进入 pending;
|
||||||
// pending 评论不计入 comment_count,审核通过时才 +1。
|
// pending 评论不计入 comment_count,审核通过时才 +1。
|
||||||
|
|||||||
@@ -158,9 +158,9 @@ func (s *ModerationService) PendingCounts(actor *Actor) (posts int64, comments i
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// ApprovePost 帖子审核通过
|
// ApprovePost 帖子审核通过;成功时返回板块 ID 供 feed 广播
|
||||||
func (s *ModerationService) ApprovePost(actor *Actor, id uint) error {
|
func (s *ModerationService) ApprovePost(actor *Actor, id uint) (boardID uint, err error) {
|
||||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
var post model.Post
|
var post model.Post
|
||||||
if err := tx.First(&post, id).Error; err != nil {
|
if err := tx.First(&post, id).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -174,10 +174,12 @@ func (s *ModerationService) ApprovePost(actor *Actor, id uint) error {
|
|||||||
if err := tx.Model(&post).Update("status", model.ContentStatusPublished).Error; err != nil {
|
if err := tx.Model(&post).Update("status", model.ContentStatusPublished).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
boardID = post.BoardID
|
||||||
s.notif.Create(post.UserID, actor.ID, model.NotificationTypeApproved, post.ID, 0,
|
s.notif.Create(post.UserID, actor.ID, model.NotificationTypeApproved, post.ID, 0,
|
||||||
"你的帖子《"+post.Title+"》已通过审核")
|
"你的帖子《"+post.Title+"》已通过审核")
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
return boardID, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// RejectPost 帖子审核拒绝(标记 rejected,不物理删除;作者仍可在详情页看到结果)
|
// RejectPost 帖子审核拒绝(标记 rejected,不物理删除;作者仍可在详情页看到结果)
|
||||||
@@ -202,15 +204,15 @@ func (s *ModerationService) RejectPost(actor *Actor, id uint) error {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ApproveComment 评论审核通过(通过时才计入帖子评论数)
|
// ApproveComment 评论审核通过(通过时才计入帖子评论数);成功时返回帖子 ID 与板块 ID
|
||||||
func (s *ModerationService) ApproveComment(actor *Actor, id uint) error {
|
func (s *ModerationService) ApproveComment(actor *Actor, id uint) (postID, boardID uint, err error) {
|
||||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
var cm model.Comment
|
var cm model.Comment
|
||||||
if err := tx.First(&cm, id).Error; err != nil {
|
if err := tx.First(&cm, id).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var post model.Post
|
var post model.Post
|
||||||
if err := tx.Select("id", "board_id", "title").First(&post, cm.PostID).Error; err != nil {
|
if err := tx.Select("id", "board_id", "title", "user_id").First(&post, cm.PostID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !actor.CanModerateBoard(post.BoardID) {
|
if !actor.CanModerateBoard(post.BoardID) {
|
||||||
@@ -226,6 +228,8 @@ func (s *ModerationService) ApproveComment(actor *Actor, id uint) error {
|
|||||||
UpdateColumn("comment_count", gorm.Expr("comment_count + 1")).Error; err != nil {
|
UpdateColumn("comment_count", gorm.Expr("comment_count + 1")).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
postID = cm.PostID
|
||||||
|
boardID = post.BoardID
|
||||||
s.notif.Create(cm.UserID, actor.ID, model.NotificationTypeApproved, cm.PostID, cm.ID,
|
s.notif.Create(cm.UserID, actor.ID, model.NotificationTypeApproved, cm.PostID, cm.ID,
|
||||||
"你在帖子《"+post.Title+"》下的评论已通过审核")
|
"你在帖子《"+post.Title+"》下的评论已通过审核")
|
||||||
// 评论此时才公开,补发送业务通知(以评论者为 actor):
|
// 评论此时才公开,补发送业务通知(以评论者为 actor):
|
||||||
@@ -240,6 +244,7 @@ func (s *ModerationService) ApproveComment(actor *Actor, id uint) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
return postID, boardID, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// RejectComment 评论审核拒绝
|
// RejectComment 评论审核拒绝
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import (
|
|||||||
// NotificationService 通知服务
|
// NotificationService 通知服务
|
||||||
type NotificationService struct {
|
type NotificationService struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
// OnNotifyNew 落库成功后回调(用于 WS 推送红点);可为 nil
|
||||||
|
OnNotifyNew func(userID uint)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewNotificationService(db *gorm.DB) *NotificationService {
|
func NewNotificationService(db *gorm.DB) *NotificationService {
|
||||||
@@ -33,7 +35,38 @@ func (s *NotificationService) Create(userID, actorID uint, notifType string, pos
|
|||||||
IsRead: false,
|
IsRead: false,
|
||||||
}
|
}
|
||||||
// 通知创建失败不影响主流程,忽略错误
|
// 通知创建失败不影响主流程,忽略错误
|
||||||
_ = s.db.Create(n).Error
|
if err := s.db.Create(n).Error; err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if s.OnNotifyNew != nil {
|
||||||
|
s.OnNotifyNew(userID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateMention 创建群聊 @ 提醒(PostID=0,用 RoomID/MessageID 关联)。
|
||||||
|
// 返回创建出的通知 ID(0 表示未创建),供 handler 实时推送。
|
||||||
|
func (s *NotificationService) CreateMention(userID, actorID, roomID, messageID uint, content string) uint {
|
||||||
|
if userID == 0 || actorID == 0 || userID == actorID || roomID == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if runes := []rune(content); len(runes) > 100 {
|
||||||
|
content = string(runes[:100])
|
||||||
|
}
|
||||||
|
n := &model.Notification{
|
||||||
|
UserID: userID,
|
||||||
|
ActorID: actorID,
|
||||||
|
Type: model.NotificationTypeMention,
|
||||||
|
RoomID: roomID,
|
||||||
|
MessageID: messageID,
|
||||||
|
Content: content,
|
||||||
|
}
|
||||||
|
if err := s.db.Create(n).Error; err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if s.OnNotifyNew != nil {
|
||||||
|
s.OnNotifyNew(userID)
|
||||||
|
}
|
||||||
|
return n.ID
|
||||||
}
|
}
|
||||||
|
|
||||||
// List 获取用户通知列表(分页,按时间倒序)
|
// List 获取用户通知列表(分页,按时间倒序)
|
||||||
@@ -52,7 +85,7 @@ func (s *NotificationService) List(userID uint, page, size int) ([]model.Notific
|
|||||||
var list []model.Notification
|
var list []model.Notification
|
||||||
offset := (page - 1) * size
|
offset := (page - 1) * size
|
||||||
if err := query.Order("created_at DESC").Offset(offset).Limit(size).
|
if err := query.Order("created_at DESC").Offset(offset).Limit(size).
|
||||||
Preload("Actor").Preload("Post").Find(&list).Error; err != nil {
|
Preload("Actor").Preload("Post").Preload("Room").Find(&list).Error; err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
return list, total, nil
|
return list, total, nil
|
||||||
|
|||||||
@@ -29,9 +29,11 @@ type PostListQuery struct {
|
|||||||
BoardID uint
|
BoardID uint
|
||||||
Page int
|
Page int
|
||||||
Size int
|
Size int
|
||||||
Sort string // latest | hot
|
Sort string // latest | hot | new
|
||||||
Keyword string // 搜索关键词
|
Keyword string // 搜索关键词
|
||||||
Recommended bool // 仅精华帖
|
Recommended bool // 仅精华帖
|
||||||
|
ViewerID uint // 当前查看者(0=游客)
|
||||||
|
Actor *Actor // 查看者权限快照;nil 仅 published
|
||||||
}
|
}
|
||||||
|
|
||||||
// toPostListItems 将 Post 模型批量转为不含正文的列表项
|
// toPostListItems 将 Post 模型批量转为不含正文的列表项
|
||||||
@@ -42,7 +44,7 @@ func toPostListItems(posts []model.Post) []PostListItem {
|
|||||||
ID: p.ID, BoardID: p.BoardID, UserID: p.UserID,
|
ID: p.ID, BoardID: p.BoardID, UserID: p.UserID,
|
||||||
Title: p.Title, Tags: p.Tags, PostType: p.PostType,
|
Title: p.Title, Tags: p.Tags, PostType: p.PostType,
|
||||||
Pinned: p.Pinned, Recommended: p.Recommended, LikeCount: p.LikeCount, ViewCount: p.ViewCount,
|
Pinned: p.Pinned, Recommended: p.Recommended, LikeCount: p.LikeCount, ViewCount: p.ViewCount,
|
||||||
CommentCount: p.CommentCount, CreatedAt: p.CreatedAt,
|
CommentCount: p.CommentCount, Status: p.Status, CreatedAt: p.CreatedAt,
|
||||||
Board: p.Board, User: p.User,
|
Board: p.Board, User: p.User,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -76,6 +78,7 @@ type PostListItem struct {
|
|||||||
LikeCount int `json:"like_count"`
|
LikeCount int `json:"like_count"`
|
||||||
ViewCount int `json:"view_count"`
|
ViewCount int `json:"view_count"`
|
||||||
CommentCount int `json:"comment_count"`
|
CommentCount int `json:"comment_count"`
|
||||||
|
Status string `json:"status"`
|
||||||
Liked bool `json:"liked"`
|
Liked bool `json:"liked"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
LastReply *LastReplyInfo `json:"last_reply,omitempty"`
|
LastReply *LastReplyInfo `json:"last_reply,omitempty"`
|
||||||
@@ -145,6 +148,26 @@ func (s *PostService) fillLastReply(items []PostListItem) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// applyListVisibility 公开流可见性:published,或 pending 且(作者本人 / 该板可审者)
|
||||||
|
func applyListVisibility(db *gorm.DB, viewerID uint, actor *Actor) *gorm.DB {
|
||||||
|
if viewerID == 0 || actor == nil {
|
||||||
|
return db.Where("status = ?", model.ContentStatusPublished)
|
||||||
|
}
|
||||||
|
if model.RoleLevel(actor.Role) >= model.RoleLevel(model.RoleAdmin) {
|
||||||
|
return db.Where("status IN ?", []string{model.ContentStatusPublished, model.ContentStatusPending})
|
||||||
|
}
|
||||||
|
if actor.Role == model.RoleBoardAdmin && len(actor.BoardIDs) > 0 {
|
||||||
|
return db.Where(
|
||||||
|
"status = ? OR (status = ? AND (user_id = ? OR board_id IN ?))",
|
||||||
|
model.ContentStatusPublished, model.ContentStatusPending, viewerID, actor.BoardIDs,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return db.Where(
|
||||||
|
"status = ? OR (status = ? AND user_id = ?)",
|
||||||
|
model.ContentStatusPublished, model.ContentStatusPending, viewerID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// List 获取帖子列表
|
// List 获取帖子列表
|
||||||
func (s *PostService) List(q PostListQuery) ([]PostListItem, int64, error) {
|
func (s *PostService) List(q PostListQuery) ([]PostListItem, int64, error) {
|
||||||
if q.Page < 1 {
|
if q.Page < 1 {
|
||||||
@@ -154,7 +177,7 @@ func (s *PostService) List(q PostListQuery) ([]PostListItem, int64, error) {
|
|||||||
q.Size = 20
|
q.Size = 20
|
||||||
}
|
}
|
||||||
|
|
||||||
query := s.db.Model(&model.Post{}).Where("status = ?", model.ContentStatusPublished)
|
query := applyListVisibility(s.db.Model(&model.Post{}), q.ViewerID, q.Actor)
|
||||||
if q.BoardID > 0 {
|
if q.BoardID > 0 {
|
||||||
query = query.Where("board_id = ?", q.BoardID)
|
query = query.Where("board_id = ?", q.BoardID)
|
||||||
}
|
}
|
||||||
@@ -196,15 +219,26 @@ func (s *PostService) List(q PostListQuery) ([]PostListItem, int64, error) {
|
|||||||
return items, total, nil
|
return items, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListByUser 获取指定用户发布的帖子(公开已发布)
|
// ListByUser 获取指定用户发布的帖子。
|
||||||
func (s *PostService) ListByUser(userID uint, page, size int) ([]PostListItem, int64, error) {
|
// viewer 为本人或全站可审者时并入 pending;板块管理员仅并入其授权板的 pending。
|
||||||
|
func (s *PostService) ListByUser(userID, viewerID uint, actor *Actor, page, size int) ([]PostListItem, int64, error) {
|
||||||
if page < 1 {
|
if page < 1 {
|
||||||
page = 1
|
page = 1
|
||||||
}
|
}
|
||||||
if size < 1 || size > 50 {
|
if size < 1 || size > 50 {
|
||||||
size = 20
|
size = 20
|
||||||
}
|
}
|
||||||
query := s.db.Model(&model.Post{}).Where("user_id = ? AND status = ?", userID, model.ContentStatusPublished)
|
query := s.db.Model(&model.Post{}).Where("user_id = ?", userID)
|
||||||
|
if viewerID == userID || (actor != nil && model.RoleLevel(actor.Role) >= model.RoleLevel(model.RoleAdmin)) {
|
||||||
|
query = query.Where("status IN ?", []string{model.ContentStatusPublished, model.ContentStatusPending})
|
||||||
|
} else if actor != nil && actor.Role == model.RoleBoardAdmin && len(actor.BoardIDs) > 0 {
|
||||||
|
query = query.Where(
|
||||||
|
"status = ? OR (status = ? AND board_id IN ?)",
|
||||||
|
model.ContentStatusPublished, model.ContentStatusPending, actor.BoardIDs,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
query = query.Where("status = ?", model.ContentStatusPublished)
|
||||||
|
}
|
||||||
var total int64
|
var total int64
|
||||||
if err := query.Count(&total).Error; err != nil {
|
if err := query.Count(&total).Error; err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
@@ -229,6 +263,15 @@ func (s *PostService) GetAuthorID(postID uint) (uint, error) {
|
|||||||
return post.UserID, nil
|
return post.UserID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetBoardID 获取帖子所属板块 ID(不增加浏览量)
|
||||||
|
func (s *PostService) GetBoardID(postID uint) (uint, error) {
|
||||||
|
var post model.Post
|
||||||
|
if err := s.db.Select("board_id").First(&post, postID).Error; err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return post.BoardID, nil
|
||||||
|
}
|
||||||
|
|
||||||
// CountByUser 统计用户发帖数
|
// CountByUser 统计用户发帖数
|
||||||
func (s *PostService) CountByUser(userID uint) (int64, error) {
|
func (s *PostService) CountByUser(userID uint) (int64, error) {
|
||||||
var total int64
|
var total int64
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ const (
|
|||||||
RateRegister = "register"
|
RateRegister = "register"
|
||||||
RatePost = "post"
|
RatePost = "post"
|
||||||
RateComment = "comment"
|
RateComment = "comment"
|
||||||
|
RateChat = "chat" // 群聊发消息
|
||||||
)
|
)
|
||||||
|
|
||||||
// DefaultRateLimiter 创建默认速率限制器
|
// DefaultRateLimiter 创建默认速率限制器
|
||||||
@@ -75,5 +76,6 @@ func DefaultRateLimiter() *RateLimiter {
|
|||||||
rl.SetLimit(RateRegister, 10) // 注册 10/分钟
|
rl.SetLimit(RateRegister, 10) // 注册 10/分钟
|
||||||
rl.SetLimit(RatePost, 10) // 发帖 10/分钟
|
rl.SetLimit(RatePost, 10) // 发帖 10/分钟
|
||||||
rl.SetLimit(RateComment, 30) // 评论 30/分钟
|
rl.SetLimit(RateComment, 30) // 评论 30/分钟
|
||||||
|
rl.SetLimit(RateChat, 30) // 群聊消息 30/分钟
|
||||||
return rl
|
return rl
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
isSuperOrOwner,
|
isSuperOrOwner,
|
||||||
type RoleUserLike,
|
type RoleUserLike,
|
||||||
} from "@/lib/roles";
|
} from "@/lib/roles";
|
||||||
|
import { realtime, RT_MODERATION_CHANGED } from "@/lib/realtime";
|
||||||
import Avatar from "@/components/Avatar";
|
import Avatar from "@/components/Avatar";
|
||||||
import RoleBadge from "@/components/RoleBadge";
|
import RoleBadge from "@/components/RoleBadge";
|
||||||
|
|
||||||
@@ -69,7 +70,7 @@ function isActive(pathname: string, href: string, exact?: boolean) {
|
|||||||
return exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);
|
return exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 待审核数量轮询(30 秒);仅内容审核入口可见时启用 */
|
/** 待审核数量:首屏 + WS 推送 + 回前台校准(无定时轮询) */
|
||||||
function usePendingCounts(enabled: boolean) {
|
function usePendingCounts(enabled: boolean) {
|
||||||
const [counts, setCounts] = useState({ posts: 0, comments: 0 });
|
const [counts, setCounts] = useState({ posts: 0, comments: 0 });
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -83,14 +84,14 @@ function usePendingCounts(enabled: boolean) {
|
|||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
};
|
};
|
||||||
load();
|
load();
|
||||||
const t = setInterval(load, 30_000);
|
const off = realtime.on(RT_MODERATION_CHANGED, () => load());
|
||||||
const onVisible = () => {
|
const onVisible = () => {
|
||||||
if (document.visibilityState === "visible") load();
|
if (document.visibilityState === "visible") load();
|
||||||
};
|
};
|
||||||
document.addEventListener("visibilitychange", onVisible);
|
document.addEventListener("visibilitychange", onVisible);
|
||||||
return () => {
|
return () => {
|
||||||
alive = false;
|
alive = false;
|
||||||
clearInterval(t);
|
off();
|
||||||
document.removeEventListener("visibilitychange", onVisible);
|
document.removeEventListener("visibilitychange", onVisible);
|
||||||
};
|
};
|
||||||
}, [enabled]);
|
}, [enabled]);
|
||||||
|
|||||||
@@ -2,21 +2,22 @@ import type { Metadata } from "next";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import {
|
import {
|
||||||
Users,
|
|
||||||
PenLine,
|
|
||||||
MessageCircle,
|
|
||||||
Activity,
|
|
||||||
Megaphone,
|
|
||||||
Palette,
|
|
||||||
ChevronRight,
|
|
||||||
UserPlus,
|
UserPlus,
|
||||||
LayoutGrid,
|
LayoutGrid,
|
||||||
ClipboardCheck,
|
ClipboardCheck,
|
||||||
|
ChevronRight,
|
||||||
|
MessageSquareText,
|
||||||
|
FileText,
|
||||||
|
Users,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { fetchOverview, type OverviewResponse } from "@/lib/api";
|
import {
|
||||||
|
fetchOverview,
|
||||||
|
fetchAdminPendingCounts,
|
||||||
|
type PendingCounts,
|
||||||
|
} from "@/lib/api";
|
||||||
import { authCookieHeader } from "@/lib/cookies";
|
import { authCookieHeader } from "@/lib/cookies";
|
||||||
import { getMeCached } from "@/lib/serverData";
|
import { getMeCached } from "@/lib/serverData";
|
||||||
import { canModerateAny, isAdminOrAbove, isSuperOrOwner } from "@/lib/roles";
|
import { canModerateAny, isSuperOrOwner } from "@/lib/roles";
|
||||||
import Avatar from "@/components/Avatar";
|
import Avatar from "@/components/Avatar";
|
||||||
import { formatRelative } from "@/lib/format";
|
import { formatRelative } from "@/lib/format";
|
||||||
|
|
||||||
@@ -24,7 +25,6 @@ export const metadata: Metadata = {
|
|||||||
title: "管理仪表盘",
|
title: "管理仪表盘",
|
||||||
};
|
};
|
||||||
|
|
||||||
// 精确千分位(管理员视角需要真实数值,不用首页的紧凑 K/M)
|
|
||||||
const fmt = (n: number) => n.toLocaleString("zh-CN");
|
const fmt = (n: number) => n.toLocaleString("zh-CN");
|
||||||
|
|
||||||
function greeting(hour: number) {
|
function greeting(hour: number) {
|
||||||
@@ -35,91 +35,6 @@ function greeting(hour: number) {
|
|||||||
return "晚上好";
|
return "晚上好";
|
||||||
}
|
}
|
||||||
|
|
||||||
// 统计 Bento 卡:总量 + 今日增量,语义色与全站令牌一致
|
|
||||||
function StatCard({
|
|
||||||
label,
|
|
||||||
value,
|
|
||||||
foot,
|
|
||||||
icon,
|
|
||||||
color,
|
|
||||||
soft,
|
|
||||||
}: {
|
|
||||||
label: string;
|
|
||||||
value: string;
|
|
||||||
foot: string;
|
|
||||||
icon: React.ReactNode;
|
|
||||||
color: string;
|
|
||||||
soft: string;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div className="panel p-4 sm:p-5">
|
|
||||||
<div className="flex items-start justify-between gap-2">
|
|
||||||
<p className="text-[12.5px] font-semibold" style={{ color: "var(--ink-3)" }}>
|
|
||||||
{label}
|
|
||||||
</p>
|
|
||||||
<span
|
|
||||||
className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
|
|
||||||
style={{ background: soft, color }}
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
{icon}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<p
|
|
||||||
className="mt-3 text-[26px] sm:text-[30px] font-extrabold tabular-nums leading-none tracking-tight"
|
|
||||||
style={{ color: "var(--ink)" }}
|
|
||||||
>
|
|
||||||
{value}
|
|
||||||
</p>
|
|
||||||
<p className="mt-2 text-[11.5px] sm:text-[12px] font-semibold" style={{ color: "var(--ink-3)" }}>
|
|
||||||
{foot}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 快捷管理入口:整卡可点(stretch-link),图标 + 标题 + 描述 + 箭头
|
|
||||||
function QuickLink({
|
|
||||||
href,
|
|
||||||
icon,
|
|
||||||
title,
|
|
||||||
desc,
|
|
||||||
soft,
|
|
||||||
color,
|
|
||||||
}: {
|
|
||||||
href: string;
|
|
||||||
icon: React.ReactNode;
|
|
||||||
title: string;
|
|
||||||
desc: string;
|
|
||||||
soft: string;
|
|
||||||
color: string;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<Link href={href} className="panel hover-lift relative block p-5 group">
|
|
||||||
<div className="flex items-start gap-3.5">
|
|
||||||
<span
|
|
||||||
className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0"
|
|
||||||
style={{ background: soft, color }}
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
{icon}
|
|
||||||
</span>
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<p className="text-[15px] font-extrabold" style={{ color: "var(--ink)" }}>
|
|
||||||
{title}
|
|
||||||
</p>
|
|
||||||
<p className="meta mt-1 text-[12.5px] leading-relaxed">{desc}</p>
|
|
||||||
</div>
|
|
||||||
<ChevronRight
|
|
||||||
size={17}
|
|
||||||
className="shrink-0 mt-1 transition-transform group-hover:translate-x-0.5"
|
|
||||||
style={{ color: "var(--ink-3)" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PanelHead({ title, extra }: { title: string; extra?: string }) {
|
function PanelHead({ title, extra }: { title: string; extra?: string }) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -138,12 +53,86 @@ function PanelHead({ title, extra }: { title: string; extra?: string }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 待办工作区:待审帖子 / 评论数量,整块进入审核页 */
|
||||||
|
function PendingWorkPanel({ counts }: { counts: PendingCounts }) {
|
||||||
|
const total = counts.posts + counts.comments;
|
||||||
|
const idle = total === 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
href="/admin/moderation"
|
||||||
|
className="panel hover-lift relative block p-4 sm:p-5 mb-4 group"
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3.5">
|
||||||
|
<span
|
||||||
|
className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0"
|
||||||
|
style={{
|
||||||
|
background: idle ? "var(--tint)" : "var(--ok-soft)",
|
||||||
|
color: idle ? "var(--ink-3)" : "var(--ok)",
|
||||||
|
}}
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<ClipboardCheck size={20} />
|
||||||
|
</span>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<p className="text-[15px] font-extrabold" style={{ color: "var(--ink)" }}>
|
||||||
|
内容审核
|
||||||
|
</p>
|
||||||
|
{idle ? (
|
||||||
|
<span
|
||||||
|
className="text-[11.5px] font-semibold px-2 py-0.5 rounded-full"
|
||||||
|
style={{ background: "var(--tint)", color: "var(--ink-3)" }}
|
||||||
|
>
|
||||||
|
暂无待审
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span
|
||||||
|
className="text-[11.5px] font-semibold px-2 py-0.5 rounded-full tabular-nums"
|
||||||
|
style={{ background: "var(--ok-soft)", color: "var(--ok)" }}
|
||||||
|
>
|
||||||
|
{fmt(total)} 项待处理
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex flex-wrap gap-3 sm:gap-5">
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-[13px]" style={{ color: "var(--ink-2)" }}>
|
||||||
|
<FileText size={14} style={{ color: "var(--ink-3)" }} aria-hidden="true" />
|
||||||
|
待审帖子
|
||||||
|
<strong className="tabular-nums font-extrabold" style={{ color: "var(--ink)" }}>
|
||||||
|
{fmt(counts.posts)}
|
||||||
|
</strong>
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-[13px]" style={{ color: "var(--ink-2)" }}>
|
||||||
|
<MessageSquareText size={14} style={{ color: "var(--ink-3)" }} aria-hidden="true" />
|
||||||
|
待审评论
|
||||||
|
<strong className="tabular-nums font-extrabold" style={{ color: "var(--ink)" }}>
|
||||||
|
{fmt(counts.comments)}
|
||||||
|
</strong>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ChevronRight
|
||||||
|
size={18}
|
||||||
|
className="shrink-0 mt-1 transition-transform group-hover:translate-x-0.5"
|
||||||
|
style={{ color: "var(--ink-3)" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default async function AdminDashboardPage() {
|
export default async function AdminDashboardPage() {
|
||||||
const cookie = authCookieHeader(await cookies());
|
const cookie = authCookieHeader(await cookies());
|
||||||
// 与 layout 的 /me 请求共享 React cache;概览失败降级,不阻塞仪表盘骨架
|
const me = await getMeCached(cookie || undefined);
|
||||||
const [me, overview] = await Promise.all([
|
const canMod = canModerateAny(me.user);
|
||||||
getMeCached(cookie || undefined),
|
const canUsers = isSuperOrOwner(me.user?.role);
|
||||||
|
|
||||||
|
const [overview, pendingCounts] = await Promise.all([
|
||||||
fetchOverview(cookie).catch(() => null),
|
fetchOverview(cookie).catch(() => null),
|
||||||
|
canMod
|
||||||
|
? fetchAdminPendingCounts(cookie).catch(() => ({ posts: 0, comments: 0 }))
|
||||||
|
: Promise.resolve(null),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
@@ -162,100 +151,24 @@ export default async function AdminDashboardPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{/* 页头 */}
|
|
||||||
<div className="mb-5">
|
<div className="mb-5">
|
||||||
<h1 className="text-[22px] sm:text-[26px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
|
<h1
|
||||||
|
className="text-[22px] sm:text-[26px] font-extrabold tracking-tight"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
>
|
||||||
{greeting(now.getHours())},{me.user?.nickname}
|
{greeting(now.getHours())},{me.user?.nickname}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="meta mt-1.5 text-[12.5px]">{dateLabel} · 这里是站点运营全貌</p>
|
<p className="meta mt-1.5 text-[12.5px]">{dateLabel} · 站点管理</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 统计 Bento */}
|
{canMod && pendingCounts && <PendingWorkPanel counts={pendingCounts} />}
|
||||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
|
|
||||||
<StatCard
|
|
||||||
label="注册用户"
|
|
||||||
value={stats ? fmt(stats.users) : "—"}
|
|
||||||
foot={stats ? `今日新增 +${fmt(stats.today_users)}` : "统计暂不可用"}
|
|
||||||
icon={<Users size={16} />}
|
|
||||||
color="var(--accent)"
|
|
||||||
soft="var(--accent-soft)"
|
|
||||||
/>
|
|
||||||
<StatCard
|
|
||||||
label="话题总数"
|
|
||||||
value={stats ? fmt(stats.posts) : "—"}
|
|
||||||
foot={stats ? `今日新发 +${fmt(stats.today_posts)}` : "统计暂不可用"}
|
|
||||||
icon={<PenLine size={16} />}
|
|
||||||
color="var(--clay)"
|
|
||||||
soft="var(--clay-soft)"
|
|
||||||
/>
|
|
||||||
<StatCard
|
|
||||||
label="回复总数"
|
|
||||||
value={stats ? fmt(stats.comments) : "—"}
|
|
||||||
foot={stats ? `今日新增 +${fmt(stats.today_comments)}` : "统计暂不可用"}
|
|
||||||
icon={<MessageCircle size={16} />}
|
|
||||||
color="var(--ok)"
|
|
||||||
soft="var(--ok-soft)"
|
|
||||||
/>
|
|
||||||
<StatCard
|
|
||||||
label="在线用户"
|
|
||||||
value={stats ? fmt(stats.online) : "—"}
|
|
||||||
foot={stats ? `近 5 分钟活跃 · 峰值 ${fmt(stats.peak_online)}` : "统计暂不可用"}
|
|
||||||
icon={<Activity size={16} />}
|
|
||||||
color="var(--gold)"
|
|
||||||
soft="var(--gold-soft)"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 快捷入口(按角色权限过滤,与侧边栏一致;后端路由另有守卫) */}
|
<div className="grid lg:grid-cols-2 gap-4 items-start">
|
||||||
<h2 className="sr-only">快捷管理</h2>
|
|
||||||
<div className="grid sm:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4 mt-4">
|
|
||||||
{canModerateAny(me.user) && (
|
|
||||||
<QuickLink
|
|
||||||
href="/admin/moderation"
|
|
||||||
icon={<ClipboardCheck size={18} />}
|
|
||||||
title="内容审核"
|
|
||||||
desc="审核普通用户提交的帖子与评论,通过后内容公开可见"
|
|
||||||
soft="var(--ok-soft)"
|
|
||||||
color="var(--ok)"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{isAdminOrAbove(me.user?.role) && (
|
|
||||||
<QuickLink
|
|
||||||
href="/admin/announcements"
|
|
||||||
icon={<Megaphone size={18} />}
|
|
||||||
title="公告管理"
|
|
||||||
desc="发布、编辑与下线站点公告,支持标签颜色与草稿状态"
|
|
||||||
soft="var(--clay-soft)"
|
|
||||||
color="var(--clay)"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{isSuperOrOwner(me.user?.role) && (
|
|
||||||
<QuickLink
|
|
||||||
href="/admin/users"
|
|
||||||
icon={<Users size={18} />}
|
|
||||||
title="用户权限"
|
|
||||||
desc="查看全站成员,授予管理角色与板块授权,封禁违规账号"
|
|
||||||
soft="var(--accent-soft)"
|
|
||||||
color="var(--accent)"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{isSuperOrOwner(me.user?.role) && (
|
|
||||||
<QuickLink
|
|
||||||
href="/admin/appearance"
|
|
||||||
icon={<Palette size={18} />}
|
|
||||||
title="外观设置"
|
|
||||||
desc="配置全站主题强调色,实时预览后保存并对所有用户生效"
|
|
||||||
soft="var(--gold-soft)"
|
|
||||||
color="var(--gold)"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 成员与板块 */}
|
|
||||||
<div className="grid lg:grid-cols-2 gap-4 mt-4 items-start">
|
|
||||||
{/* 最新注册成员 */}
|
|
||||||
<div className="panel overflow-hidden">
|
<div className="panel overflow-hidden">
|
||||||
<PanelHead title="最新注册成员" extra={stats ? `共 ${fmt(stats.users)} 人` : undefined} />
|
<PanelHead
|
||||||
|
title="最新注册成员"
|
||||||
|
extra={stats ? `共 ${fmt(stats.users)} 人` : undefined}
|
||||||
|
/>
|
||||||
{newUsers.length === 0 ? (
|
{newUsers.length === 0 ? (
|
||||||
<p className="meta text-center py-14 text-[13px]">暂无成员数据</p>
|
<p className="meta text-center py-14 text-[13px]">暂无成员数据</p>
|
||||||
) : (
|
) : (
|
||||||
@@ -266,12 +179,22 @@ export default async function AdminDashboardPage() {
|
|||||||
className="flex items-center gap-3 px-4 sm:px-5 py-3 transition-colors hover:bg-[var(--panel-2)]"
|
className="flex items-center gap-3 px-4 sm:px-5 py-3 transition-colors hover:bg-[var(--panel-2)]"
|
||||||
style={{ borderTop: "1px solid var(--line)" }}
|
style={{ borderTop: "1px solid var(--line)" }}
|
||||||
>
|
>
|
||||||
<Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={34} />
|
<Avatar
|
||||||
|
name={u.nickname || u.username}
|
||||||
|
src={u.avatar || undefined}
|
||||||
|
size={34}
|
||||||
|
/>
|
||||||
<span className="min-w-0 flex-1 leading-tight">
|
<span className="min-w-0 flex-1 leading-tight">
|
||||||
<span className="block text-[13.5px] font-bold truncate" style={{ color: "var(--ink)" }}>
|
<span
|
||||||
|
className="block text-[13.5px] font-bold truncate"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
>
|
||||||
{u.nickname}
|
{u.nickname}
|
||||||
</span>
|
</span>
|
||||||
<span className="block text-[11.5px] truncate" style={{ color: "var(--ink-3)" }}>
|
<span
|
||||||
|
className="block text-[11.5px] truncate"
|
||||||
|
style={{ color: "var(--ink-3)" }}
|
||||||
|
>
|
||||||
@{u.username}
|
@{u.username}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
@@ -285,9 +208,22 @@ export default async function AdminDashboardPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
|
{canUsers && (
|
||||||
|
<Link
|
||||||
|
href="/admin/users"
|
||||||
|
className="flex items-center justify-center gap-1.5 px-4 py-3 text-[13px] font-semibold transition-colors hover:bg-[var(--panel-2)]"
|
||||||
|
style={{
|
||||||
|
borderTop: "1px solid var(--line)",
|
||||||
|
color: "var(--accent)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Users size={14} aria-hidden="true" />
|
||||||
|
前往用户权限
|
||||||
|
<ChevronRight size={14} aria-hidden="true" />
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 板块分布 */}
|
|
||||||
<div className="panel overflow-hidden">
|
<div className="panel overflow-hidden">
|
||||||
<PanelHead title="板块话题分布" extra={`${boards.length} 个板块`} />
|
<PanelHead title="板块话题分布" extra={`${boards.length} 个板块`} />
|
||||||
{topBoards.length === 0 ? (
|
{topBoards.length === 0 ? (
|
||||||
@@ -309,14 +245,19 @@ export default async function AdminDashboardPage() {
|
|||||||
</span>
|
</span>
|
||||||
<span className="min-w-0 flex-1">
|
<span className="min-w-0 flex-1">
|
||||||
<span className="flex items-center justify-between gap-2">
|
<span className="flex items-center justify-between gap-2">
|
||||||
<span className="text-[13.5px] font-bold truncate" style={{ color: "var(--ink)" }}>
|
<span
|
||||||
|
className="text-[13.5px] font-bold truncate"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
>
|
||||||
{b.name}
|
{b.name}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-[12px] font-bold tabular-nums shrink-0" style={{ color: "var(--ink-2)" }}>
|
<span
|
||||||
|
className="text-[12px] font-bold tabular-nums shrink-0"
|
||||||
|
style={{ color: "var(--ink-2)" }}
|
||||||
|
>
|
||||||
{fmt(b.post_count)}
|
{fmt(b.post_count)}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
{/* 相对占比迷你条(纯装饰) */}
|
|
||||||
<span
|
<span
|
||||||
className="block mt-1.5 h-1 rounded-full overflow-hidden"
|
className="block mt-1.5 h-1 rounded-full overflow-hidden"
|
||||||
style={{ background: "var(--tint)" }}
|
style={{ background: "var(--tint)" }}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
ChevronRight,
|
ChevronRight,
|
||||||
Clock,
|
Clock,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
|
FolderSearch,
|
||||||
History,
|
History,
|
||||||
Loader2,
|
Loader2,
|
||||||
Monitor,
|
Monitor,
|
||||||
@@ -31,9 +32,10 @@ import {
|
|||||||
type Board,
|
type Board,
|
||||||
type LoginLog,
|
type LoginLog,
|
||||||
} from "@/lib/api";
|
} from "@/lib/api";
|
||||||
import { ROLES } from "@/lib/roles";
|
import { isOwner, ROLES } from "@/lib/roles";
|
||||||
import { formatDate, formatRelative } from "@/lib/format";
|
import { formatDate, formatRelative } from "@/lib/format";
|
||||||
import { toast } from "@/lib/toast";
|
import { toast } from "@/lib/toast";
|
||||||
|
import { realtime } from "@/lib/realtime";
|
||||||
import Avatar from "@/components/Avatar";
|
import Avatar from "@/components/Avatar";
|
||||||
import RoleBadge from "@/components/RoleBadge";
|
import RoleBadge from "@/components/RoleBadge";
|
||||||
|
|
||||||
@@ -156,6 +158,24 @@ export default function UsersAdmin({
|
|||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// 在线状态实时化:WS hello 全量快照校正当前页绿点,之后 presence:update 增量跳变;
|
||||||
|
// 后端在线判定(有活跃 WS 连接)比列表接口的 5 分钟 last_seen 启发式更精确
|
||||||
|
useEffect(() => {
|
||||||
|
const reconcile = (ids: ReadonlySet<number>) => {
|
||||||
|
if (ids.size === 0) return;
|
||||||
|
setUsers((prev) =>
|
||||||
|
prev.map((u) => (u.online === ids.has(u.id) ? u : { ...u, online: ids.has(u.id) }))
|
||||||
|
);
|
||||||
|
};
|
||||||
|
reconcile(realtime.getOnlineIds());
|
||||||
|
const off = realtime.onPresence(({ user_id: id, online }) => {
|
||||||
|
setUsers((prev) =>
|
||||||
|
prev.map((u) => (u.id === id && u.online !== online ? { ...u, online } : u))
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return off;
|
||||||
|
}, []);
|
||||||
|
|
||||||
const load = useCallback(async (opts: { page: number; filter: UserFilter; q: string }) => {
|
const load = useCallback(async (opts: { page: number; filter: UserFilter; q: string }) => {
|
||||||
const seq = ++seqRef.current;
|
const seq = ++seqRef.current;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -319,10 +339,24 @@ export default function UsersAdmin({
|
|||||||
);
|
);
|
||||||
|
|
||||||
const renderActions = (u: AdminUser, isSelf: boolean) => {
|
const renderActions = (u: AdminUser, isSelf: boolean) => {
|
||||||
// 站长账号:任何人不可操作(后端 403 兜底),仅保留主页入口与站长标识
|
const canAudit = isOwner(currentUserRole);
|
||||||
|
const auditBtn = canAudit ? (
|
||||||
|
<Link
|
||||||
|
href={`/admin/users/${u.id}`}
|
||||||
|
title="内容档案"
|
||||||
|
aria-label={`查看 ${u.username} 的内容档案`}
|
||||||
|
className={ghostBtn}
|
||||||
|
style={{ color: "var(--accent)" }}
|
||||||
|
>
|
||||||
|
<FolderSearch size={15} />
|
||||||
|
</Link>
|
||||||
|
) : null;
|
||||||
|
|
||||||
|
// 站长账号:不可改角色/封禁,保留主页与(站长自己的)内容档案
|
||||||
if (u.role === ROLES.OWNER) {
|
if (u.role === ROLES.OWNER) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-1 justify-end">
|
<div className="flex items-center gap-1 justify-end">
|
||||||
|
{auditBtn}
|
||||||
<Link
|
<Link
|
||||||
href={`/u/${u.id}`}
|
href={`/u/${u.id}`}
|
||||||
title="查看个人主页"
|
title="查看个人主页"
|
||||||
@@ -336,17 +370,21 @@ export default function UsersAdmin({
|
|||||||
}
|
}
|
||||||
if (isSelf) {
|
if (isSelf) {
|
||||||
return (
|
return (
|
||||||
<span
|
<div className="flex items-center gap-1 justify-end">
|
||||||
className="inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold whitespace-nowrap"
|
{auditBtn}
|
||||||
style={{ background: "var(--panel-2)", color: "var(--ink-3)" }}
|
<span
|
||||||
>
|
className="inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold whitespace-nowrap"
|
||||||
当前账号
|
style={{ background: "var(--panel-2)", color: "var(--ink-3)" }}
|
||||||
</span>
|
>
|
||||||
|
当前账号
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const busy = actingId === u.id;
|
const busy = actingId === u.id;
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-1 justify-end">
|
<div className="flex items-center gap-1 justify-end">
|
||||||
|
{auditBtn}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
title="登录历史"
|
title="登录历史"
|
||||||
@@ -623,7 +661,11 @@ export default function UsersAdmin({
|
|||||||
</div>
|
</div>
|
||||||
<div className="min-w-0">{renderLastLogin(u)}</div>
|
<div className="min-w-0">{renderLastLogin(u)}</div>
|
||||||
<div className="hidden xl:block">
|
<div className="hidden xl:block">
|
||||||
<p className="text-[12.5px] font-semibold tabular-nums" style={{ color: "var(--ink-2)" }}>
|
<p
|
||||||
|
className="text-[12.5px] font-semibold tabular-nums"
|
||||||
|
style={{ color: "var(--ink-2)" }}
|
||||||
|
title="仅统计已发布内容;驳回/删除见内容档案"
|
||||||
|
>
|
||||||
帖 {u.post_count} · 评 {u.comment_count}
|
帖 {u.post_count} · 评 {u.comment_count}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-[11px] tabular-nums" style={{ color: "var(--ink-3)" }}>
|
<p className="text-[11px] tabular-nums" style={{ color: "var(--ink-3)" }}>
|
||||||
@@ -661,7 +703,11 @@ export default function UsersAdmin({
|
|||||||
</div>
|
</div>
|
||||||
{renderStatus(u)}
|
{renderStatus(u)}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-2.5 text-[11.5px] tabular-nums" style={{ color: "var(--ink-3)" }}>
|
<p
|
||||||
|
className="mt-2.5 text-[11.5px] tabular-nums"
|
||||||
|
style={{ color: "var(--ink-3)" }}
|
||||||
|
title="仅统计已发布内容;驳回/删除见内容档案"
|
||||||
|
>
|
||||||
帖 {u.post_count} · 评 {u.comment_count} · 注册 {formatDate(u.created_at)}
|
帖 {u.post_count} · 评 {u.comment_count} · 注册 {formatDate(u.created_at)}
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-1 text-[11.5px] tabular-nums flex items-center gap-1.5" style={{ color: "var(--ink-3)" }}>
|
<p className="mt-1 text-[11.5px] tabular-nums flex items-center gap-1.5" style={{ color: "var(--ink-3)" }}>
|
||||||
@@ -671,37 +717,49 @@ export default function UsersAdmin({
|
|||||||
{u.last_login_at ? ` · ${formatRelative(u.last_login_at)}` : ""}
|
{u.last_login_at ? ` · ${formatRelative(u.last_login_at)}` : ""}
|
||||||
</button>
|
</button>
|
||||||
</p>
|
</p>
|
||||||
{!isSelf && u.role !== ROLES.OWNER && (
|
<div className="flex items-center gap-2 mt-3 flex-wrap">
|
||||||
<div className="flex items-center gap-2 mt-3 flex-wrap">
|
{isOwner(currentUserRole) && (
|
||||||
|
<Link href={`/admin/users/${u.id}`} className="btn btn-line btn-sm">
|
||||||
|
<FolderSearch size={13} /> 内容档案
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{(isSelf || u.role === ROLES.OWNER) && (
|
||||||
<Link href={`/u/${u.id}`} className="btn btn-line btn-sm">
|
<Link href={`/u/${u.id}`} className="btn btn-line btn-sm">
|
||||||
<ExternalLink size={13} /> 主页
|
<ExternalLink size={13} /> 主页
|
||||||
</Link>
|
</Link>
|
||||||
<button
|
)}
|
||||||
type="button"
|
{!isSelf && u.role !== ROLES.OWNER && (
|
||||||
disabled={actingId === u.id}
|
<>
|
||||||
onClick={() => setRoleTarget(u)}
|
<Link href={`/u/${u.id}`} className="btn btn-line btn-sm">
|
||||||
className="btn btn-line btn-sm"
|
<ExternalLink size={13} /> 主页
|
||||||
style={u.role !== ROLES.USER ? { color: "var(--accent)", borderColor: "var(--accent)" } : undefined}
|
</Link>
|
||||||
>
|
<button
|
||||||
<ShieldCheck size={13} />
|
type="button"
|
||||||
角色权限
|
disabled={actingId === u.id}
|
||||||
</button>
|
onClick={() => setRoleTarget(u)}
|
||||||
<button
|
className="btn btn-line btn-sm"
|
||||||
type="button"
|
style={u.role !== ROLES.USER ? { color: "var(--accent)", borderColor: "var(--accent)" } : undefined}
|
||||||
disabled={actingId === u.id}
|
>
|
||||||
onClick={() => setBanTarget(u)}
|
<ShieldCheck size={13} />
|
||||||
className="btn btn-sm"
|
角色权限
|
||||||
style={
|
</button>
|
||||||
u.banned
|
<button
|
||||||
? { background: "var(--ok-soft)", color: "var(--ok)" }
|
type="button"
|
||||||
: { background: "var(--danger-soft)", color: "var(--danger)" }
|
disabled={actingId === u.id}
|
||||||
}
|
onClick={() => setBanTarget(u)}
|
||||||
>
|
className="btn btn-sm"
|
||||||
{u.banned ? <RotateCcw size={13} /> : <Ban size={13} />}
|
style={
|
||||||
{u.banned ? "解封" : "封禁"}
|
u.banned
|
||||||
</button>
|
? { background: "var(--ok-soft)", color: "var(--ok)" }
|
||||||
</div>
|
: { background: "var(--danger-soft)", color: "var(--danger)" }
|
||||||
)}
|
}
|
||||||
|
>
|
||||||
|
{u.banned ? <RotateCcw size={13} /> : <Ban size={13} />}
|
||||||
|
{u.banned ? "解封" : "封禁"}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
400
frontend/app/admin/users/[id]/UserAuditClient.tsx
Normal file
400
frontend/app/admin/users/[id]/UserAuditClient.tsx
Normal file
@@ -0,0 +1,400 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import {
|
||||||
|
ArrowLeft,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
ExternalLink,
|
||||||
|
FileText,
|
||||||
|
Loader2,
|
||||||
|
MessageCircle,
|
||||||
|
MessagesSquare,
|
||||||
|
} from "lucide-react";
|
||||||
|
import {
|
||||||
|
apiAdminUserAuditComments,
|
||||||
|
apiAdminUserAuditMessages,
|
||||||
|
apiAdminUserAuditPosts,
|
||||||
|
type AdminAuditCommentItem,
|
||||||
|
type AdminAuditMessageItem,
|
||||||
|
type AdminAuditPostItem,
|
||||||
|
type AdminUserAuditProfile,
|
||||||
|
} from "@/lib/api";
|
||||||
|
import { formatDate, formatRelative } from "@/lib/format";
|
||||||
|
import Avatar from "@/components/Avatar";
|
||||||
|
import RoleBadge from "@/components/RoleBadge";
|
||||||
|
|
||||||
|
type TabKey = "posts" | "comments" | "messages";
|
||||||
|
|
||||||
|
const TABS: { key: TabKey; label: string; icon: React.ReactNode }[] = [
|
||||||
|
{ key: "posts", label: "帖子", icon: <FileText size={14} /> },
|
||||||
|
{ key: "comments", label: "评论", icon: <MessageCircle size={14} /> },
|
||||||
|
{ key: "messages", label: "私信与群消息", icon: <MessagesSquare size={14} /> },
|
||||||
|
];
|
||||||
|
|
||||||
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
|
function StatusChip({
|
||||||
|
status,
|
||||||
|
deleted,
|
||||||
|
recalled,
|
||||||
|
}: {
|
||||||
|
status?: string;
|
||||||
|
deleted?: boolean;
|
||||||
|
recalled?: boolean;
|
||||||
|
}) {
|
||||||
|
const chips: { label: string; color: string; soft: string }[] = [];
|
||||||
|
if (deleted) chips.push({ label: "已删除", color: "var(--danger)", soft: "var(--danger-soft)" });
|
||||||
|
if (recalled) chips.push({ label: "已撤回", color: "var(--ink-3)", soft: "var(--tint)" });
|
||||||
|
if (status === "pending") chips.push({ label: "待审", color: "var(--gold)", soft: "var(--gold-soft)" });
|
||||||
|
if (status === "rejected") chips.push({ label: "已驳回", color: "var(--danger)", soft: "var(--danger-soft)" });
|
||||||
|
if (status === "published" && !deleted) {
|
||||||
|
chips.push({ label: "已发布", color: "var(--ok)", soft: "var(--ok-soft)" });
|
||||||
|
}
|
||||||
|
if (chips.length === 0 && !recalled) {
|
||||||
|
chips.push({ label: "正常", color: "var(--ink-3)", soft: "var(--tint)" });
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className="inline-flex flex-wrap gap-1">
|
||||||
|
{chips.map((c) => (
|
||||||
|
<span
|
||||||
|
key={c.label}
|
||||||
|
className="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-bold"
|
||||||
|
style={{ background: c.soft, color: c.color }}
|
||||||
|
>
|
||||||
|
{c.label}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Pager({
|
||||||
|
page,
|
||||||
|
total,
|
||||||
|
onChange,
|
||||||
|
loading,
|
||||||
|
}: {
|
||||||
|
page: number;
|
||||||
|
total: number;
|
||||||
|
onChange: (p: number) => void;
|
||||||
|
loading?: boolean;
|
||||||
|
}) {
|
||||||
|
const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||||
|
if (pages <= 1) return null;
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center gap-2 py-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={page <= 1 || loading}
|
||||||
|
onClick={() => onChange(page - 1)}
|
||||||
|
className="btn btn-line btn-sm"
|
||||||
|
aria-label="上一页"
|
||||||
|
>
|
||||||
|
<ChevronLeft size={14} />
|
||||||
|
</button>
|
||||||
|
<span className="text-[12.5px] tabular-nums meta">
|
||||||
|
{page} / {pages}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={page >= pages || loading}
|
||||||
|
onClick={() => onChange(page + 1)}
|
||||||
|
className="btn btn-line btn-sm"
|
||||||
|
aria-label="下一页"
|
||||||
|
>
|
||||||
|
<ChevronRight size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function UserAuditClient({
|
||||||
|
userId,
|
||||||
|
initial,
|
||||||
|
}: {
|
||||||
|
userId: number;
|
||||||
|
initial: AdminUserAuditProfile;
|
||||||
|
}) {
|
||||||
|
const [profile] = useState(initial);
|
||||||
|
const [tab, setTab] = useState<TabKey>("posts");
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [posts, setPosts] = useState<AdminAuditPostItem[]>([]);
|
||||||
|
const [comments, setComments] = useState<AdminAuditCommentItem[]>([]);
|
||||||
|
const [messages, setMessages] = useState<AdminAuditMessageItem[]>([]);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
|
||||||
|
const u = profile.user;
|
||||||
|
|
||||||
|
const load = useCallback(
|
||||||
|
async (t: TabKey, p: number) => {
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
if (t === "posts") {
|
||||||
|
const res = await apiAdminUserAuditPosts(userId, p);
|
||||||
|
setPosts(res.items || []);
|
||||||
|
setTotal(res.total);
|
||||||
|
} else if (t === "comments") {
|
||||||
|
const res = await apiAdminUserAuditComments(userId, p);
|
||||||
|
setComments(res.items || []);
|
||||||
|
setTotal(res.total);
|
||||||
|
} else {
|
||||||
|
const res = await apiAdminUserAuditMessages(userId, p);
|
||||||
|
setMessages(res.items || []);
|
||||||
|
setTotal(res.total);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "加载失败");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load(tab, page);
|
||||||
|
}, [tab, page, load]);
|
||||||
|
|
||||||
|
const switchTab = (t: TabKey) => {
|
||||||
|
setTab(t);
|
||||||
|
setPage(1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tabCount = (t: TabKey) => {
|
||||||
|
if (t === "posts") return profile.posts_total;
|
||||||
|
if (t === "comments") return profile.comments_total;
|
||||||
|
return profile.messages_total;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Link
|
||||||
|
href="/admin/users"
|
||||||
|
className="inline-flex items-center gap-1.5 text-[13px] font-semibold mb-4 hover:opacity-80"
|
||||||
|
style={{ color: "var(--accent)" }}
|
||||||
|
>
|
||||||
|
<ArrowLeft size={14} />
|
||||||
|
返回用户列表
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<div className="panel p-4 sm:p-5 mb-4">
|
||||||
|
<div className="flex items-start gap-3.5">
|
||||||
|
<Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={48} />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<h1
|
||||||
|
className="text-[18px] sm:text-[20px] font-extrabold truncate"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
>
|
||||||
|
{u.nickname}
|
||||||
|
</h1>
|
||||||
|
<RoleBadge role={u.role} />
|
||||||
|
{u.banned && (
|
||||||
|
<span
|
||||||
|
className="text-[11px] font-bold px-2 py-0.5 rounded-full"
|
||||||
|
style={{ background: "var(--danger-soft)", color: "var(--danger)" }}
|
||||||
|
>
|
||||||
|
已封禁
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="meta text-[12.5px] mt-0.5 truncate">@{u.username}</p>
|
||||||
|
<p className="meta text-[12px] mt-2">
|
||||||
|
注册于 {formatDate(u.created_at)} · 已发布帖 {profile.published_posts} / 评{" "}
|
||||||
|
{profile.published_comments}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
href={`/u/${u.id}`}
|
||||||
|
className="btn btn-line btn-sm gap-1.5 shrink-0"
|
||||||
|
target="_blank"
|
||||||
|
>
|
||||||
|
<ExternalLink size={13} />
|
||||||
|
主页
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="mt-4 grid grid-cols-3 gap-2 sm:gap-3 pt-4"
|
||||||
|
style={{ borderTop: "1px solid var(--line)" }}
|
||||||
|
>
|
||||||
|
{[
|
||||||
|
{ label: "全部帖子", value: profile.posts_total },
|
||||||
|
{ label: "全部评论", value: profile.comments_total },
|
||||||
|
{ label: "全部消息", value: profile.messages_total },
|
||||||
|
].map((c) => (
|
||||||
|
<div key={c.label} className="text-center">
|
||||||
|
<p
|
||||||
|
className="text-[20px] font-extrabold tabular-nums leading-none"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
>
|
||||||
|
{c.value.toLocaleString("zh-CN")}
|
||||||
|
</p>
|
||||||
|
<p className="meta text-[11.5px] mt-1.5">{c.label}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className="flex gap-1 mb-3 overflow-x-auto"
|
||||||
|
style={{ borderBottom: "1px solid var(--line)" }}
|
||||||
|
>
|
||||||
|
{TABS.map((t) => {
|
||||||
|
const active = tab === t.key;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={t.key}
|
||||||
|
type="button"
|
||||||
|
onClick={() => switchTab(t.key)}
|
||||||
|
className="inline-flex items-center gap-1.5 px-3 py-2.5 text-[13px] font-bold whitespace-nowrap -mb-px"
|
||||||
|
style={{
|
||||||
|
color: active ? "var(--accent)" : "var(--ink-3)",
|
||||||
|
borderBottom: active ? "2px solid var(--accent)" : "2px solid transparent",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t.icon}
|
||||||
|
{t.label}
|
||||||
|
<span className="tabular-nums font-semibold opacity-70">
|
||||||
|
{tabCount(t.key).toLocaleString("zh-CN")}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="panel overflow-hidden">
|
||||||
|
{error && (
|
||||||
|
<p className="text-center py-10 text-[13px]" style={{ color: "var(--danger)" }}>
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!error && loading && posts.length + comments.length + messages.length === 0 && (
|
||||||
|
<div className="flex justify-center py-14" style={{ color: "var(--ink-3)" }}>
|
||||||
|
<Loader2 size={22} className="animate-spin" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!error && !loading && total === 0 && (
|
||||||
|
<p className="meta text-center py-14 text-[13px]">该分类暂无内容</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === "posts" &&
|
||||||
|
posts.map((p) => (
|
||||||
|
<div
|
||||||
|
key={p.id}
|
||||||
|
className="px-4 sm:px-5 py-3.5"
|
||||||
|
style={{ borderTop: "1px solid var(--line)" }}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap mb-1">
|
||||||
|
<StatusChip status={p.status} deleted={p.deleted} />
|
||||||
|
{p.board_name && (
|
||||||
|
<span className="text-[11.5px] meta truncate">{p.board_name}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{p.deleted ? (
|
||||||
|
<p className="text-[14px] font-bold" style={{ color: "var(--ink-3)" }}>
|
||||||
|
{p.title || "(无标题)"}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<Link
|
||||||
|
href={`/post/${p.id}`}
|
||||||
|
className="text-[14px] font-bold hover:underline"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
>
|
||||||
|
{p.title || "(无标题)"}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{p.content && (
|
||||||
|
<p className="meta text-[12.5px] mt-1 line-clamp-2 leading-relaxed">
|
||||||
|
{p.content}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span className="shrink-0 text-[11.5px] meta tabular-nums">
|
||||||
|
{formatRelative(p.created_at)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{tab === "comments" &&
|
||||||
|
comments.map((c) => (
|
||||||
|
<div
|
||||||
|
key={c.id}
|
||||||
|
className="px-4 sm:px-5 py-3.5"
|
||||||
|
style={{ borderTop: "1px solid var(--line)" }}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap mb-1">
|
||||||
|
<StatusChip status={c.status} deleted={c.deleted} />
|
||||||
|
{c.deleted ? (
|
||||||
|
<span className="text-[11.5px] meta">帖子 #{c.post_id}</span>
|
||||||
|
) : (
|
||||||
|
<Link
|
||||||
|
href={`/post/${c.post_id}`}
|
||||||
|
className="text-[11.5px] font-semibold hover:underline"
|
||||||
|
style={{ color: "var(--accent)" }}
|
||||||
|
>
|
||||||
|
帖子 #{c.post_id}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p
|
||||||
|
className="text-[13.5px] leading-relaxed whitespace-pre-wrap break-words"
|
||||||
|
style={{ color: c.deleted ? "var(--ink-3)" : "var(--ink)" }}
|
||||||
|
>
|
||||||
|
{c.content || "(空)"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span className="shrink-0 text-[11.5px] meta tabular-nums">
|
||||||
|
{formatRelative(c.created_at)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{tab === "messages" &&
|
||||||
|
messages.map((m) => (
|
||||||
|
<div
|
||||||
|
key={m.id}
|
||||||
|
className="px-4 sm:px-5 py-3.5"
|
||||||
|
style={{ borderTop: "1px solid var(--line)" }}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap mb-1">
|
||||||
|
<StatusChip deleted={m.deleted} recalled={m.recalled} />
|
||||||
|
<span className="text-[11.5px] meta truncate">
|
||||||
|
{m.room_name}
|
||||||
|
{m.room_type === "direct" ? " · 私聊" : m.room_type === "group" ? " · 群聊" : ""}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p
|
||||||
|
className="text-[13.5px] leading-relaxed whitespace-pre-wrap break-words"
|
||||||
|
style={{
|
||||||
|
color: m.recalled || m.deleted ? "var(--ink-3)" : "var(--ink)",
|
||||||
|
fontStyle: m.recalled ? "italic" : undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{m.content || "(空)"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span className="shrink-0 text-[11.5px] meta tabular-nums">
|
||||||
|
{formatRelative(m.created_at)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Pager page={page} total={total} onChange={setPage} loading={loading} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
44
frontend/app/admin/users/[id]/page.tsx
Normal file
44
frontend/app/admin/users/[id]/page.tsx
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { authCookieHeader } from "@/lib/cookies";
|
||||||
|
import { fetchAdminUserAudit } from "@/lib/api";
|
||||||
|
import { getMeCached } from "@/lib/serverData";
|
||||||
|
import { isOwner, isSuperOrOwner } from "@/lib/roles";
|
||||||
|
import Forbidden from "../../Forbidden";
|
||||||
|
import UserAuditClient from "./UserAuditClient";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "用户内容档案",
|
||||||
|
};
|
||||||
|
|
||||||
|
interface PageProps {
|
||||||
|
params: Promise<{ id: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function AdminUserAuditPage({ params }: PageProps) {
|
||||||
|
const { id: idRaw } = await params;
|
||||||
|
const userId = parseInt(idRaw, 10);
|
||||||
|
if (!Number.isFinite(userId) || userId <= 0) {
|
||||||
|
return <Forbidden text="无效的用户 ID。" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cookie = authCookieHeader(await cookies());
|
||||||
|
const me = await getMeCached(cookie || undefined);
|
||||||
|
|
||||||
|
if (!me.user || !isSuperOrOwner(me.user.role)) {
|
||||||
|
return <Forbidden text="用户与角色权限仅超级管理员和站长可操作。" />;
|
||||||
|
}
|
||||||
|
if (!isOwner(me.user.role)) {
|
||||||
|
return <Forbidden text="用户内容档案仅站长可查看。" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
let profile;
|
||||||
|
try {
|
||||||
|
profile = await fetchAdminUserAudit(userId, cookie || undefined);
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : "获取用户档案失败";
|
||||||
|
return <Forbidden text={msg} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <UserAuditClient userId={userId} initial={profile} />;
|
||||||
|
}
|
||||||
@@ -4,9 +4,11 @@ import { cookies } from "next/headers";
|
|||||||
import { PenSquare, MessagesSquare, ChevronRight } from "lucide-react";
|
import { PenSquare, MessagesSquare, ChevronRight } from "lucide-react";
|
||||||
import { fetchPosts, fetchBoards } from "@/lib/api";
|
import { fetchPosts, fetchBoards } from "@/lib/api";
|
||||||
import { authCookieHeader } from "@/lib/cookies";
|
import { authCookieHeader } from "@/lib/cookies";
|
||||||
|
import { getMeCached } from "@/lib/serverData";
|
||||||
import Pagination from "@/components/Pagination";
|
import Pagination from "@/components/Pagination";
|
||||||
import PostRow from "@/components/PostRow";
|
import PostRow from "@/components/PostRow";
|
||||||
import PinnedPosts from "@/components/PinnedPosts";
|
import PinnedPosts from "@/components/PinnedPosts";
|
||||||
|
import FeedNewTip from "@/components/home/FeedNewTip";
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
params: Promise<{ id: string }>;
|
params: Promise<{ id: string }>;
|
||||||
@@ -28,12 +30,14 @@ export default async function BoardPage({ params, searchParams }: PageProps) {
|
|||||||
const { page: pageStr } = await searchParams;
|
const { page: pageStr } = await searchParams;
|
||||||
const page = Math.max(1, parseInt(pageStr || "1", 10) || 1);
|
const page = Math.max(1, parseInt(pageStr || "1", 10) || 1);
|
||||||
const cookie = authCookieHeader(await cookies());
|
const cookie = authCookieHeader(await cookies());
|
||||||
const [postsData, boardsData] = await Promise.all([
|
const [postsData, boardsData, me] = await Promise.all([
|
||||||
fetchPosts(page, 20, Number(id), "latest", "", false, cookie),
|
fetchPosts(page, 20, Number(id), "latest", "", false, cookie),
|
||||||
fetchBoards(),
|
fetchBoards(),
|
||||||
|
getMeCached(cookie || undefined),
|
||||||
]);
|
]);
|
||||||
const boardIndex = boardsData.boards.findIndex((b) => b.id === Number(id));
|
const boardIndex = boardsData.boards.findIndex((b) => b.id === Number(id));
|
||||||
const board = boardIndex >= 0 ? boardsData.boards[boardIndex] : null;
|
const board = boardIndex >= 0 ? boardsData.boards[boardIndex] : null;
|
||||||
|
const user = me.user;
|
||||||
|
|
||||||
// 第一页:置顶帖独立成区,列表只保留非置顶
|
// 第一页:置顶帖独立成区,列表只保留非置顶
|
||||||
const pinned = page === 1 ? postsData.posts.filter((p) => p.pinned > 0) : [];
|
const pinned = page === 1 ? postsData.posts.filter((p) => p.pinned > 0) : [];
|
||||||
@@ -88,6 +92,16 @@ export default async function BoardPage({ params, searchParams }: PageProps) {
|
|||||||
<span className="font-bold text-[15px]" style={{ color: "var(--ink)" }}>全部讨论</span>
|
<span className="font-bold text-[15px]" style={{ color: "var(--ink)" }}>全部讨论</span>
|
||||||
<span className="meta text-xs">第 {page} 页</span>
|
<span className="meta text-xs">第 {page} 页</span>
|
||||||
</div>
|
</div>
|
||||||
|
{user && (
|
||||||
|
<div className="pt-2.5">
|
||||||
|
<FeedNewTip
|
||||||
|
sort="latest"
|
||||||
|
boardId={Number(id)}
|
||||||
|
page={page}
|
||||||
|
userId={user.id}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{rows.map((post, i) => (
|
{rows.map((post, i) => (
|
||||||
<PostRow key={post.id} post={post} index={i} />
|
<PostRow key={post.id} post={post} index={i} />
|
||||||
))}
|
))}
|
||||||
|
|||||||
706
frontend/app/chat/ChatShell.tsx
Normal file
706
frontend/app/chat/ChatShell.tsx
Normal file
@@ -0,0 +1,706 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback, useRef } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import {
|
||||||
|
Search,
|
||||||
|
Plus,
|
||||||
|
MessageSquare,
|
||||||
|
Users,
|
||||||
|
X,
|
||||||
|
Pin,
|
||||||
|
} from "lucide-react";
|
||||||
|
import {
|
||||||
|
apiListChatRooms,
|
||||||
|
apiSearchChatUsers,
|
||||||
|
apiOpenDirectChat,
|
||||||
|
apiCreateChatRoom,
|
||||||
|
apiPinChatRoom,
|
||||||
|
type ChatRoomView,
|
||||||
|
type User,
|
||||||
|
} from "@/lib/api";
|
||||||
|
import { realtime, RT_CHAT_UNREAD, RT_CHAT_MEMBERSHIP } from "@/lib/realtime";
|
||||||
|
import type { RtChatUnreadData, RtChatMembershipData } from "@/lib/realtime";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
import Avatar from "@/components/Avatar";
|
||||||
|
import ContextMenu, { type CtxMenuItem } from "@/components/ContextMenu";
|
||||||
|
|
||||||
|
function roomTitle(room: ChatRoomView) {
|
||||||
|
if (room.room_type === "direct") {
|
||||||
|
return room.peer?.nickname || room.peer?.username || room.name || "私聊";
|
||||||
|
}
|
||||||
|
return room.name || "未命名群";
|
||||||
|
}
|
||||||
|
|
||||||
|
function roomPreview(room: ChatRoomView) {
|
||||||
|
const lm = room.last_message;
|
||||||
|
if (!lm) return room.description || "暂无消息";
|
||||||
|
if (lm.recalled_at) {
|
||||||
|
if (lm.recalled_by && lm.recalled_by !== lm.sender_id) {
|
||||||
|
return "管理员撤回了此消息";
|
||||||
|
}
|
||||||
|
return "此消息已撤回";
|
||||||
|
}
|
||||||
|
const who =
|
||||||
|
room.room_type === "direct"
|
||||||
|
? ""
|
||||||
|
: `${lm.sender?.nickname || lm.sender?.username || ""}:`;
|
||||||
|
return `${who}${lm.content || ""}`.slice(0, 48);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(dateStr?: string) {
|
||||||
|
if (!dateStr) return "";
|
||||||
|
const d = new Date(dateStr);
|
||||||
|
const now = new Date();
|
||||||
|
const sameDay =
|
||||||
|
d.getFullYear() === now.getFullYear() &&
|
||||||
|
d.getMonth() === now.getMonth() &&
|
||||||
|
d.getDate() === now.getDate();
|
||||||
|
if (sameDay) {
|
||||||
|
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
return `${d.getMonth() + 1}/${d.getDate()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 与后端一致:大厅强制置顶 > 个人置顶 > last_message_id */
|
||||||
|
function sortRooms(list: ChatRoomView[]): ChatRoomView[] {
|
||||||
|
return [...list].sort((a, b) => {
|
||||||
|
const aHall = !!a.is_default;
|
||||||
|
const bHall = !!b.is_default;
|
||||||
|
if (aHall !== bHall) return aHall ? -1 : 1;
|
||||||
|
const aPin = !aHall && !!a.pinned;
|
||||||
|
const bPin = !bHall && !!b.pinned;
|
||||||
|
if (aPin !== bPin) return aPin ? -1 : 1;
|
||||||
|
if (a.last_message_id !== b.last_message_id) {
|
||||||
|
return (b.last_message_id || 0) - (a.last_message_id || 0);
|
||||||
|
}
|
||||||
|
return b.id - a.id;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPinnedView(room: ChatRoomView) {
|
||||||
|
return !!room.is_default || !!room.pinned || !!room.pin_forced;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PC 端飞书式消息壳:左会话列表 + 右会话区;移动端列表/会话互斥全屏。
|
||||||
|
*/
|
||||||
|
export default function ChatShell({
|
||||||
|
meId,
|
||||||
|
initialRooms,
|
||||||
|
activeRoomId = null,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
meId: number;
|
||||||
|
initialRooms: ChatRoomView[];
|
||||||
|
activeRoomId?: number | null;
|
||||||
|
children?: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [rooms, setRooms] = useState<ChatRoomView[]>(initialRooms);
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [userHits, setUserHits] = useState<User[]>([]);
|
||||||
|
const [searching, setSearching] = useState(false);
|
||||||
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
|
const [ctxMenu, setCtxMenu] = useState<{
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
room: ChatRoomView;
|
||||||
|
} | null>(null);
|
||||||
|
const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setRooms(sortRooms(initialRooms));
|
||||||
|
}, [initialRooms]);
|
||||||
|
|
||||||
|
const refreshRooms = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const res = await apiListChatRooms(1, 50, "", "joined");
|
||||||
|
setRooms(sortRooms(res.rooms || []));
|
||||||
|
} catch {
|
||||||
|
// 静默
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 每次进入消息壳都用 HTTP 拉最新排序(避免首页 Link 预取/路由缓存导致新消息会话不置顶)
|
||||||
|
useEffect(() => {
|
||||||
|
refreshRooms();
|
||||||
|
}, [refreshRooms, activeRoomId]);
|
||||||
|
|
||||||
|
// 从其他标签页切回时也对账一次
|
||||||
|
useEffect(() => {
|
||||||
|
const onVisible = () => {
|
||||||
|
if (document.visibilityState === "visible") refreshRooms();
|
||||||
|
};
|
||||||
|
document.addEventListener("visibilitychange", onVisible);
|
||||||
|
return () => document.removeEventListener("visibilitychange", onVisible);
|
||||||
|
}, [refreshRooms]);
|
||||||
|
|
||||||
|
// 实时未读:更新侧栏角标与预览,按置顶规则重排(不盲目置顶到最前)
|
||||||
|
useEffect(() => {
|
||||||
|
const off = realtime.on<RtChatUnreadData>(RT_CHAT_UNREAD, (data) => {
|
||||||
|
if (!data?.room_id) return;
|
||||||
|
if (activeRoomId === data.room_id) return;
|
||||||
|
setRooms((prev) => {
|
||||||
|
const idx = prev.findIndex((r) => r.id === data.room_id);
|
||||||
|
if (idx < 0) {
|
||||||
|
refreshRooms();
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
const next = [...prev];
|
||||||
|
const cur = next[idx];
|
||||||
|
next[idx] = {
|
||||||
|
...cur,
|
||||||
|
unread_count: (cur.unread_count || 0) + (data.delta || 1),
|
||||||
|
last_message_id: data.message_id,
|
||||||
|
last_message: {
|
||||||
|
id: data.message_id,
|
||||||
|
room_id: data.room_id,
|
||||||
|
sender_id: data.sender_id,
|
||||||
|
content: data.preview || "",
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
sender: cur.last_message?.sender || ({
|
||||||
|
id: data.sender_id,
|
||||||
|
username: "",
|
||||||
|
nickname: "",
|
||||||
|
avatar: "",
|
||||||
|
role: "user",
|
||||||
|
} as User),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return sortRooms(next);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return off;
|
||||||
|
}, [activeRoomId, refreshRooms]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const off = realtime.on<RtChatMembershipData>(RT_CHAT_MEMBERSHIP, (data) => {
|
||||||
|
if (!data) return;
|
||||||
|
if (data.status === "invited" || data.status === "dissolved" || data.status === "kicked") {
|
||||||
|
refreshRooms();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return off;
|
||||||
|
}, [refreshRooms]);
|
||||||
|
|
||||||
|
// 进入会话后清零该会话未读
|
||||||
|
useEffect(() => {
|
||||||
|
if (!activeRoomId) return;
|
||||||
|
setRooms((prev) =>
|
||||||
|
prev.map((r) => (r.id === activeRoomId ? { ...r, unread_count: 0 } : r))
|
||||||
|
);
|
||||||
|
}, [activeRoomId]);
|
||||||
|
|
||||||
|
// 搜索:会话本地过滤 + 用户远程搜索
|
||||||
|
useEffect(() => {
|
||||||
|
const q = query.trim();
|
||||||
|
if (!q) {
|
||||||
|
setUserHits([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const t = setTimeout(async () => {
|
||||||
|
setSearching(true);
|
||||||
|
try {
|
||||||
|
const res = await apiSearchChatUsers(q);
|
||||||
|
setUserHits(res.users || []);
|
||||||
|
} catch {
|
||||||
|
setUserHits([]);
|
||||||
|
} finally {
|
||||||
|
setSearching(false);
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [query]);
|
||||||
|
|
||||||
|
const filteredRooms = (() => {
|
||||||
|
const q = query.trim().toLowerCase();
|
||||||
|
if (!q) return rooms;
|
||||||
|
return rooms.filter((r) => {
|
||||||
|
const title = roomTitle(r).toLowerCase();
|
||||||
|
const uname = r.peer?.username?.toLowerCase() || "";
|
||||||
|
return title.includes(q) || uname.includes(q) || r.name.toLowerCase().includes(q);
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|
||||||
|
const openDM = async (uid: number) => {
|
||||||
|
try {
|
||||||
|
const { room } = await apiOpenDirectChat(uid);
|
||||||
|
setQuery("");
|
||||||
|
setUserHits([]);
|
||||||
|
router.push(`/chat/${room.id}`);
|
||||||
|
refreshRooms();
|
||||||
|
} catch (e) {
|
||||||
|
toast(e instanceof Error ? e.message : "无法发起私聊");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const togglePin = async (room: ChatRoomView) => {
|
||||||
|
setCtxMenu(null);
|
||||||
|
if (room.is_default || room.pin_forced) {
|
||||||
|
toast("大厅已置顶且不可取消");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const next = !room.pinned;
|
||||||
|
try {
|
||||||
|
await apiPinChatRoom(room.id, next);
|
||||||
|
setRooms((prev) =>
|
||||||
|
sortRooms(
|
||||||
|
prev.map((r) =>
|
||||||
|
r.id === room.id ? { ...r, pinned: next } : r
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
toast(next ? "已置顶" : "已取消置顶", "ok");
|
||||||
|
} catch (err) {
|
||||||
|
toast(err instanceof Error ? err.message : "操作失败");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openRoomMenu = (room: ChatRoomView, x: number, y: number) => {
|
||||||
|
if (room.is_default || room.pin_forced) return;
|
||||||
|
setCtxMenu({ x, y, room });
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearLongPress = () => {
|
||||||
|
if (longPressTimer.current) {
|
||||||
|
clearTimeout(longPressTimer.current);
|
||||||
|
longPressTimer.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const showList = !activeRoomId;
|
||||||
|
// 移动端:有会话时隐藏列表;桌面始终显示列表
|
||||||
|
const listClass = activeRoomId
|
||||||
|
? "hidden lg:flex"
|
||||||
|
: "flex";
|
||||||
|
const paneClass = activeRoomId
|
||||||
|
? "flex"
|
||||||
|
: "hidden lg:flex";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="panel overflow-hidden grid grid-cols-1 lg:grid-cols-[320px_minmax(0,1fr)]"
|
||||||
|
style={{
|
||||||
|
height: "calc(100vh - 8.5rem)",
|
||||||
|
minHeight: "480px",
|
||||||
|
borderColor: "var(--line)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 左栏:会话列表 */}
|
||||||
|
<aside
|
||||||
|
className={`${listClass} flex-col min-h-0`}
|
||||||
|
style={{ borderRight: "1px solid var(--line)" }}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="flex items-center justify-between gap-2 px-4 py-3 shrink-0"
|
||||||
|
style={{ borderBottom: "1px solid var(--line)" }}
|
||||||
|
>
|
||||||
|
<h1 className="font-extrabold text-[17px]" style={{ color: "var(--ink)" }}>
|
||||||
|
消息
|
||||||
|
</h1>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreate(true)}
|
||||||
|
className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] transition-colors"
|
||||||
|
style={{ color: "var(--accent)" }}
|
||||||
|
aria-label="新建群聊"
|
||||||
|
title="新建群聊"
|
||||||
|
>
|
||||||
|
<Plus size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-3 py-2.5 shrink-0 space-y-1.5">
|
||||||
|
<label
|
||||||
|
className="j13-chat-search flex items-center gap-2 px-3 h-10 rounded-xl cursor-text transition-[border-color,box-shadow] duration-150"
|
||||||
|
style={{
|
||||||
|
background: "var(--bg)",
|
||||||
|
border: "1px solid var(--line)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Search size={15} className="shrink-0 pointer-events-none" style={{ color: query ? "var(--accent)" : "var(--ink-3)" }} />
|
||||||
|
<input
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
placeholder="搜索会话、用户名或昵称"
|
||||||
|
className="j13-chat-search-input bg-transparent flex-1 self-stretch h-full text-[13px] min-w-0"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
/>
|
||||||
|
{query && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setQuery("");
|
||||||
|
}}
|
||||||
|
aria-label="清除搜索"
|
||||||
|
className="w-5 h-5 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] shrink-0"
|
||||||
|
style={{ color: "var(--ink-3)" }}
|
||||||
|
>
|
||||||
|
<X size={12} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
{query.trim() && (
|
||||||
|
<p className="px-1 text-[11px] meta">
|
||||||
|
{searching
|
||||||
|
? "正在搜索用户…"
|
||||||
|
: `会话 ${filteredRooms.length} · 用户 ${userHits.length}`}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto min-h-0">
|
||||||
|
{query.trim() && (
|
||||||
|
<div className="px-2 pb-2">
|
||||||
|
<p
|
||||||
|
className="px-2 py-1.5 text-[11px] font-bold uppercase tracking-wider"
|
||||||
|
style={{ color: "var(--ink-3)" }}
|
||||||
|
>
|
||||||
|
用户 {searching ? "…" : ""}
|
||||||
|
</p>
|
||||||
|
{userHits.length === 0 && !searching ? (
|
||||||
|
<p className="px-2 py-2 text-[12px] meta">无匹配用户</p>
|
||||||
|
) : (
|
||||||
|
userHits.map((u) => (
|
||||||
|
<button
|
||||||
|
key={u.id}
|
||||||
|
onClick={() => openDM(u.id)}
|
||||||
|
className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left hover:bg-[var(--accent-soft)] transition-colors"
|
||||||
|
>
|
||||||
|
<Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={36} />
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-[13px] font-semibold truncate" style={{ color: "var(--ink)" }}>
|
||||||
|
{u.nickname || u.username}
|
||||||
|
</p>
|
||||||
|
<p className="text-[11px] meta truncate">@{u.username}</p>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
<p
|
||||||
|
className="px-2 py-1.5 mt-1 text-[11px] font-bold uppercase tracking-wider"
|
||||||
|
style={{ color: "var(--ink-3)" }}
|
||||||
|
>
|
||||||
|
会话
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{filteredRooms.length === 0 ? (
|
||||||
|
<div className="text-center py-16 px-4">
|
||||||
|
<MessageSquare size={28} style={{ color: "var(--ink-3)", margin: "0 auto 8px" }} />
|
||||||
|
<p className="text-[13px] meta">
|
||||||
|
{query ? "无匹配会话" : "还没有会话,搜索用户发起私聊或新建群聊"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="px-1.5 pb-2">
|
||||||
|
{filteredRooms.map((room) => {
|
||||||
|
const active = room.id === activeRoomId;
|
||||||
|
const pinned = isPinnedView(room);
|
||||||
|
return (
|
||||||
|
<li key={room.id}>
|
||||||
|
<Link
|
||||||
|
href={`/chat/${room.id}`}
|
||||||
|
className="flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl transition-colors"
|
||||||
|
style={{
|
||||||
|
background: active ? "var(--accent-soft)" : "transparent",
|
||||||
|
}}
|
||||||
|
onContextMenu={(e) => {
|
||||||
|
if (room.is_default || room.pin_forced) return;
|
||||||
|
e.preventDefault();
|
||||||
|
openRoomMenu(room, e.clientX, e.clientY);
|
||||||
|
}}
|
||||||
|
onTouchStart={(e) => {
|
||||||
|
if (room.is_default || room.pin_forced) return;
|
||||||
|
const t = e.touches[0];
|
||||||
|
if (!t) return;
|
||||||
|
clearLongPress();
|
||||||
|
longPressTimer.current = setTimeout(() => {
|
||||||
|
openRoomMenu(room, t.clientX, t.clientY);
|
||||||
|
}, 480);
|
||||||
|
}}
|
||||||
|
onTouchEnd={clearLongPress}
|
||||||
|
onTouchMove={clearLongPress}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="w-10 h-10 shrink-0 rounded-xl flex items-center justify-center overflow-hidden"
|
||||||
|
style={{ background: "var(--panel-2)" }}
|
||||||
|
>
|
||||||
|
{room.room_type === "direct" && room.peer ? (
|
||||||
|
<Avatar
|
||||||
|
name={room.peer.nickname || room.peer.username}
|
||||||
|
src={room.peer.avatar || undefined}
|
||||||
|
size={40}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Users size={18} style={{ color: "var(--accent)" }} />
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span
|
||||||
|
className="font-semibold text-[13.5px] truncate"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
>
|
||||||
|
{roomTitle(room)}
|
||||||
|
</span>
|
||||||
|
{pinned && (
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center gap-0.5 text-[10px] font-bold shrink-0 px-1.5 py-0.5 rounded"
|
||||||
|
style={{
|
||||||
|
background: "var(--accent-soft)",
|
||||||
|
color: "var(--accent)",
|
||||||
|
}}
|
||||||
|
title={room.is_default ? "强制置顶" : "置顶"}
|
||||||
|
>
|
||||||
|
<Pin size={10} /> 置顶
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{room.is_default && (
|
||||||
|
<span className="text-[10px] font-bold shrink-0" style={{ color: "var(--gold)" }}>
|
||||||
|
大厅
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{room.is_private && room.room_type === "group" && (
|
||||||
|
<span className="text-[10px] font-bold shrink-0 meta">私密</span>
|
||||||
|
)}
|
||||||
|
<span className="ml-auto meta text-[10.5px] shrink-0">
|
||||||
|
{formatTime(room.last_message?.created_at || room.updated_at)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 mt-0.5">
|
||||||
|
<p className="text-[12px] truncate meta flex-1">{roomPreview(room)}</p>
|
||||||
|
{room.unread_count > 0 && (
|
||||||
|
<span
|
||||||
|
className="shrink-0 min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold flex items-center justify-center"
|
||||||
|
style={{ background: "var(--clay)", color: "#fff" }}
|
||||||
|
>
|
||||||
|
{room.unread_count > 99 ? "99+" : room.unread_count}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* 右栏:会话内容 */}
|
||||||
|
<section className={`${paneClass} flex-col min-h-0 min-w-0`}>
|
||||||
|
{children ? (
|
||||||
|
children
|
||||||
|
) : (
|
||||||
|
<div className="flex-1 flex flex-col items-center justify-center px-6 text-center">
|
||||||
|
<span
|
||||||
|
className="w-16 h-16 rounded-2xl flex items-center justify-center mb-4"
|
||||||
|
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
|
||||||
|
>
|
||||||
|
<MessageSquare size={28} />
|
||||||
|
</span>
|
||||||
|
<p className="font-bold text-[16px]" style={{ color: "var(--ink)" }}>
|
||||||
|
选择一个会话开始聊天
|
||||||
|
</p>
|
||||||
|
<p className="meta mt-1.5 text-[13px] max-w-xs">
|
||||||
|
在左侧搜索用户发起私聊,或新建群聊。全站大厅已为你自动加入。
|
||||||
|
</p>
|
||||||
|
{showList && (
|
||||||
|
<p className="lg:hidden meta mt-4 text-[12px]">请从上方列表选择会话</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{showCreate && (
|
||||||
|
<CreateGroupModal
|
||||||
|
onClose={() => setShowCreate(false)}
|
||||||
|
onCreated={(id) => {
|
||||||
|
setShowCreate(false);
|
||||||
|
toast("群已创建", "ok");
|
||||||
|
router.push(`/chat/${id}`);
|
||||||
|
refreshRooms();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{ctxMenu && (
|
||||||
|
<ContextMenu
|
||||||
|
x={ctxMenu.x}
|
||||||
|
y={ctxMenu.y}
|
||||||
|
items={
|
||||||
|
[
|
||||||
|
{
|
||||||
|
key: "pin",
|
||||||
|
label: ctxMenu.room.pinned ? "取消置顶" : "置顶",
|
||||||
|
icon: <Pin size={14} />,
|
||||||
|
onClick: () => togglePin(ctxMenu.room),
|
||||||
|
},
|
||||||
|
] as CtxMenuItem[]
|
||||||
|
}
|
||||||
|
onClose={() => setCtxMenu(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CreateGroupModal({
|
||||||
|
onClose,
|
||||||
|
onCreated,
|
||||||
|
}: {
|
||||||
|
onClose: () => void;
|
||||||
|
onCreated: (roomId: number) => void;
|
||||||
|
}) {
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [description, setDescription] = useState("");
|
||||||
|
const [isPrivate, setIsPrivate] = useState(false);
|
||||||
|
const [memberInput, setMemberInput] = useState("");
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
const trimmed = name.trim();
|
||||||
|
if (trimmed.length < 2 || trimmed.length > 32) {
|
||||||
|
toast("群名称需为 2-32 个字符");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (description.length > 200) {
|
||||||
|
toast("群简介不能超过 200 个字符");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const usernames = memberInput
|
||||||
|
.split(/[\s,,]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
const { room } = await apiCreateChatRoom(trimmed, description.trim(), {
|
||||||
|
is_private: isPrivate,
|
||||||
|
member_usernames: isPrivate ? usernames : [],
|
||||||
|
});
|
||||||
|
onCreated(room.id);
|
||||||
|
} catch (e) {
|
||||||
|
toast(e instanceof Error ? e.message : "建群失败");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-[1000] flex items-center justify-center p-4"
|
||||||
|
style={{ background: "rgba(0,0,0,0.55)" }}
|
||||||
|
// 刻意不绑定外侧点击关闭,避免误关丢失已填内容
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-md rounded-2xl p-6 j13-toast-in"
|
||||||
|
style={{ background: "var(--panel)", border: "1px solid var(--line)" }}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between mb-5">
|
||||||
|
<h2 className="text-[18px] font-extrabold" style={{ color: "var(--ink)" }}>
|
||||||
|
新建群聊
|
||||||
|
</h2>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={submitting}
|
||||||
|
aria-label="关闭"
|
||||||
|
className="w-7 h-7 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] transition-colors"
|
||||||
|
style={{ color: "var(--ink-3)" }}
|
||||||
|
>
|
||||||
|
<X size={15} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[12px] font-bold mb-1.5" style={{ color: "var(--ink-2)" }}>
|
||||||
|
群名称 <span style={{ color: "var(--danger)" }}>*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
type="text"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
maxLength={32}
|
||||||
|
placeholder="2-32 个字符"
|
||||||
|
className="w-full px-3.5 h-10 rounded-lg outline-none"
|
||||||
|
style={{ background: "var(--bg)", border: "1px solid var(--line)", color: "var(--ink)" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[12px] font-bold mb-1.5" style={{ color: "var(--ink-2)" }}>
|
||||||
|
群简介(选填)
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
maxLength={200}
|
||||||
|
rows={3}
|
||||||
|
className="w-full px-3.5 py-2.5 rounded-lg outline-none resize-none"
|
||||||
|
style={{ background: "var(--bg)", border: "1px solid var(--line)", color: "var(--ink)" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[12px] font-bold mb-2" style={{ color: "var(--ink-2)" }}>
|
||||||
|
可见性
|
||||||
|
</label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsPrivate(false)}
|
||||||
|
className="flex-1 h-9 rounded-lg text-[13px] font-semibold"
|
||||||
|
style={{
|
||||||
|
background: !isPrivate ? "var(--accent-soft)" : "var(--bg)",
|
||||||
|
color: !isPrivate ? "var(--accent)" : "var(--ink-2)",
|
||||||
|
border: `1px solid ${!isPrivate ? "var(--accent)" : "var(--line)"}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
公开
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsPrivate(true)}
|
||||||
|
className="flex-1 h-9 rounded-lg text-[13px] font-semibold"
|
||||||
|
style={{
|
||||||
|
background: isPrivate ? "var(--accent-soft)" : "var(--bg)",
|
||||||
|
color: isPrivate ? "var(--accent)" : "var(--ink-2)",
|
||||||
|
border: `1px solid ${isPrivate ? "var(--accent)" : "var(--line)"}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
私密
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{isPrivate && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-[12px] font-bold mb-1.5" style={{ color: "var(--ink-2)" }}>
|
||||||
|
初始成员(选填)
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={memberInput}
|
||||||
|
onChange={(e) => setMemberInput(e.target.value)}
|
||||||
|
placeholder="用户名,多个用空格或逗号分隔"
|
||||||
|
className="w-full px-3.5 h-10 rounded-lg outline-none"
|
||||||
|
style={{ background: "var(--bg)", border: "1px solid var(--line)", color: "var(--ink)" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex justify-end gap-2 pt-1">
|
||||||
|
<button onClick={onClose} disabled={submitting} className="btn btn-line btn-sm">
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button onClick={submit} disabled={submitting} className="btn btn-accent btn-sm">
|
||||||
|
{submitting ? "创建中..." : "创建"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
1589
frontend/app/chat/[id]/ChatRoomClient.tsx
Normal file
1589
frontend/app/chat/[id]/ChatRoomClient.tsx
Normal file
File diff suppressed because it is too large
Load Diff
94
frontend/app/chat/[id]/page.tsx
Normal file
94
frontend/app/chat/[id]/page.tsx
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { notFound, redirect } from "next/navigation";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { authCookieHeader } from "@/lib/cookies";
|
||||||
|
import { getMeCached } from "@/lib/serverData";
|
||||||
|
import { fetchChatRoom, fetchChatMessages, fetchChatRooms } from "@/lib/api";
|
||||||
|
import ChatShell from "../ChatShell";
|
||||||
|
import ChatRoomClient from "./ChatRoomClient";
|
||||||
|
|
||||||
|
interface PageProps {
|
||||||
|
params: Promise<{ id: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
||||||
|
const { id } = await params;
|
||||||
|
try {
|
||||||
|
const { room } = await fetchChatRoom(id, authCookieHeader(await cookies()));
|
||||||
|
const title =
|
||||||
|
room.room_type === "direct"
|
||||||
|
? room.peer?.nickname || room.peer?.username || room.name || "私聊"
|
||||||
|
: room.name;
|
||||||
|
return { title: `消息 · ${title}` };
|
||||||
|
} catch {
|
||||||
|
return { title: "会话不存在" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ChatRoomPage({ params }: PageProps) {
|
||||||
|
const { id } = await params;
|
||||||
|
const cookie = authCookieHeader(await cookies());
|
||||||
|
const me = await getMeCached(cookie || undefined);
|
||||||
|
if (!me.user) {
|
||||||
|
redirect(`/login?redirect=${encodeURIComponent(`/chat/${id}`)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rooms: Awaited<ReturnType<typeof fetchChatRooms>>["rooms"] = [];
|
||||||
|
try {
|
||||||
|
const data = await fetchChatRooms(1, 50, "", cookie, "joined");
|
||||||
|
rooms = data.rooms || [];
|
||||||
|
} catch {
|
||||||
|
rooms = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
let room: Awaited<ReturnType<typeof fetchChatRoom>>["room"];
|
||||||
|
try {
|
||||||
|
({ room } = await fetchChatRoom(id, cookie));
|
||||||
|
} catch {
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
let initialMessages: Awaited<ReturnType<typeof fetchChatMessages>> = {
|
||||||
|
messages: [],
|
||||||
|
has_more: false,
|
||||||
|
};
|
||||||
|
if (room.joined) {
|
||||||
|
try {
|
||||||
|
initialMessages = await fetchChatMessages(id, 0, 30, cookie);
|
||||||
|
} catch {
|
||||||
|
// 客户端兜底
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const displayName =
|
||||||
|
room.room_type === "direct"
|
||||||
|
? room.peer?.nickname || room.peer?.username || room.name || "私聊"
|
||||||
|
: room.name;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-6xl mx-auto">
|
||||||
|
<ChatShell meId={me.user.id} initialRooms={rooms} activeRoomId={room.id}>
|
||||||
|
<ChatRoomClient
|
||||||
|
roomId={room.id}
|
||||||
|
roomName={displayName}
|
||||||
|
roomDescription={room.description}
|
||||||
|
ownerId={room.owner_id}
|
||||||
|
memberCount={room.member_count}
|
||||||
|
myRole={room.my_role}
|
||||||
|
joined={room.joined}
|
||||||
|
isPrivate={room.is_private}
|
||||||
|
isDefault={room.is_default}
|
||||||
|
roomType={room.room_type || "group"}
|
||||||
|
peer={room.peer || null}
|
||||||
|
meId={me.user.id}
|
||||||
|
meRole={me.user.role}
|
||||||
|
meName={me.user.nickname || me.user.username}
|
||||||
|
meAvatar={me.user.avatar || ""}
|
||||||
|
initialMessages={initialMessages.messages}
|
||||||
|
initialHasMore={initialMessages.has_more}
|
||||||
|
embedded
|
||||||
|
/>
|
||||||
|
</ChatShell>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
34
frontend/app/chat/page.tsx
Normal file
34
frontend/app/chat/page.tsx
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import type { Metadata } from "next";
|
||||||
|
import { authCookieHeader } from "@/lib/cookies";
|
||||||
|
import { getMeCached } from "@/lib/serverData";
|
||||||
|
import { fetchChatRooms } from "@/lib/api";
|
||||||
|
import ChatShell from "./ChatShell";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "消息",
|
||||||
|
description: "私聊与群聊,实时交流。",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function ChatListPage() {
|
||||||
|
const cookie = authCookieHeader(await cookies());
|
||||||
|
const me = await getMeCached(cookie || undefined);
|
||||||
|
if (!me.user) {
|
||||||
|
redirect(`/login?redirect=${encodeURIComponent("/chat")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rooms: Awaited<ReturnType<typeof fetchChatRooms>>["rooms"] = [];
|
||||||
|
try {
|
||||||
|
const data = await fetchChatRooms(1, 50, "", cookie, "joined");
|
||||||
|
rooms = data.rooms || [];
|
||||||
|
} catch {
|
||||||
|
rooms = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-6xl mx-auto">
|
||||||
|
<ChatShell meId={me.user.id} initialRooms={rooms} activeRoomId={null} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -155,6 +155,89 @@ h1, h2, h3, h4 {
|
|||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 消息侧栏搜索:单层描边,避免外框 + focus-visible 双线 */
|
||||||
|
.j13-chat-search:focus-within {
|
||||||
|
border-color: var(--accent) !important;
|
||||||
|
box-shadow: 0 0 0 3px var(--accent-soft);
|
||||||
|
}
|
||||||
|
.j13-chat-search-input,
|
||||||
|
.j13-chat-search-input:focus,
|
||||||
|
.j13-chat-search-input:focus-visible {
|
||||||
|
outline: none !important;
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 聊天输入区:与搜索框同款聚焦态 */
|
||||||
|
.j13-chat-composer:focus-within {
|
||||||
|
border-color: var(--accent) !important;
|
||||||
|
box-shadow: 0 0 0 3px var(--accent-soft);
|
||||||
|
}
|
||||||
|
.j13-chat-composer-input,
|
||||||
|
.j13-chat-composer-input:focus,
|
||||||
|
.j13-chat-composer-input:focus-visible {
|
||||||
|
outline: none !important;
|
||||||
|
box-shadow: none !important;
|
||||||
|
resize: none !important;
|
||||||
|
}
|
||||||
|
.j13-chat-composer-input.has-value {
|
||||||
|
color: transparent;
|
||||||
|
caret-color: var(--ink);
|
||||||
|
}
|
||||||
|
.j13-chat-composer-input.has-value::placeholder {
|
||||||
|
color: transparent;
|
||||||
|
}
|
||||||
|
.j13-chat-composer-mirror {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
pointer-events: none;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
word-break: break-word;
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
.j13-mention-token {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 2px 8px;
|
||||||
|
margin: 0 2px;
|
||||||
|
border-radius: 999px;
|
||||||
|
line-height: 1.35;
|
||||||
|
vertical-align: baseline;
|
||||||
|
/* 主题强调色加深 + 对比色字,胶囊形 */
|
||||||
|
background: color-mix(in srgb, var(--accent) 82%, #000);
|
||||||
|
color: #fff !important;
|
||||||
|
font-weight: 600;
|
||||||
|
text-decoration: none !important;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: filter 0.12s ease, opacity 0.12s ease;
|
||||||
|
box-decoration-break: clone;
|
||||||
|
-webkit-box-decoration-break: clone;
|
||||||
|
}
|
||||||
|
a.j13-mention-token:hover {
|
||||||
|
filter: brightness(1.08);
|
||||||
|
opacity: 0.95;
|
||||||
|
}
|
||||||
|
.dark .j13-mention-token {
|
||||||
|
/* 暗色下 accent 偏亮,用实心 accent + 配套字色 */
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-on) !important;
|
||||||
|
}
|
||||||
|
/* 输入镜像层:不加粗/不加 padding,避免与透明 textarea 字宽错位 */
|
||||||
|
.j13-chat-composer-mirror .j13-mention-token {
|
||||||
|
display: inline;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
line-height: inherit;
|
||||||
|
font-weight: inherit;
|
||||||
|
border-radius: 999px;
|
||||||
|
box-shadow: none;
|
||||||
|
background: color-mix(in srgb, var(--accent) 82%, #000);
|
||||||
|
}
|
||||||
|
.dark .j13-chat-composer-mirror .j13-mention-token {
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-on) !important;
|
||||||
|
}
|
||||||
|
|
||||||
@layer components {
|
@layer components {
|
||||||
/* ----- 小标签(旧名 .kicker 保留兼容) ----- */
|
/* ----- 小标签(旧名 .kicker 保留兼容) ----- */
|
||||||
.kicker {
|
.kicker {
|
||||||
@@ -230,6 +313,22 @@ h1, h2, h3, h4 {
|
|||||||
.btn-primary:active:not(:disabled) {
|
.btn-primary:active:not(:disabled) {
|
||||||
transform: translateY(0);
|
transform: translateY(0);
|
||||||
}
|
}
|
||||||
|
/* 与 btn-primary 同款,历史类名兼容 */
|
||||||
|
.btn-accent {
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-on);
|
||||||
|
box-shadow: 0 1px 2px rgba(16, 24, 40, 0.12),
|
||||||
|
0 2px 8px color-mix(in srgb, var(--accent) 26%, transparent);
|
||||||
|
}
|
||||||
|
.btn-accent:hover:not(:disabled) {
|
||||||
|
background: var(--accent-hi);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 2px 6px rgba(16, 24, 40, 0.1),
|
||||||
|
0 8px 20px color-mix(in srgb, var(--accent) 34%, transparent);
|
||||||
|
}
|
||||||
|
.btn-accent:active:not(:disabled) {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
.btn-line {
|
.btn-line {
|
||||||
background: var(--panel);
|
background: var(--panel);
|
||||||
@@ -380,6 +479,18 @@ h1, h2, h3, h4 {
|
|||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
.badge-pending {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
padding: 4px 11px;
|
||||||
|
background: var(--accent-soft);
|
||||||
|
color: var(--accent);
|
||||||
|
border-radius: 999px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
/* 帖子列表中的板块小标签:全站统一浅灰配色,避免每行多色眩目 */
|
/* 帖子列表中的板块小标签:全站统一浅灰配色,避免每行多色眩目 */
|
||||||
.j13-board-tag {
|
.j13-board-tag {
|
||||||
@@ -539,6 +650,20 @@ h1, h2, h3, h4 {
|
|||||||
transform: scale(0.97);
|
transform: scale(0.97);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 帖子流「有新内容」提示条(三期) */
|
||||||
|
.j13-feed-new-tip:hover {
|
||||||
|
filter: brightness(0.97);
|
||||||
|
}
|
||||||
|
.j13-feed-new-tip:focus-visible {
|
||||||
|
outline: 2px solid var(--accent);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.j13-feed-new-tip {
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* 侧栏导航项 */
|
/* 侧栏导航项 */
|
||||||
.j13-raillink {
|
.j13-raillink {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import Footer from "@/components/Footer";
|
|||||||
import Toaster from "@/components/Toaster";
|
import Toaster from "@/components/Toaster";
|
||||||
import AccountGuard from "@/components/AccountGuard";
|
import AccountGuard from "@/components/AccountGuard";
|
||||||
import ThemeSync from "@/components/ThemeSync";
|
import ThemeSync from "@/components/ThemeSync";
|
||||||
|
import RealtimeProvider from "@/components/RealtimeProvider";
|
||||||
import type { User } from "@/lib/api";
|
import type { User } from "@/lib/api";
|
||||||
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
|
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
|
||||||
import { TOKEN_COOKIE, REFRESH_COOKIE, authCookieHeader } from "@/lib/cookies";
|
import { TOKEN_COOKIE, REFRESH_COOKIE, authCookieHeader } from "@/lib/cookies";
|
||||||
@@ -68,6 +69,7 @@ export default async function RootLayout({
|
|||||||
|
|
||||||
let user: User | null = null;
|
let user: User | null = null;
|
||||||
let unread = 0;
|
let unread = 0;
|
||||||
|
let chatUnread = 0;
|
||||||
const hasAuthCookie =
|
const hasAuthCookie =
|
||||||
!!cookieStore.get(TOKEN_COOKIE)?.value || !!cookieStore.get(REFRESH_COOKIE)?.value;
|
!!cookieStore.get(TOKEN_COOKIE)?.value || !!cookieStore.get(REFRESH_COOKIE)?.value;
|
||||||
if (hasAuthCookie) {
|
if (hasAuthCookie) {
|
||||||
@@ -75,6 +77,7 @@ export default async function RootLayout({
|
|||||||
const me = await getMeCached(authCookieHeader(cookieStore) || undefined);
|
const me = await getMeCached(authCookieHeader(cookieStore) || undefined);
|
||||||
user = me.user;
|
user = me.user;
|
||||||
unread = me.unread_count;
|
unread = me.unread_count;
|
||||||
|
chatUnread = me.chat_unread_count ?? 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -84,7 +87,7 @@ export default async function RootLayout({
|
|||||||
>
|
>
|
||||||
<body className="min-h-screen flex flex-col">
|
<body className="min-h-screen flex flex-col">
|
||||||
{accentCSS ? (
|
{accentCSS ? (
|
||||||
// id 与 lib/theme 的运行时换肤共用:后台实时预览时直接复用/替换此节点
|
// React 托管的 SSR 主题节点;客户端换肤走 j13-accent-runtime,禁止对此外挂 remove
|
||||||
<style
|
<style
|
||||||
id="j13-accent-vars"
|
id="j13-accent-vars"
|
||||||
data-accent-source="ssr"
|
data-accent-source="ssr"
|
||||||
@@ -94,7 +97,12 @@ export default async function RootLayout({
|
|||||||
<a href="#main" className="skip-link">
|
<a href="#main" className="skip-link">
|
||||||
跳到主要内容
|
跳到主要内容
|
||||||
</a>
|
</a>
|
||||||
<Header initialUser={user} initialUnread={unread} initialTheme={theme} />
|
<Header
|
||||||
|
initialUser={user}
|
||||||
|
initialUnread={unread}
|
||||||
|
initialChatUnread={chatUnread}
|
||||||
|
initialTheme={theme}
|
||||||
|
/>
|
||||||
<main
|
<main
|
||||||
id="main"
|
id="main"
|
||||||
tabIndex={-1}
|
tabIndex={-1}
|
||||||
@@ -106,6 +114,7 @@ export default async function RootLayout({
|
|||||||
<Toaster />
|
<Toaster />
|
||||||
<AccountGuard />
|
<AccountGuard />
|
||||||
<ThemeSync initialAccent={accent || ""} />
|
<ThemeSync initialAccent={accent || ""} />
|
||||||
|
<RealtimeProvider userId={user ? user.id : null} />
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Heart, MessageCircle, CheckCheck, Bell, CheckCircle2, XCircle } from "lucide-react";
|
import { Heart, MessageCircle, CheckCheck, Bell, CheckCircle2, XCircle, AtSign, ClipboardList } from "lucide-react";
|
||||||
import { apiMarkRead, apiMarkAllRead, type NotificationsResponse, type NotificationItem } from "@/lib/api";
|
import { apiMarkRead, apiMarkAllRead, type NotificationsResponse, type NotificationItem } from "@/lib/api";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,7 +20,14 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
|
|||||||
list.map((item) => (item.id === n.id ? { ...item, is_read: true } : item))
|
list.map((item) => (item.id === n.id ? { ...item, is_read: true } : item))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
router.push(`/post/${n.post_id}`);
|
// @提及通知跳到群聊房间;其余跳到帖子/评论
|
||||||
|
if (n.type === "mention" && n.room_id) {
|
||||||
|
router.push(`/chat/${n.room_id}`);
|
||||||
|
} else if (n.type === "pending_review") {
|
||||||
|
router.push(n.post_id ? `/post/${n.post_id}` : "/admin/moderation");
|
||||||
|
} else {
|
||||||
|
router.push(`/post/${n.post_id}`);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMarkAll = async () => {
|
const handleMarkAll = async () => {
|
||||||
@@ -73,7 +80,11 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
|
|||||||
? <XCircle size={16} />
|
? <XCircle size={16} />
|
||||||
: n.type === "like"
|
: n.type === "like"
|
||||||
? <Heart size={16} />
|
? <Heart size={16} />
|
||||||
: <MessageCircle size={16} />;
|
: n.type === "mention"
|
||||||
|
? <AtSign size={16} />
|
||||||
|
: n.type === "pending_review"
|
||||||
|
? <ClipboardList size={16} />
|
||||||
|
: <MessageCircle size={16} />;
|
||||||
const iconColor = n.type === "approved"
|
const iconColor = n.type === "approved"
|
||||||
? "var(--ok)"
|
? "var(--ok)"
|
||||||
: n.type === "rejected"
|
: n.type === "rejected"
|
||||||
@@ -128,14 +139,28 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
|
|||||||
? "评论了你的帖子"
|
? "评论了你的帖子"
|
||||||
: n.type === "reply"
|
: n.type === "reply"
|
||||||
? "回复了你的评论"
|
? "回复了你的评论"
|
||||||
: "点赞了你的帖子"}
|
: n.type === "mention"
|
||||||
|
? "在消息中提到了你"
|
||||||
|
: n.type === "pending_review"
|
||||||
|
? "有新内容待审核"
|
||||||
|
: "点赞了你的帖子"}
|
||||||
</span>
|
</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-sm mt-1 truncate" style={{ color: "var(--ink-2)" }}>
|
{n.type === "mention" ? (
|
||||||
《{n.post.title}》
|
n.room && (
|
||||||
</p>
|
<p className="text-sm mt-1 truncate" style={{ color: "var(--ink-2)" }}>
|
||||||
|
# {n.room.name}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
n.post && (
|
||||||
|
<p className="text-sm mt-1 truncate" style={{ color: "var(--ink-2)" }}>
|
||||||
|
《{n.post.title}》
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
)}
|
||||||
{n.content && (
|
{n.content && (
|
||||||
<p className="text-[13px] mt-1.5 line-clamp-2" style={{ color: "var(--ink-3)" }}>
|
<p className="text-[13px] mt-1.5 line-clamp-2" style={{ color: "var(--ink-3)" }}>
|
||||||
{n.content}
|
{n.content}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { getMeCached } from "@/lib/serverData";
|
|||||||
import Pagination from "@/components/Pagination";
|
import Pagination from "@/components/Pagination";
|
||||||
import PostRow from "@/components/PostRow";
|
import PostRow from "@/components/PostRow";
|
||||||
import FeedTabs, { type FeedSort } from "@/components/home/FeedTabs";
|
import FeedTabs, { type FeedSort } from "@/components/home/FeedTabs";
|
||||||
|
import FeedNewTip from "@/components/home/FeedNewTip";
|
||||||
import { WorkspaceNav, WorkspaceNavMobile } from "@/components/home/WorkspaceNav";
|
import { WorkspaceNav, WorkspaceNavMobile } from "@/components/home/WorkspaceNav";
|
||||||
import { CommunityPanels, CommunityPanelsMobile } from "@/components/home/CommunityPanels";
|
import { CommunityPanels, CommunityPanelsMobile } from "@/components/home/CommunityPanels";
|
||||||
|
|
||||||
@@ -158,6 +159,14 @@ export default async function HomePage({ searchParams }: HomePageProps) {
|
|||||||
共 {postsData.total} 篇
|
共 {postsData.total} 篇
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
{user && (
|
||||||
|
<FeedNewTip
|
||||||
|
sort={sort}
|
||||||
|
boardId={boardId}
|
||||||
|
page={page}
|
||||||
|
userId={user.id}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{postsData.posts.length > 0 ? (
|
{postsData.posts.length > 0 ? (
|
||||||
postsData.posts.map((post, i) => (
|
postsData.posts.map((post, i) => (
|
||||||
<PostRow
|
<PostRow
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ import PostToc, { type TocItem } from "@/components/PostToc";
|
|||||||
import MobilePostBar from "@/components/MobilePostBar";
|
import MobilePostBar from "@/components/MobilePostBar";
|
||||||
import Avatar from "@/components/Avatar";
|
import Avatar from "@/components/Avatar";
|
||||||
import RoleBadge from "@/components/RoleBadge";
|
import RoleBadge from "@/components/RoleBadge";
|
||||||
import { isStaff } from "@/lib/roles";
|
import { canModerateBoard } from "@/lib/roles";
|
||||||
import { IconComment, IconEye } from "@/components/Icons";
|
import { IconComment, IconEye } from "@/components/Icons";
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
@@ -340,7 +340,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
|||||||
|
|
||||||
// 非公开帖(待审/未通过)仅作者本人与管理团队可看,顶部给出醒目状态
|
// 非公开帖(待审/未通过)仅作者本人与管理团队可看,顶部给出醒目状态
|
||||||
const isPublished = post.status === "published";
|
const isPublished = post.status === "published";
|
||||||
const canSeeStatus = !!me.user && (me.user.id === post.user.id || isStaff(me.user.role));
|
const canSeeStatus = !!me.user && (me.user.id === post.user.id || canModerateBoard(me.user, post.board_id));
|
||||||
|
|
||||||
const jsonLd = {
|
const jsonLd = {
|
||||||
"@context": "https://schema.org",
|
"@context": "https://schema.org",
|
||||||
|
|||||||
36
frontend/app/u/[id]/StartDMButton.tsx
Normal file
36
frontend/app/u/[id]/StartDMButton.tsx
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { MessageSquare } from "lucide-react";
|
||||||
|
import { apiOpenDirectChat } from "@/lib/api";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
|
||||||
|
/** 用户主页:发起私聊 */
|
||||||
|
export default function StartDMButton({ userId }: { userId: number }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const start = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const { room } = await apiOpenDirectChat(userId);
|
||||||
|
router.push(`/chat/${room.id}`);
|
||||||
|
} catch (e) {
|
||||||
|
toast(e instanceof Error ? e.message : "无法发起私聊");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={start}
|
||||||
|
disabled={loading}
|
||||||
|
className="btn btn-accent btn-sm gap-1.5"
|
||||||
|
>
|
||||||
|
<MessageSquare size={14} />
|
||||||
|
{loading ? "打开中…" : "私聊"}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import PasswordForm from "./PasswordForm";
|
|||||||
import Avatar from "@/components/Avatar";
|
import Avatar from "@/components/Avatar";
|
||||||
import RoleBadge from "@/components/RoleBadge";
|
import RoleBadge from "@/components/RoleBadge";
|
||||||
import { roleMeta } from "@/lib/roles";
|
import { roleMeta } from "@/lib/roles";
|
||||||
|
import StartDMButton from "./StartDMButton";
|
||||||
|
|
||||||
interface UserPageProps {
|
interface UserPageProps {
|
||||||
params: Promise<{ id: string }>;
|
params: Promise<{ id: string }>;
|
||||||
@@ -132,8 +133,8 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 本人操作按钮 */}
|
{/* 本人操作按钮 / 访客私聊 */}
|
||||||
{isOwner && (
|
{isOwner ? (
|
||||||
<div className="absolute top-3 right-3 sm:top-4 sm:right-4 z-20 flex items-center gap-2">
|
<div className="absolute top-3 right-3 sm:top-4 sm:right-4 z-20 flex items-center gap-2">
|
||||||
<Link href={`/u/${id}?tab=settings`} className="btn btn-line btn-sm">
|
<Link href={`/u/${id}?tab=settings`} className="btn btn-line btn-sm">
|
||||||
<PenLine size={13.5} />
|
<PenLine size={13.5} />
|
||||||
@@ -148,7 +149,11 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
|
|||||||
<Shield size={14} />
|
<Shield size={14} />
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
)}
|
) : currentUser ? (
|
||||||
|
<div className="absolute top-3 right-3 sm:top-4 sm:right-4 z-20">
|
||||||
|
<StartDMButton userId={data.user.id} />
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{/* 身份信息:纯文档流,头像 + 右侧文字 baseline 对齐 */}
|
{/* 身份信息:纯文档流,头像 + 右侧文字 baseline 对齐 */}
|
||||||
<div className="relative z-10 px-5 sm:px-7 pt-5 sm:pt-6">
|
<div className="relative z-10 px-5 sm:px-7 pt-5 sm:pt-6">
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ export default function CommentSection({
|
|||||||
setContent("");
|
setContent("");
|
||||||
if (res.comment.status === "pending") {
|
if (res.comment.status === "pending") {
|
||||||
toast("已提交,等待审核通过后公开");
|
toast("已提交,等待审核通过后公开");
|
||||||
|
router.refresh();
|
||||||
} else {
|
} else {
|
||||||
// 新楼层在最后一页:刷新后由服务端直出最新分页
|
// 新楼层在最后一页:刷新后由服务端直出最新分页
|
||||||
router.refresh();
|
router.refresh();
|
||||||
@@ -91,6 +92,7 @@ export default function CommentSection({
|
|||||||
setReplyContent("");
|
setReplyContent("");
|
||||||
if (res.comment.status === "pending") {
|
if (res.comment.status === "pending") {
|
||||||
toast("已提交,等待审核通过后公开");
|
toast("已提交,等待审核通过后公开");
|
||||||
|
router.refresh();
|
||||||
} else {
|
} else {
|
||||||
// 刷新后由 SSR 直出新树(子评论全量挂在本楼)
|
// 刷新后由 SSR 直出新树(子评论全量挂在本楼)
|
||||||
router.refresh();
|
router.refresh();
|
||||||
@@ -221,6 +223,7 @@ export default function CommentSection({
|
|||||||
{c.user.nickname || c.user.username}
|
{c.user.nickname || c.user.username}
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
{c.status === "pending" && <span className="badge-pending shrink-0 !text-[10px] !py-0.5 !px-1.5">待审</span>}
|
||||||
{isReplyToReply && parent && (
|
{isReplyToReply && parent && (
|
||||||
<>
|
<>
|
||||||
<ChevronRight size={12} className="cmt-reply-arrow" aria-hidden="true" />
|
<ChevronRight size={12} className="cmt-reply-arrow" aria-hidden="true" />
|
||||||
@@ -301,6 +304,7 @@ export default function CommentSection({
|
|||||||
{c.user.nickname || c.user.username}
|
{c.user.nickname || c.user.username}
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
{c.status === "pending" && <span className="badge-pending shrink-0">待审</span>}
|
||||||
{floor && (
|
{floor && (
|
||||||
<a href={`#comment-${c.id}`} className="cmt-floor-label" aria-label={`楼层 ${floor}`}>
|
<a href={`#comment-${c.id}`} className="cmt-floor-label" aria-label={`楼层 ${floor}`}>
|
||||||
#{floor}
|
#{floor}
|
||||||
|
|||||||
84
frontend/components/ConfirmDialog.tsx
Normal file
84
frontend/components/ConfirmDialog.tsx
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { X } from "lucide-react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 站点风格确认框:仅取消/关闭可关,避免点遮罩误关。
|
||||||
|
* danger 主按钮使用 btn-danger,其余用 btn-accent。
|
||||||
|
*/
|
||||||
|
export default function ConfirmDialog({
|
||||||
|
open,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
confirmLabel = "确定",
|
||||||
|
cancelLabel = "取消",
|
||||||
|
danger = false,
|
||||||
|
busy = false,
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
title: string;
|
||||||
|
message: string;
|
||||||
|
confirmLabel?: string;
|
||||||
|
cancelLabel?: string;
|
||||||
|
danger?: boolean;
|
||||||
|
busy?: boolean;
|
||||||
|
onConfirm: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}) {
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-[1100] flex items-center justify-center p-4"
|
||||||
|
style={{ background: "rgba(0,0,0,0.55)" }}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-sm rounded-2xl p-5 j13-toast-in"
|
||||||
|
style={{ background: "var(--panel)", border: "1px solid var(--line)" }}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3 mb-3">
|
||||||
|
<h2
|
||||||
|
className="text-[16px] font-extrabold leading-snug"
|
||||||
|
style={{ color: "var(--ink)" }}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</h2>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onCancel}
|
||||||
|
disabled={busy}
|
||||||
|
aria-label="关闭"
|
||||||
|
className="w-7 h-7 shrink-0 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] transition-colors"
|
||||||
|
style={{ color: "var(--ink-3)" }}
|
||||||
|
>
|
||||||
|
<X size={15} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-[13.5px] leading-relaxed mb-5" style={{ color: "var(--ink-2)" }}>
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onCancel}
|
||||||
|
disabled={busy}
|
||||||
|
className="btn btn-line btn-sm"
|
||||||
|
>
|
||||||
|
{cancelLabel}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onConfirm}
|
||||||
|
disabled={busy}
|
||||||
|
className={`btn btn-sm ${danger ? "btn-danger" : "btn-accent"}`}
|
||||||
|
>
|
||||||
|
{busy ? "处理中…" : confirmLabel}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
136
frontend/components/ContextMenu.tsx
Normal file
136
frontend/components/ContextMenu.tsx
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
|
||||||
|
export type CtxMenuItem = {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
icon?: React.ReactNode;
|
||||||
|
danger?: boolean;
|
||||||
|
disabled?: boolean;
|
||||||
|
onClick: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一右键/长按浮层菜单(飞书式)。
|
||||||
|
* 定位会钳制在视口内;点击外侧或滚动关闭。
|
||||||
|
*/
|
||||||
|
export default function ContextMenu({
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
items,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
items: CtxMenuItem[];
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const close = () => onClose();
|
||||||
|
window.addEventListener("click", close);
|
||||||
|
window.addEventListener("scroll", close, true);
|
||||||
|
window.addEventListener("resize", close);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("click", close);
|
||||||
|
window.removeEventListener("scroll", close, true);
|
||||||
|
window.removeEventListener("resize", close);
|
||||||
|
};
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = ref.current;
|
||||||
|
if (!el) return;
|
||||||
|
const rect = el.getBoundingClientRect();
|
||||||
|
let left = x;
|
||||||
|
let top = y;
|
||||||
|
if (left + rect.width > window.innerWidth - 8) {
|
||||||
|
left = Math.max(8, window.innerWidth - rect.width - 8);
|
||||||
|
}
|
||||||
|
if (top + rect.height > window.innerHeight - 8) {
|
||||||
|
top = Math.max(8, window.innerHeight - rect.height - 8);
|
||||||
|
}
|
||||||
|
el.style.left = `${left}px`;
|
||||||
|
el.style.top = `${top}px`;
|
||||||
|
}, [x, y, items]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className="fixed z-[1200] min-w-[148px] rounded-xl py-1 shadow-lg j13-toast-in"
|
||||||
|
style={{
|
||||||
|
left: x,
|
||||||
|
top: y,
|
||||||
|
background: "var(--panel)",
|
||||||
|
border: "1px solid var(--line)",
|
||||||
|
}}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
onContextMenu={(e) => e.preventDefault()}
|
||||||
|
>
|
||||||
|
{items.map((it) => (
|
||||||
|
<button
|
||||||
|
key={it.key}
|
||||||
|
type="button"
|
||||||
|
disabled={it.disabled}
|
||||||
|
className="w-full flex items-center gap-2.5 px-3.5 py-2 text-[13px] text-left transition-colors disabled:opacity-40"
|
||||||
|
style={{
|
||||||
|
color: it.danger ? "var(--danger)" : "var(--ink)",
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e) => {
|
||||||
|
e.currentTarget.style.background = it.danger
|
||||||
|
? "var(--danger-soft)"
|
||||||
|
: "var(--accent-soft)";
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e) => {
|
||||||
|
e.currentTarget.style.background = "transparent";
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
if (it.disabled) return;
|
||||||
|
onClose();
|
||||||
|
it.onClick();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{it.icon}
|
||||||
|
{it.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 绑定桌面右键 + 移动端长按,打开菜单 */
|
||||||
|
export function usePressMenu(
|
||||||
|
openAt: (x: number, y: number) => void
|
||||||
|
): {
|
||||||
|
onContextMenu: (e: React.MouseEvent) => void;
|
||||||
|
onTouchStart: (e: React.TouchEvent) => void;
|
||||||
|
onTouchEnd: () => void;
|
||||||
|
onTouchMove: () => void;
|
||||||
|
} {
|
||||||
|
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const clear = () => {
|
||||||
|
if (timer.current) {
|
||||||
|
clearTimeout(timer.current);
|
||||||
|
timer.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
onContextMenu: (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
openAt(e.clientX, e.clientY);
|
||||||
|
},
|
||||||
|
onTouchStart: (e) => {
|
||||||
|
const t = e.touches[0];
|
||||||
|
if (!t) return;
|
||||||
|
clear();
|
||||||
|
timer.current = setTimeout(() => {
|
||||||
|
openAt(t.clientX, t.clientY);
|
||||||
|
}, 480);
|
||||||
|
},
|
||||||
|
onTouchEnd: clear,
|
||||||
|
onTouchMove: clear,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -19,21 +19,26 @@ import {
|
|||||||
User as UserIcon,
|
User as UserIcon,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ShieldCheck,
|
ShieldCheck,
|
||||||
|
MessageSquare,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { apiLogout, apiMe, type User } from "@/lib/api";
|
import { apiLogout, apiMe, apiChatUnreadSummary, type User } from "@/lib/api";
|
||||||
import { hasAuthCookieHint } from "@/lib/cookies";
|
import { hasAuthCookieHint } from "@/lib/cookies";
|
||||||
import { isStaff } from "@/lib/roles";
|
import { isStaff } from "@/lib/roles";
|
||||||
import { onUserUpdate, onForceLogout } from "@/lib/userEvents";
|
import { onUserUpdate, onForceLogout } from "@/lib/userEvents";
|
||||||
|
import { realtime, RT_CHAT_UNREAD } from "@/lib/realtime";
|
||||||
|
import type { RtChatUnreadData } from "@/lib/realtime";
|
||||||
import NotificationBell from "./NotificationBell";
|
import NotificationBell from "./NotificationBell";
|
||||||
import Avatar from "./Avatar";
|
import Avatar from "./Avatar";
|
||||||
|
|
||||||
export default function Header({
|
export default function Header({
|
||||||
initialUser,
|
initialUser,
|
||||||
initialUnread = 0,
|
initialUnread = 0,
|
||||||
|
initialChatUnread = 0,
|
||||||
initialTheme = "light",
|
initialTheme = "light",
|
||||||
}: {
|
}: {
|
||||||
initialUser: User | null;
|
initialUser: User | null;
|
||||||
initialUnread?: number;
|
initialUnread?: number;
|
||||||
|
initialChatUnread?: number;
|
||||||
initialTheme?: "light" | "dark";
|
initialTheme?: "light" | "dark";
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -43,6 +48,7 @@ export default function Header({
|
|||||||
// 登录态以 SSR 直出为初始值,F5 无切换闪动;router.refresh() 后随 props 校正
|
// 登录态以 SSR 直出为初始值,F5 无切换闪动;router.refresh() 后随 props 校正
|
||||||
const [user, setUser] = useState<User | null>(initialUser);
|
const [user, setUser] = useState<User | null>(initialUser);
|
||||||
const [unread, setUnread] = useState(initialUnread);
|
const [unread, setUnread] = useState(initialUnread);
|
||||||
|
const [chatUnread, setChatUnread] = useState(initialChatUnread);
|
||||||
const [searchQuery, setSearchQuery] = useState("");
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
@@ -55,6 +61,10 @@ export default function Header({
|
|||||||
setUnread(initialUnread);
|
setUnread(initialUnread);
|
||||||
}, [initialUnread]);
|
}, [initialUnread]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setChatUnread(initialChatUnread);
|
||||||
|
}, [initialChatUnread]);
|
||||||
|
|
||||||
// 同页内资料变更(如上传/删除头像)立即生效,不依赖 router.refresh 时序
|
// 同页内资料变更(如上传/删除头像)立即生效,不依赖 router.refresh 时序
|
||||||
useEffect(() => onUserUpdate((patch) => {
|
useEffect(() => onUserUpdate((patch) => {
|
||||||
setUser((prev) => (prev ? { ...prev, ...patch } : prev));
|
setUser((prev) => (prev ? { ...prev, ...patch } : prev));
|
||||||
@@ -84,10 +94,49 @@ export default function Header({
|
|||||||
.then((res) => {
|
.then((res) => {
|
||||||
setUser(res.user);
|
setUser(res.user);
|
||||||
if (typeof res.unread_count === "number") setUnread(res.unread_count);
|
if (typeof res.unread_count === "number") setUnread(res.unread_count);
|
||||||
|
if (typeof res.chat_unread_count === "number")
|
||||||
|
setChatUnread(res.chat_unread_count);
|
||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// 实时未读:chat:unread 推送给所有成员(含未打开会话页);在当前会话页则忽略
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user) return;
|
||||||
|
const off = realtime.on<RtChatUnreadData>(RT_CHAT_UNREAD, (data) => {
|
||||||
|
if (!data || typeof data.room_id !== "number") return;
|
||||||
|
if (pathname === `/chat/${data.room_id}`) return;
|
||||||
|
const delta = typeof data.delta === "number" ? data.delta : 1;
|
||||||
|
setChatUnread((c) => Math.max(0, c + delta));
|
||||||
|
});
|
||||||
|
return off;
|
||||||
|
}, [user, pathname]);
|
||||||
|
|
||||||
|
// 会话内已读后主动对账(ChatRoomClient 派发)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user) return;
|
||||||
|
const onSync = () => {
|
||||||
|
apiChatUnreadSummary()
|
||||||
|
.then((res) => setChatUnread(res.total || 0))
|
||||||
|
.catch(() => {});
|
||||||
|
};
|
||||||
|
window.addEventListener("j13-chat-unread-sync", onSync);
|
||||||
|
return () => window.removeEventListener("j13-chat-unread-sync", onSync);
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
// 切回标签页时重新对账未读
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user) return;
|
||||||
|
const onVisible = () => {
|
||||||
|
if (document.visibilityState !== "visible") return;
|
||||||
|
apiChatUnreadSummary()
|
||||||
|
.then((res) => setChatUnread(res.total || 0))
|
||||||
|
.catch(() => {});
|
||||||
|
};
|
||||||
|
document.addEventListener("visibilitychange", onVisible);
|
||||||
|
return () => document.removeEventListener("visibilitychange", onVisible);
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
const handleSearch = (e: React.FormEvent) => {
|
const handleSearch = (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const q = searchQuery.trim();
|
const q = searchQuery.trim();
|
||||||
@@ -237,6 +286,39 @@ export default function Header({
|
|||||||
>
|
>
|
||||||
{theme === "dark" ? <Sun size={17} /> : <Moon size={17} />}
|
{theme === "dark" ? <Sun size={17} /> : <Moon size={17} />}
|
||||||
</button>
|
</button>
|
||||||
|
{user && (
|
||||||
|
<Link
|
||||||
|
href="/chat"
|
||||||
|
prefetch={false}
|
||||||
|
aria-label="消息"
|
||||||
|
className="relative inline-flex items-center justify-center w-10 h-10 rounded-full transition-colors"
|
||||||
|
style={{
|
||||||
|
color: pathname?.startsWith("/chat")
|
||||||
|
? "var(--accent)"
|
||||||
|
: "var(--ink-2)",
|
||||||
|
border: `1px solid ${
|
||||||
|
pathname?.startsWith("/chat") ? "var(--accent)" : "var(--line)"
|
||||||
|
}`,
|
||||||
|
background: pathname?.startsWith("/chat")
|
||||||
|
? "var(--accent-soft)"
|
||||||
|
: "var(--panel)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MessageSquare size={17} />
|
||||||
|
{chatUnread > 0 && (
|
||||||
|
<span
|
||||||
|
className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 text-[10px] font-bold flex items-center justify-center rounded-full"
|
||||||
|
style={{
|
||||||
|
background: "var(--clay)",
|
||||||
|
color: "#fff",
|
||||||
|
border: "2px solid var(--bg)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{chatUnread > 99 ? "99+" : chatUnread}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
{user && <NotificationBell initialUnread={unread} />}
|
{user && <NotificationBell initialUnread={unread} />}
|
||||||
{user ? (
|
{user ? (
|
||||||
<>
|
<>
|
||||||
@@ -289,6 +371,21 @@ export default function Header({
|
|||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<MobileLink href="/" active={pathname === "/"}>首页</MobileLink>
|
<MobileLink href="/" active={pathname === "/"}>首页</MobileLink>
|
||||||
{user && <MobileLink href="/compose">发帖</MobileLink>}
|
{user && <MobileLink href="/compose">发帖</MobileLink>}
|
||||||
|
{user && (
|
||||||
|
<MobileLink href="/chat" active={pathname?.startsWith("/chat") ?? false}>
|
||||||
|
<span className="inline-flex items-center gap-2">
|
||||||
|
<MessageSquare size={15} /> 消息
|
||||||
|
{chatUnread > 0 && (
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center justify-center min-w-[16px] h-4 px-1 text-[10px] font-bold rounded-full"
|
||||||
|
style={{ background: "var(--clay)", color: "#fff" }}
|
||||||
|
>
|
||||||
|
{chatUnread > 99 ? "99+" : chatUnread}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</MobileLink>
|
||||||
|
)}
|
||||||
{user && (
|
{user && (
|
||||||
<MobileLink href="/notifications">
|
<MobileLink href="/notifications">
|
||||||
<span className="inline-flex items-center gap-2"><Bell size={15} /> 通知中心</span>
|
<span className="inline-flex items-center gap-2"><Bell size={15} /> 通知中心</span>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { useState, useEffect, useRef } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Bell, CheckCheck, Heart, MessageCircle, CheckCircle2, XCircle } from "lucide-react";
|
import { Bell, CheckCheck, Heart, MessageCircle, CheckCircle2, XCircle, AtSign, ClipboardList } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
apiFetchNotifications,
|
apiFetchNotifications,
|
||||||
apiUnreadCount,
|
apiUnreadCount,
|
||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
apiMarkAllRead,
|
apiMarkAllRead,
|
||||||
type NotificationItem,
|
type NotificationItem,
|
||||||
} from "@/lib/api";
|
} from "@/lib/api";
|
||||||
|
import { realtime, RT_NOTIFICATION_NEW } from "@/lib/realtime";
|
||||||
|
|
||||||
export default function NotificationBell({ initialUnread = 0 }: { initialUnread?: number }) {
|
export default function NotificationBell({ initialUnread = 0 }: { initialUnread?: number }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -21,10 +22,11 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
// 轮询未读数(30 秒);页面从后台切回时立即探测一次,
|
// 未读数:WS 推送后拉取校准;回前台再对账(无定时轮询)
|
||||||
// 使账号被封禁等服务端状态变化在用户切回标签页的瞬间即可被发现
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
const fetchCount = () => {
|
const fetchCount = () => {
|
||||||
apiUnreadCount()
|
apiUnreadCount()
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
@@ -32,18 +34,28 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
|
|||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const fetchCountDebounced = () => {
|
||||||
|
if (debounceTimer) clearTimeout(debounceTimer);
|
||||||
|
debounceTimer = setTimeout(fetchCount, 200);
|
||||||
|
};
|
||||||
|
|
||||||
fetchCount();
|
fetchCount();
|
||||||
const timer = setInterval(fetchCount, 30000);
|
const off = realtime.on(RT_NOTIFICATION_NEW, () => {
|
||||||
|
fetchCountDebounced();
|
||||||
|
if (open) loadNotifications();
|
||||||
|
});
|
||||||
const onVisible = () => {
|
const onVisible = () => {
|
||||||
if (document.visibilityState === "visible") fetchCount();
|
if (document.visibilityState === "visible") fetchCount();
|
||||||
};
|
};
|
||||||
document.addEventListener("visibilitychange", onVisible);
|
document.addEventListener("visibilitychange", onVisible);
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
clearInterval(timer);
|
if (debounceTimer) clearTimeout(debounceTimer);
|
||||||
|
off();
|
||||||
document.removeEventListener("visibilitychange", onVisible);
|
document.removeEventListener("visibilitychange", onVisible);
|
||||||
};
|
};
|
||||||
}, []);
|
}, [open]);
|
||||||
|
|
||||||
// 点击外部关闭下拉
|
// 点击外部关闭下拉
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -84,7 +96,14 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
router.push(`/post/${n.post_id}`);
|
// @提及通知跳到群聊房间;其余跳到帖子/评论
|
||||||
|
if (n.type === "mention" && n.room_id) {
|
||||||
|
router.push(`/chat/${n.room_id}`);
|
||||||
|
} else if (n.type === "pending_review") {
|
||||||
|
router.push(n.post_id ? `/post/${n.post_id}` : "/admin/moderation");
|
||||||
|
} else {
|
||||||
|
router.push(`/post/${n.post_id}`);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMarkAllRead = async () => {
|
const handleMarkAllRead = async () => {
|
||||||
@@ -109,6 +128,8 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
|
|||||||
if (n.type === "reply") return "回复了你的评论";
|
if (n.type === "reply") return "回复了你的评论";
|
||||||
if (n.type === "approved") return "审核通过";
|
if (n.type === "approved") return "审核通过";
|
||||||
if (n.type === "rejected") return "未通过审核";
|
if (n.type === "rejected") return "未通过审核";
|
||||||
|
if (n.type === "mention") return "在消息中提到了你";
|
||||||
|
if (n.type === "pending_review") return "有新内容待审核";
|
||||||
return "点赞了你的帖子";
|
return "点赞了你的帖子";
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -121,6 +142,10 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
|
|||||||
return { color: "var(--danger)", bg: "var(--danger-soft)", node: <XCircle size={15} /> };
|
return { color: "var(--danger)", bg: "var(--danger-soft)", node: <XCircle size={15} /> };
|
||||||
if (n.type === "like")
|
if (n.type === "like")
|
||||||
return { color: "var(--clay)", bg: "var(--clay-soft)", node: <Heart size={15} /> };
|
return { color: "var(--clay)", bg: "var(--clay-soft)", node: <Heart size={15} /> };
|
||||||
|
if (n.type === "mention")
|
||||||
|
return { color: "var(--accent)", bg: "var(--accent-soft)", node: <AtSign size={15} /> };
|
||||||
|
if (n.type === "pending_review")
|
||||||
|
return { color: "var(--accent)", bg: "var(--accent-soft)", node: <ClipboardList size={15} /> };
|
||||||
return { color: "var(--accent)", bg: "var(--accent-soft)", node: <MessageCircle size={15} /> };
|
return { color: "var(--accent)", bg: "var(--accent-soft)", node: <MessageCircle size={15} /> };
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -221,9 +246,19 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs mt-1 truncate" style={{ color: "var(--ink-2)" }}>
|
{n.type === "mention" ? (
|
||||||
《{n.post.title}》
|
n.room && (
|
||||||
</p>
|
<p className="text-xs mt-1 truncate" style={{ color: "var(--ink-2)" }}>
|
||||||
|
# {n.room.name}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
n.post && (
|
||||||
|
<p className="text-xs mt-1 truncate" style={{ color: "var(--ink-2)" }}>
|
||||||
|
《{n.post.title}》
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
)}
|
||||||
{n.content && (
|
{n.content && (
|
||||||
<p className="text-xs mt-1 line-clamp-1" style={{ color: "var(--ink-3)" }}>
|
<p className="text-xs mt-1 line-clamp-1" style={{ color: "var(--ink-3)" }}>
|
||||||
{n.content}
|
{n.content}
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ export default function PostRow({
|
|||||||
<div className="flex items-center gap-2 min-w-0">
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
{post.pinned > 0 && <span className="badge-pin shrink-0">置顶</span>}
|
{post.pinned > 0 && <span className="badge-pin shrink-0">置顶</span>}
|
||||||
{post.recommended && <span className="badge-rec shrink-0">推荐</span>}
|
{post.recommended && <span className="badge-rec shrink-0">推荐</span>}
|
||||||
|
{post.status === "pending" && <span className="badge-pending shrink-0">待审</span>}
|
||||||
<Link
|
<Link
|
||||||
href={`/post/${post.id}`}
|
href={`/post/${post.id}`}
|
||||||
className="stretch-link min-w-0 flex-1"
|
className="stretch-link min-w-0 flex-1"
|
||||||
|
|||||||
18
frontend/components/RealtimeProvider.tsx
Normal file
18
frontend/components/RealtimeProvider.tsx
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { realtime } from "@/lib/realtime";
|
||||||
|
|
||||||
|
// 实时总线生命周期:登录即连、登出即断;连接/重连/心跳全部封装在 lib/realtime。
|
||||||
|
// 挂在持久 root layout 上,全标签页只维护一条 WebSocket。
|
||||||
|
export default function RealtimeProvider({ userId }: { userId: number | null }) {
|
||||||
|
useEffect(() => {
|
||||||
|
if (userId) {
|
||||||
|
realtime.connect();
|
||||||
|
return () => realtime.disconnect();
|
||||||
|
}
|
||||||
|
realtime.disconnect();
|
||||||
|
}, [userId]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -4,12 +4,12 @@ import { useEffect, useRef } from "react";
|
|||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { apiGetSettings } from "@/lib/api";
|
import { apiGetSettings } from "@/lib/api";
|
||||||
import { applyAccentTheme } from "@/lib/theme";
|
import { applyAccentTheme } from "@/lib/theme";
|
||||||
|
import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime";
|
||||||
|
|
||||||
// 站点主题色同步器:
|
// 站点主题色同步器:
|
||||||
// 主题色由管理员在后台修改后,其他用户已打开的标签页不会因软导航重新执行根布局
|
// 主题色由管理员在后台修改后,其他用户已打开的标签页不会因软导航重新执行根布局
|
||||||
// SSR,本组件通过轮询 + 标签页重新可见/获焦时探测公开设置,发现变化即热替换
|
// SSR,本组件通过 WS 推送 + 标签页重新可见/获焦时探测公开设置,发现变化即热替换
|
||||||
// accent CSS 变量(复用 lib/theme 的运行时 style 节点),无需 F5 即可换肤。
|
// accent CSS 变量(复用 lib/theme 的运行时 style 节点),无需 F5 即可换肤。
|
||||||
const POLL_INTERVAL_MS = 60_000;
|
|
||||||
// 焦点/可见性事件可能短时间连续触发,限制实际请求间隔
|
// 焦点/可见性事件可能短时间连续触发,限制实际请求间隔
|
||||||
const MIN_FETCH_GAP_MS = 10_000;
|
const MIN_FETCH_GAP_MS = 10_000;
|
||||||
|
|
||||||
@@ -27,6 +27,12 @@ export default function ThemeSync({ initialAccent }: { initialAccent: string })
|
|||||||
|
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
|
||||||
|
const apply = (next: string) => {
|
||||||
|
if (cancelled || next === currentRef.current) return;
|
||||||
|
currentRef.current = next;
|
||||||
|
applyAccentTheme(next || null);
|
||||||
|
};
|
||||||
|
|
||||||
const sync = async () => {
|
const sync = async () => {
|
||||||
if (inFlightRef.current) return;
|
if (inFlightRef.current) return;
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -37,18 +43,19 @@ export default function ThemeSync({ initialAccent }: { initialAccent: string })
|
|||||||
// no-store:必须拿到管理员刚保存的最新值,不能走浏览器缓存
|
// no-store:必须拿到管理员刚保存的最新值,不能走浏览器缓存
|
||||||
const { accent } = await apiGetSettings();
|
const { accent } = await apiGetSettings();
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
const next = (accent || "").trim().toLowerCase();
|
apply((accent || "").trim().toLowerCase());
|
||||||
if (next !== currentRef.current) {
|
|
||||||
currentRef.current = next;
|
|
||||||
applyAccentTheme(next || null);
|
|
||||||
}
|
|
||||||
} catch {
|
} catch {
|
||||||
// 主题同步失败静默处理,下个周期/下次回前台再试,不打扰用户
|
// 主题同步失败静默处理,下次回前台再试,不打扰用户
|
||||||
} finally {
|
} finally {
|
||||||
inFlightRef.current = false;
|
inFlightRef.current = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// WebSocket 推送优先:管理员保存即换肤;回前台 HTTP 校准兜底
|
||||||
|
const offPush = realtime.on<RtSettingsData>(RT_SETTINGS_CHANGED, (data) => {
|
||||||
|
if (data) apply((data.accent || "").trim().toLowerCase());
|
||||||
|
});
|
||||||
|
|
||||||
const onActive = () => {
|
const onActive = () => {
|
||||||
if (document.visibilityState === "visible") void sync();
|
if (document.visibilityState === "visible") void sync();
|
||||||
};
|
};
|
||||||
@@ -56,13 +63,12 @@ export default function ThemeSync({ initialAccent }: { initialAccent: string })
|
|||||||
window.addEventListener("focus", onActive);
|
window.addEventListener("focus", onActive);
|
||||||
// 离开外观页等 pathname 变化时立刻对齐一次(受 MIN_FETCH_GAP 限频)
|
// 离开外观页等 pathname 变化时立刻对齐一次(受 MIN_FETCH_GAP 限频)
|
||||||
void sync();
|
void sync();
|
||||||
const timer = setInterval(() => void sync(), POLL_INTERVAL_MS);
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
|
offPush();
|
||||||
document.removeEventListener("visibilitychange", onActive);
|
document.removeEventListener("visibilitychange", onActive);
|
||||||
window.removeEventListener("focus", onActive);
|
window.removeEventListener("focus", onActive);
|
||||||
clearInterval(timer);
|
|
||||||
};
|
};
|
||||||
}, [pathname]);
|
}, [pathname]);
|
||||||
|
|
||||||
|
|||||||
75
frontend/components/home/FeedNewTip.tsx
Normal file
75
frontend/components/home/FeedNewTip.tsx
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { ArrowUp } from "lucide-react";
|
||||||
|
import {
|
||||||
|
realtime,
|
||||||
|
RT_FEED_CHANGED,
|
||||||
|
type RtFeedChangedData,
|
||||||
|
} from "@/lib/realtime";
|
||||||
|
import type { FeedSort } from "@/components/home/FeedTabs";
|
||||||
|
|
||||||
|
interface FeedNewTipProps {
|
||||||
|
sort: FeedSort;
|
||||||
|
boardId?: number;
|
||||||
|
page?: number;
|
||||||
|
userId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 帖子流「有新内容」提示(三期):WS feed:changed → tip → 点击 refresh SSR
|
||||||
|
export default function FeedNewTip({
|
||||||
|
sort,
|
||||||
|
boardId = 0,
|
||||||
|
page = 1,
|
||||||
|
userId,
|
||||||
|
}: FeedNewTipProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [visible, setVisible] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// 第 2+ 页与推荐帖不订阅展示(推荐不随新帖/新评变化)
|
||||||
|
if (page !== 1 || sort === "recommended") {
|
||||||
|
setVisible(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const off = realtime.on<RtFeedChangedData>(RT_FEED_CHANGED, (data) => {
|
||||||
|
if (!data || typeof data.post_id !== "number") return;
|
||||||
|
// 忽略自己刚发布的内容,避免回首页又弹 tip
|
||||||
|
if (data.actor_id === userId) return;
|
||||||
|
if (boardId > 0 && data.board_id !== boardId) return;
|
||||||
|
// 「新帖子」tab 只关心新帖;「新评论」tab 接受帖与评
|
||||||
|
if (sort === "new" && data.kind !== "post") return;
|
||||||
|
if (data.kind !== "post" && data.kind !== "comment") return;
|
||||||
|
setVisible(true);
|
||||||
|
});
|
||||||
|
return off;
|
||||||
|
}, [sort, boardId, page, userId]);
|
||||||
|
|
||||||
|
if (!visible || page !== 1 || sort === "recommended") return null;
|
||||||
|
|
||||||
|
const handleClick = () => {
|
||||||
|
setVisible(false);
|
||||||
|
router.refresh();
|
||||||
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="px-3 sm:px-4 pb-2.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleClick}
|
||||||
|
className="j13-feed-new-tip w-full inline-flex items-center justify-center gap-1.5 py-2 px-3 text-[13px] font-semibold rounded-[var(--r-sm)] transition-colors"
|
||||||
|
style={{
|
||||||
|
color: "var(--accent)",
|
||||||
|
background: "var(--accent-soft)",
|
||||||
|
border: "1px solid var(--nav-active-line, var(--accent))",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ArrowUp size={14} aria-hidden />
|
||||||
|
有新内容
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -38,6 +38,8 @@ export interface User {
|
|||||||
export interface MeResponse {
|
export interface MeResponse {
|
||||||
user: User | null;
|
user: User | null;
|
||||||
unread_count: number;
|
unread_count: number;
|
||||||
|
// 群聊未读消息总数(二期)
|
||||||
|
chat_unread_count?: number;
|
||||||
// 后端 OptionalAuth 识别到凭据所属账号已封禁时携带(HTTP 仍 200,不阻断页面)
|
// 后端 OptionalAuth 识别到凭据所属账号已封禁时携带(HTTP 仍 200,不阻断页面)
|
||||||
banned?: boolean;
|
banned?: boolean;
|
||||||
code?: string;
|
code?: string;
|
||||||
@@ -144,6 +146,7 @@ export interface PostListItem {
|
|||||||
like_count: number;
|
like_count: number;
|
||||||
view_count: number;
|
view_count: number;
|
||||||
comment_count: number;
|
comment_count: number;
|
||||||
|
status?: string;
|
||||||
liked: boolean;
|
liked: boolean;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
last_reply?: {
|
last_reply?: {
|
||||||
@@ -251,14 +254,17 @@ export interface NotificationItem {
|
|||||||
id: number;
|
id: number;
|
||||||
user_id: number;
|
user_id: number;
|
||||||
actor_id: number;
|
actor_id: number;
|
||||||
type: "comment" | "reply" | "like" | "approved" | "rejected";
|
type: "comment" | "reply" | "like" | "approved" | "rejected" | "mention" | "pending_review";
|
||||||
post_id: number;
|
post_id: number;
|
||||||
comment_id: number;
|
comment_id: number;
|
||||||
|
room_id?: number;
|
||||||
|
message_id?: number;
|
||||||
content: string;
|
content: string;
|
||||||
is_read: boolean;
|
is_read: boolean;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
actor: User;
|
actor: User;
|
||||||
post: { id: number; title: string };
|
post?: { id: number; title: string };
|
||||||
|
room?: { id: number; name: string } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface NotificationsResponse {
|
export interface NotificationsResponse {
|
||||||
@@ -890,6 +896,18 @@ export async function fetchAdminPendingPosts(
|
|||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** SSR 待审数量(帖子 + 评论);失败时返回零,不阻塞仪表盘 */
|
||||||
|
export async function fetchAdminPendingCounts(
|
||||||
|
cookieHeader?: string
|
||||||
|
): Promise<PendingCounts> {
|
||||||
|
const res = await fetch(
|
||||||
|
`${API_BASE}/api/admin/moderation/counts`,
|
||||||
|
ssrInit(cookieHeaders(cookieHeader))
|
||||||
|
);
|
||||||
|
if (!res.ok) return { posts: 0, comments: 0 };
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
// 客户端后台用户列表(走 rewrite,携带 cookie + CSRF)
|
// 客户端后台用户列表(走 rewrite,携带 cookie + CSRF)
|
||||||
export async function apiAdminListUsers(query: AdminUsersQuery = {}): Promise<AdminUsersResponse> {
|
export async function apiAdminListUsers(query: AdminUsersQuery = {}): Promise<AdminUsersResponse> {
|
||||||
const res = await fetchWithRefresh(`/api/admin/users?${adminUsersParams(query)}`, {
|
const res = await fetchWithRefresh(`/api/admin/users?${adminUsersParams(query)}`, {
|
||||||
@@ -946,6 +964,115 @@ export async function apiAdminSetUserBan(
|
|||||||
return data as { user: AdminUser };
|
return data as { user: AdminUser };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== 站长用户内容档案 =====
|
||||||
|
|
||||||
|
export interface AdminUserAuditProfile {
|
||||||
|
user: AdminUser;
|
||||||
|
posts_total: number;
|
||||||
|
comments_total: number;
|
||||||
|
messages_total: number;
|
||||||
|
published_posts: number;
|
||||||
|
published_comments: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminAuditPostItem {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
content: string;
|
||||||
|
status: string;
|
||||||
|
deleted: boolean;
|
||||||
|
board_id: number;
|
||||||
|
board_name: string;
|
||||||
|
created_at: string;
|
||||||
|
deleted_at?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminAuditCommentItem {
|
||||||
|
id: number;
|
||||||
|
post_id: number;
|
||||||
|
content: string;
|
||||||
|
status: string;
|
||||||
|
deleted: boolean;
|
||||||
|
created_at: string;
|
||||||
|
deleted_at?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminAuditMessageItem {
|
||||||
|
id: number;
|
||||||
|
room_id: number;
|
||||||
|
room_name: string;
|
||||||
|
room_type: string;
|
||||||
|
content: string;
|
||||||
|
recalled: boolean;
|
||||||
|
deleted: boolean;
|
||||||
|
created_at: string;
|
||||||
|
deleted_at?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminAuditListResponse<T> {
|
||||||
|
items: T[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchAdminUserAudit(
|
||||||
|
id: number,
|
||||||
|
cookieHeader?: string
|
||||||
|
): Promise<AdminUserAuditProfile> {
|
||||||
|
const res = await fetch(
|
||||||
|
`${API_BASE}/api/admin/users/${id}`,
|
||||||
|
ssrInit(cookieHeaders(cookieHeader))
|
||||||
|
);
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取用户档案失败");
|
||||||
|
return data as AdminUserAuditProfile;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function apiAdminUserAudit(id: number): Promise<AdminUserAuditProfile> {
|
||||||
|
const res = await fetchWithRefresh(`/api/admin/users/${id}`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取用户档案失败");
|
||||||
|
return data as AdminUserAuditProfile;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function apiAdminUserAuditPosts(
|
||||||
|
id: number,
|
||||||
|
page = 1
|
||||||
|
): Promise<AdminAuditListResponse<AdminAuditPostItem>> {
|
||||||
|
const res = await fetchWithRefresh(`/api/admin/users/${id}/posts?page=${page}`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取帖子失败");
|
||||||
|
return data as AdminAuditListResponse<AdminAuditPostItem>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function apiAdminUserAuditComments(
|
||||||
|
id: number,
|
||||||
|
page = 1
|
||||||
|
): Promise<AdminAuditListResponse<AdminAuditCommentItem>> {
|
||||||
|
const res = await fetchWithRefresh(`/api/admin/users/${id}/comments?page=${page}`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取评论失败");
|
||||||
|
return data as AdminAuditListResponse<AdminAuditCommentItem>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function apiAdminUserAuditMessages(
|
||||||
|
id: number,
|
||||||
|
page = 1
|
||||||
|
): Promise<AdminAuditListResponse<AdminAuditMessageItem>> {
|
||||||
|
const res = await fetchWithRefresh(`/api/admin/users/${id}/messages?page=${page}`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取消息失败");
|
||||||
|
return data as AdminAuditListResponse<AdminAuditMessageItem>;
|
||||||
|
}
|
||||||
|
|
||||||
// ===== 站点外观设置 =====
|
// ===== 站点外观设置 =====
|
||||||
|
|
||||||
export async function apiGetSettings(): Promise<PublicSettings> {
|
export async function apiGetSettings(): Promise<PublicSettings> {
|
||||||
@@ -1043,3 +1170,400 @@ export const apiAdminApproveComment = (id: number) =>
|
|||||||
moderationAction(`/api/admin/moderation/comments/${id}/approve`);
|
moderationAction(`/api/admin/moderation/comments/${id}/approve`);
|
||||||
export const apiAdminRejectComment = (id: number) =>
|
export const apiAdminRejectComment = (id: number) =>
|
||||||
moderationAction(`/api/admin/moderation/comments/${id}/reject`);
|
moderationAction(`/api/admin/moderation/comments/${id}/reject`);
|
||||||
|
|
||||||
|
// ===== 群聊(二期) =====
|
||||||
|
|
||||||
|
// 群聊房间基础模型(与后端 model.ChatRoom 对齐)
|
||||||
|
export interface ChatRoom {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
owner_id: number;
|
||||||
|
room_type: "group" | "direct";
|
||||||
|
member_count: number;
|
||||||
|
last_message_id: number;
|
||||||
|
is_private: boolean;
|
||||||
|
is_default: boolean;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
owner: User;
|
||||||
|
last_message?: ChatMessage | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 列表/详情聚合视图:扁平房间 + 当前访问者相关字段
|
||||||
|
export interface ChatRoomView extends ChatRoom {
|
||||||
|
joined: boolean;
|
||||||
|
my_role: "" | "owner" | "member" | "overseer";
|
||||||
|
unread_count: number;
|
||||||
|
pinned?: boolean;
|
||||||
|
pin_forced?: boolean;
|
||||||
|
peer?: User | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 群成员行(名单/踢人用)
|
||||||
|
export interface ChatRoomMember {
|
||||||
|
id: number;
|
||||||
|
room_id: number;
|
||||||
|
user_id: number;
|
||||||
|
role: "owner" | "member";
|
||||||
|
last_read_message_id: number;
|
||||||
|
muted: boolean;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
user: User;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 群消息(发送者已 Preload)
|
||||||
|
export interface ChatMessage {
|
||||||
|
id: number;
|
||||||
|
room_id: number;
|
||||||
|
sender_id: number;
|
||||||
|
content: string;
|
||||||
|
reply_to_id?: number;
|
||||||
|
reply_snap?: string;
|
||||||
|
created_at: string;
|
||||||
|
recalled_at?: string | null;
|
||||||
|
recalled_by?: number;
|
||||||
|
sender: User;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 单群未读明细
|
||||||
|
export interface UnreadRoom {
|
||||||
|
room_id: number;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatRoomsResponse {
|
||||||
|
rooms: ChatRoomView[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatMembersResponse {
|
||||||
|
members: ChatRoomMember[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatMessagesResponse {
|
||||||
|
messages: ChatMessage[];
|
||||||
|
has_more: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatUnreadSummaryResponse {
|
||||||
|
total: number;
|
||||||
|
rooms: UnreadRoom[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// SSR 消息会话列表(默认仅已加入)
|
||||||
|
export async function fetchChatRooms(
|
||||||
|
page = 1,
|
||||||
|
size = 40,
|
||||||
|
q = "",
|
||||||
|
cookieHeader?: string,
|
||||||
|
scope: "joined" | "all" = "joined"
|
||||||
|
): Promise<ChatRoomsResponse> {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
page: String(page),
|
||||||
|
size: String(size),
|
||||||
|
scope,
|
||||||
|
});
|
||||||
|
if (q) params.set("q", q);
|
||||||
|
const res = await fetch(
|
||||||
|
`${API_BASE}/api/chat/rooms?${params}`,
|
||||||
|
ssrInit(cookieHeaders(cookieHeader))
|
||||||
|
);
|
||||||
|
if (res.status === 401) throw new Error("未登录");
|
||||||
|
if (!res.ok) throw new Error("获取会话列表失败");
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// SSR 群详情:公开非成员 200(joined=false);私密非成员/不存在 404
|
||||||
|
export async function fetchChatRoom(
|
||||||
|
id: string,
|
||||||
|
cookieHeader?: string
|
||||||
|
): Promise<{ room: ChatRoomView }> {
|
||||||
|
const res = await fetch(
|
||||||
|
`${API_BASE}/api/chat/rooms/${id}`,
|
||||||
|
ssrInit(cookieHeaders(cookieHeader))
|
||||||
|
);
|
||||||
|
if (res.status === 401) throw new Error("未登录");
|
||||||
|
if (res.status === 404) throw new Error("群不存在");
|
||||||
|
if (!res.ok) throw new Error("获取群详情失败");
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// SSR 历史消息游标分页(成员可见;非成员抛错由页面层处理)
|
||||||
|
export async function fetchChatMessages(
|
||||||
|
id: string,
|
||||||
|
before = 0,
|
||||||
|
size = 30,
|
||||||
|
cookieHeader?: string
|
||||||
|
): Promise<ChatMessagesResponse> {
|
||||||
|
const params = new URLSearchParams({ size: String(size) });
|
||||||
|
if (before) params.set("before_id", String(before));
|
||||||
|
const res = await fetch(
|
||||||
|
`${API_BASE}/api/chat/rooms/${id}/messages?${params}`,
|
||||||
|
ssrInit(cookieHeaders(cookieHeader))
|
||||||
|
);
|
||||||
|
if (res.status === 401) throw new Error("未登录");
|
||||||
|
if (res.status === 403) throw new Error("无权查看消息");
|
||||||
|
if (res.status === 404) throw new Error("群不存在");
|
||||||
|
if (!res.ok) throw new Error("获取消息失败");
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:会话列表
|
||||||
|
export async function apiListChatRooms(
|
||||||
|
page = 1,
|
||||||
|
size = 40,
|
||||||
|
q = "",
|
||||||
|
scope: "joined" | "all" = "joined"
|
||||||
|
): Promise<ChatRoomsResponse> {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
page: String(page),
|
||||||
|
size: String(size),
|
||||||
|
scope,
|
||||||
|
});
|
||||||
|
if (q) params.set("q", q);
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms?${params}`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取会话列表失败");
|
||||||
|
return data as ChatRoomsResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:打开/创建私聊
|
||||||
|
export async function apiOpenDirectChat(
|
||||||
|
userId: number
|
||||||
|
): Promise<{ room: ChatRoomView }> {
|
||||||
|
const res = await fetchWithRefresh("/api/chat/direct", {
|
||||||
|
method: "POST",
|
||||||
|
headers: clientHeaders({ "Content-Type": "application/json" }),
|
||||||
|
body: JSON.stringify({ user_id: userId }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "无法发起私聊");
|
||||||
|
return data as { room: ChatRoomView };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:搜索用户以发起私聊
|
||||||
|
export async function apiSearchChatUsers(
|
||||||
|
q: string
|
||||||
|
): Promise<{ users: User[] }> {
|
||||||
|
const params = new URLSearchParams({ q });
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/users?${params}`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "搜索失败");
|
||||||
|
return data as { users: User[] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:建群(可公开/私密,私密可带初始成员用户名)
|
||||||
|
export async function apiCreateChatRoom(
|
||||||
|
name: string,
|
||||||
|
description = "",
|
||||||
|
opts?: { is_private?: boolean; member_usernames?: string[] }
|
||||||
|
): Promise<{ room: ChatRoomView }> {
|
||||||
|
const res = await fetchWithRefresh("/api/chat/rooms", {
|
||||||
|
method: "POST",
|
||||||
|
headers: clientHeaders({ "Content-Type": "application/json" }),
|
||||||
|
body: JSON.stringify({
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
is_private: opts?.is_private ?? false,
|
||||||
|
member_usernames: opts?.member_usernames ?? [],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "建群失败");
|
||||||
|
return data as { room: ChatRoomView };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:群详情
|
||||||
|
export async function apiGetChatRoom(id: number): Promise<{ room: ChatRoomView }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取群详情失败");
|
||||||
|
return data as { room: ChatRoomView };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:群主改群名/简介
|
||||||
|
export async function apiUpdateChatRoom(
|
||||||
|
id: number,
|
||||||
|
name: string,
|
||||||
|
description = ""
|
||||||
|
): Promise<{ room: ChatRoomView }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: clientHeaders({ "Content-Type": "application/json" }),
|
||||||
|
body: JSON.stringify({ name, description }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "修改群信息失败");
|
||||||
|
return data as { room: ChatRoomView };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:置顶/取消置顶(大厅强制置顶不可取消)
|
||||||
|
export async function apiPinChatRoom(
|
||||||
|
id: number,
|
||||||
|
pinned: boolean
|
||||||
|
): Promise<{ room: ChatRoomView }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/pin`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: clientHeaders({ "Content-Type": "application/json" }),
|
||||||
|
body: JSON.stringify({ pinned }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "置顶失败");
|
||||||
|
return data as { room: ChatRoomView };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:群主解散群
|
||||||
|
export async function apiDissolveChatRoom(id: number): Promise<{ ok: boolean }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "解散群失败");
|
||||||
|
return data as { ok: boolean };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:加入群聊
|
||||||
|
export async function apiJoinChatRoom(
|
||||||
|
id: number
|
||||||
|
): Promise<{ ok: boolean; joined: boolean }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/join`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "加入群失败");
|
||||||
|
return data as { ok: boolean; joined: boolean };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:退出群聊
|
||||||
|
export async function apiLeaveChatRoom(id: number): Promise<{ ok: boolean }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/leave`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "退出群失败");
|
||||||
|
return data as { ok: boolean };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:成员名单
|
||||||
|
export async function apiListChatMembers(
|
||||||
|
id: number
|
||||||
|
): Promise<ChatMembersResponse> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/members`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取成员名单失败");
|
||||||
|
return data as ChatMembersResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:群主踢人
|
||||||
|
export async function apiKickChatMember(
|
||||||
|
roomId: number,
|
||||||
|
userId: number
|
||||||
|
): Promise<{ ok: boolean }> {
|
||||||
|
const res = await fetchWithRefresh(
|
||||||
|
`/api/chat/rooms/${roomId}/members/${userId}`,
|
||||||
|
{ method: "DELETE", headers: clientHeaders() }
|
||||||
|
);
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "踢人失败");
|
||||||
|
return data as { ok: boolean };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:邀请成员(用户名列表,群主/监管)
|
||||||
|
export async function apiInviteChatMembers(
|
||||||
|
roomId: number,
|
||||||
|
usernames: string[]
|
||||||
|
): Promise<{ added: number[] }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${roomId}/members`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: clientHeaders({ "Content-Type": "application/json" }),
|
||||||
|
body: JSON.stringify({ usernames }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "邀请失败");
|
||||||
|
return data as { added: number[] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:撤回消息
|
||||||
|
export async function apiRecallChatMessage(
|
||||||
|
roomId: number,
|
||||||
|
messageId: number
|
||||||
|
): Promise<{ message: ChatMessage }> {
|
||||||
|
const res = await fetchWithRefresh(
|
||||||
|
`/api/chat/rooms/${roomId}/messages/${messageId}`,
|
||||||
|
{ method: "DELETE", headers: clientHeaders() }
|
||||||
|
);
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "撤回失败");
|
||||||
|
return data as { message: ChatMessage };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:历史消息游标分页
|
||||||
|
export async function apiListChatMessages(
|
||||||
|
id: number,
|
||||||
|
before = 0,
|
||||||
|
size = 30
|
||||||
|
): Promise<ChatMessagesResponse> {
|
||||||
|
const params = new URLSearchParams({ size: String(size) });
|
||||||
|
if (before) params.set("before_id", String(before));
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/messages?${params}`, {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "获取消息失败");
|
||||||
|
return data as ChatMessagesResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:发消息(可带引用;@ 提醒由后端解析)
|
||||||
|
export async function apiSendChatMessage(
|
||||||
|
id: number,
|
||||||
|
content: string,
|
||||||
|
replyToId = 0
|
||||||
|
): Promise<{ message: ChatMessage }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/messages`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: clientHeaders({ "Content-Type": "application/json" }),
|
||||||
|
body: JSON.stringify({ content, reply_to_id: replyToId || undefined }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "发送失败");
|
||||||
|
return data as { message: ChatMessage };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:推进已读水位(messageId=0 或超过最新则取最新)
|
||||||
|
export async function apiMarkChatRead(
|
||||||
|
id: number,
|
||||||
|
messageId = 0
|
||||||
|
): Promise<{ ok: boolean }> {
|
||||||
|
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/read`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: clientHeaders({ "Content-Type": "application/json" }),
|
||||||
|
body: JSON.stringify({ message_id: messageId }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || "标记已读失败");
|
||||||
|
return data as { ok: boolean };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 客户端:全部群未读明细与总数(Header 红点对账)
|
||||||
|
export async function apiChatUnreadSummary(): Promise<ChatUnreadSummaryResponse> {
|
||||||
|
const res = await fetchWithRefresh("/api/chat/unread-summary", {
|
||||||
|
headers: clientHeaders(),
|
||||||
|
});
|
||||||
|
if (!res.ok) return { total: 0, rooms: [] };
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|||||||
336
frontend/lib/realtime.ts
Normal file
336
frontend/lib/realtime.ts
Normal file
@@ -0,0 +1,336 @@
|
|||||||
|
// 全站实时总线客户端(一期:在线状态 + 站点设置变更;二期:群聊 + 站内通知;三期:帖子流有新内容)。
|
||||||
|
//
|
||||||
|
// - 单条 WebSocket(浏览器握手自动携带 HttpOnly cookie 鉴权),后续群聊/通知/
|
||||||
|
// 审核角标都复用本连接,按 message type 路由。
|
||||||
|
// - 连接状态机 + 指数退避重连;应用层心跳(协议层 Ping 由浏览器自动应答)。
|
||||||
|
// - 鉴权失效关闭码 4401 不自动重连(封禁/强制下线由 AccountGuard 统一处理)。
|
||||||
|
// - 在线集合:hello 帧给 staff 全量快照,之后 presence:update 增量维护。
|
||||||
|
// - 群聊:进入群详情页调用 joinRoom(roomID) 订阅 chat:{id} 房间,
|
||||||
|
// 重连后会自动重订当前已订阅集合;离开页面/退出群调用 leaveRoom。
|
||||||
|
// - 轮询仅作兜底:回前台 / 进页时 HTTP 校准;实时靠 WS(通知、待审、主题、群聊未读)。
|
||||||
|
|
||||||
|
export const RT_HELLO = "hello";
|
||||||
|
export const RT_PONG = "pong";
|
||||||
|
export const RT_SETTINGS_CHANGED = "settings:changed";
|
||||||
|
export const RT_PRESENCE_UPDATE = "presence:update";
|
||||||
|
export const RT_CHAT_MESSAGE = "chat:message";
|
||||||
|
export const RT_CHAT_MEMBERSHIP = "chat:membership";
|
||||||
|
export const RT_CHAT_RECALLED = "chat:message_recalled";
|
||||||
|
export const RT_CHAT_UNREAD = "chat:unread";
|
||||||
|
export const RT_NOTIFICATION_NEW = "notification:new";
|
||||||
|
export const RT_FEED_CHANGED = "feed:changed";
|
||||||
|
export const RT_MODERATION_CHANGED = "moderation:changed";
|
||||||
|
|
||||||
|
export interface RtEnvelope<T = unknown> {
|
||||||
|
type: string;
|
||||||
|
data?: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RtHelloData {
|
||||||
|
user_id: number;
|
||||||
|
ts: number;
|
||||||
|
// 仅管理团队成员会收到
|
||||||
|
online_user_ids?: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RtPresenceData {
|
||||||
|
user_id: number;
|
||||||
|
online: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RtSettingsData {
|
||||||
|
accent: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 群聊新消息:data 为落库的 ChatMessage(含 sender)
|
||||||
|
export interface RtChatMessageData {
|
||||||
|
id: number;
|
||||||
|
room_id: number;
|
||||||
|
sender_id: number;
|
||||||
|
content: string;
|
||||||
|
reply_to_id?: number;
|
||||||
|
reply_snap?: string;
|
||||||
|
created_at: string;
|
||||||
|
sender: {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
nickname: string;
|
||||||
|
avatar: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 群成员关系变更:被踢/群解散/被邀请
|
||||||
|
export interface RtChatMembershipData {
|
||||||
|
room_id: number;
|
||||||
|
status: "kicked" | "dissolved" | "invited";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 消息撤回
|
||||||
|
export interface RtChatRecalledData {
|
||||||
|
id: number;
|
||||||
|
room_id: number;
|
||||||
|
sender_id?: number;
|
||||||
|
recalled_by: number;
|
||||||
|
recalled_at?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 未读增量(推送给未在房内订阅的成员,用于 Header / 会话列表角标)
|
||||||
|
export interface RtChatUnreadData {
|
||||||
|
room_id: number;
|
||||||
|
message_id: number;
|
||||||
|
sender_id: number;
|
||||||
|
preview?: string;
|
||||||
|
delta: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 新站内通知(如群聊 @):收到后应刷新通知列表/红点
|
||||||
|
export interface RtNotificationData {
|
||||||
|
room_id?: number;
|
||||||
|
message_id?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 帖子流有公开新内容(三期):首页 tip「有新内容」
|
||||||
|
export interface RtFeedChangedData {
|
||||||
|
kind: "post" | "comment";
|
||||||
|
post_id: number;
|
||||||
|
board_id: number;
|
||||||
|
actor_id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
type RtHandler<T = unknown> = (data: T) => void;
|
||||||
|
type RtState = "idle" | "connecting" | "open" | "closed";
|
||||||
|
|
||||||
|
const HEARTBEAT_MS = 25_000;
|
||||||
|
const RECONNECT_BASE_MS = 1_000;
|
||||||
|
const RECONNECT_MAX_MS = 15_000;
|
||||||
|
const CLOSE_AUTH_INVALID = 4401;
|
||||||
|
|
||||||
|
// 开发环境 Next dev 的 rewrite 不透传 WebSocket Upgrade,直连后端 3001;
|
||||||
|
// Cookie 不按端口隔离,localhost:3000 的 j13_token 会随握手发到 :3001。
|
||||||
|
// 生产环境前后端同源(反向代理),走同源 /api/ws;可用 NEXT_PUBLIC_WS_URL 覆盖。
|
||||||
|
function wsEndpoint(): string {
|
||||||
|
const explicit = process.env.NEXT_PUBLIC_WS_URL;
|
||||||
|
if (explicit) return explicit;
|
||||||
|
if (typeof window === "undefined") return "";
|
||||||
|
const scheme = window.location.protocol === "https:" ? "wss://" : "ws://";
|
||||||
|
if (process.env.NODE_ENV !== "production") {
|
||||||
|
return `${scheme}${window.location.hostname}:3001/api/ws`;
|
||||||
|
}
|
||||||
|
return `${scheme}${window.location.host}/api/ws`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class RealtimeClient {
|
||||||
|
private ws: WebSocket | null = null;
|
||||||
|
private state: RtState = "idle";
|
||||||
|
// 是否应保持连接(登录态);登出或组件卸载时置 false 停止重连
|
||||||
|
private wanted = false;
|
||||||
|
private retryCount = 0;
|
||||||
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
private readonly handlers = new Map<string, Set<RtHandler>>();
|
||||||
|
private readonly presenceHandlers = new Set<RtHandler<RtPresenceData>>();
|
||||||
|
private onlineIds = new Set<number>();
|
||||||
|
// 已订阅的群聊房间(roomID 集合):重连后会自动重订,断连期间不丢订阅意图
|
||||||
|
private readonly joinedRooms = new Set<number>();
|
||||||
|
|
||||||
|
/** 建立连接(幂等);登录后调用 */
|
||||||
|
connect(): void {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
this.wanted = true;
|
||||||
|
if (this.state === "open" || this.state === "connecting") return;
|
||||||
|
this.clearReconnectTimer();
|
||||||
|
this.open();
|
||||||
|
window.addEventListener("online", this.handleNetworkBack);
|
||||||
|
document.addEventListener("visibilitychange", this.handleVisible);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 主动断开(登出/卸载);不再自动重连 */
|
||||||
|
disconnect(): void {
|
||||||
|
this.wanted = false;
|
||||||
|
window.removeEventListener("online", this.handleNetworkBack);
|
||||||
|
document.removeEventListener("visibilitychange", this.handleVisible);
|
||||||
|
this.clearReconnectTimer();
|
||||||
|
this.clearHeartbeat();
|
||||||
|
if (this.ws) {
|
||||||
|
this.ws.onclose = null;
|
||||||
|
this.ws.close(1000, "client logout");
|
||||||
|
this.ws = null;
|
||||||
|
}
|
||||||
|
this.state = "idle";
|
||||||
|
// 登出时清空房间订阅,避免下次同标签页重新登录后误订旧群
|
||||||
|
this.joinedRooms.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
isOpen(): boolean {
|
||||||
|
return this.state === "open";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 订阅指定事件,返回取消订阅函数 */
|
||||||
|
on<T>(type: string, handler: RtHandler<T>): () => void {
|
||||||
|
let set = this.handlers.get(type);
|
||||||
|
if (!set) {
|
||||||
|
set = new Set();
|
||||||
|
this.handlers.set(type, set);
|
||||||
|
}
|
||||||
|
set.add(handler as RtHandler);
|
||||||
|
return () => set!.delete(handler as RtHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 订阅在线状态增量(用户 0↔1 连接跳变);快照请在订阅时读 getOnlineIds */
|
||||||
|
onPresence(handler: RtHandler<RtPresenceData>): () => void {
|
||||||
|
this.presenceHandlers.add(handler);
|
||||||
|
return () => this.presenceHandlers.delete(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 当前在线用户 ID 快照 */
|
||||||
|
getOnlineIds(): ReadonlySet<number> {
|
||||||
|
return this.onlineIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 订阅群聊房间(进入群详情页调用)。幂等;连接已 open 时立即发 join 帧。
|
||||||
|
* 后端会按 chat:{id} 实时校验成员身份,被踢后再 join 也会被拒绝。 */
|
||||||
|
joinRoom(roomId: number): void {
|
||||||
|
if (!Number.isInteger(roomId) || roomId <= 0) return;
|
||||||
|
this.joinedRooms.add(roomId);
|
||||||
|
this.sendRoomFrame("join", roomId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 退订群聊房间(离开群详情页/退出群调用)。幂等。 */
|
||||||
|
leaveRoom(roomId: number): void {
|
||||||
|
if (!this.joinedRooms.delete(roomId)) return;
|
||||||
|
this.sendRoomFrame("leave", roomId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 退订全部群聊房间(切账号/被踢后清理) */
|
||||||
|
clearRooms(): void {
|
||||||
|
for (const id of this.joinedRooms) {
|
||||||
|
this.sendRoomFrame("leave", id);
|
||||||
|
}
|
||||||
|
this.joinedRooms.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendRoomFrame(type: "join" | "leave", roomId: number): void {
|
||||||
|
if (this.state !== "open" || !this.ws) return;
|
||||||
|
this.ws.send(JSON.stringify({ type, room: `chat:${roomId}` }));
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleNetworkBack = (): void => {
|
||||||
|
if (this.wanted && this.state === "closed") this.open();
|
||||||
|
};
|
||||||
|
|
||||||
|
private handleVisible = (): void => {
|
||||||
|
if (!this.wanted || document.visibilityState !== "visible") return;
|
||||||
|
// 后台标签页定时器可能被节流;重新可见时若连接已断则立即重连
|
||||||
|
if (this.state === "closed" || this.state === "idle") this.open();
|
||||||
|
};
|
||||||
|
|
||||||
|
private open(): void {
|
||||||
|
if (typeof WebSocket === "undefined") return;
|
||||||
|
this.state = "connecting";
|
||||||
|
let ws: WebSocket;
|
||||||
|
try {
|
||||||
|
ws = new WebSocket(wsEndpoint());
|
||||||
|
} catch {
|
||||||
|
this.scheduleReconnect();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.ws = ws;
|
||||||
|
ws.onopen = () => {
|
||||||
|
this.state = "open";
|
||||||
|
this.retryCount = 0;
|
||||||
|
this.clearHeartbeat();
|
||||||
|
this.heartbeatTimer = setInterval(() => {
|
||||||
|
this.send({ type: "ping" });
|
||||||
|
}, HEARTBEAT_MS);
|
||||||
|
// 重连后自动重订群聊房间(避免断线期间错过消息)
|
||||||
|
// 后端会按 chat:{id} 实时校验成员身份,已退出/被踢的群会被静默拒绝
|
||||||
|
for (const roomId of this.joinedRooms) {
|
||||||
|
this.sendRoomFrame("join", roomId);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
ws.onmessage = (ev) => this.handleMessage(ev.data);
|
||||||
|
ws.onerror = () => {
|
||||||
|
// close 事件会紧随其后,重连逻辑统一在 onclose 处理
|
||||||
|
};
|
||||||
|
ws.onclose = (ev) => {
|
||||||
|
this.clearHeartbeat();
|
||||||
|
if (this.ws === ws) this.ws = null;
|
||||||
|
this.state = "closed";
|
||||||
|
// 鉴权失效:账号封禁/角色变更导致 token_version 失效,
|
||||||
|
// 不重连(强制下线/重新登录由现有 HTTP 拦截链路处理)
|
||||||
|
if (!this.wanted || ev.code === CLOSE_AUTH_INVALID) {
|
||||||
|
this.wanted = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.scheduleReconnect();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleReconnect(): void {
|
||||||
|
if (!this.wanted || this.reconnectTimer) return;
|
||||||
|
const delay = Math.min(
|
||||||
|
RECONNECT_MAX_MS,
|
||||||
|
RECONNECT_BASE_MS * 2 ** this.retryCount
|
||||||
|
);
|
||||||
|
// ±20% 抖动,避免后端重启时所有客户端同时重连
|
||||||
|
const jitter = delay * 0.2 * (Math.random() * 2 - 1);
|
||||||
|
this.retryCount += 1;
|
||||||
|
this.reconnectTimer = setTimeout(() => {
|
||||||
|
this.reconnectTimer = null;
|
||||||
|
if (this.wanted) this.open();
|
||||||
|
}, Math.max(500, delay + jitter));
|
||||||
|
}
|
||||||
|
|
||||||
|
private clearReconnectTimer(): void {
|
||||||
|
if (this.reconnectTimer) {
|
||||||
|
clearTimeout(this.reconnectTimer);
|
||||||
|
this.reconnectTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private clearHeartbeat(): void {
|
||||||
|
if (this.heartbeatTimer) {
|
||||||
|
clearInterval(this.heartbeatTimer);
|
||||||
|
this.heartbeatTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private send(msg: RtEnvelope): void {
|
||||||
|
if (this.state === "open" && this.ws) {
|
||||||
|
this.ws.send(JSON.stringify(msg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleMessage(raw: unknown): void {
|
||||||
|
if (typeof raw !== "string") return;
|
||||||
|
let msg: RtEnvelope;
|
||||||
|
try {
|
||||||
|
msg = JSON.parse(raw) as RtEnvelope;
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!msg || typeof msg.type !== "string") return;
|
||||||
|
|
||||||
|
// 内部状态事件先维护在线集合
|
||||||
|
if (msg.type === RT_HELLO) {
|
||||||
|
const data = msg.data as RtHelloData | undefined;
|
||||||
|
const ids = data?.online_user_ids;
|
||||||
|
if (Array.isArray(ids)) {
|
||||||
|
this.onlineIds = new Set(ids.filter((n) => Number.isInteger(n)));
|
||||||
|
}
|
||||||
|
} else if (msg.type === RT_PRESENCE_UPDATE) {
|
||||||
|
const data = msg.data as RtPresenceData | undefined;
|
||||||
|
if (data && typeof data.user_id === "number") {
|
||||||
|
if (data.online) this.onlineIds.add(data.user_id);
|
||||||
|
else this.onlineIds.delete(data.user_id);
|
||||||
|
this.presenceHandlers.forEach((fn) => fn(data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const set = this.handlers.get(msg.type);
|
||||||
|
if (set) set.forEach((fn) => fn(msg.data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 全站单例(模块级,持久 root layout 下与标签页生命周期一致)
|
||||||
|
export const realtime = new RealtimeClient();
|
||||||
@@ -39,11 +39,16 @@ export function isSuperOrOwner(role?: string | null): boolean {
|
|||||||
return roleLevel(role) >= ROLE_LEVEL[ROLES.SUPER_ADMIN];
|
return roleLevel(role) >= ROLE_LEVEL[ROLES.SUPER_ADMIN];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 站长(唯一,不可被操作) */
|
/** 站长(站点所有者) */
|
||||||
export function isOwner(role?: string | null): boolean {
|
export function isOwner(role?: string | null): boolean {
|
||||||
return role === ROLES.OWNER;
|
return role === ROLES.OWNER;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 站长/超管:群聊监管旁路(可见全部群、撤回任意消息) */
|
||||||
|
export function canOverseeChat(role?: string | null): boolean {
|
||||||
|
return role === ROLES.OWNER || role === ROLES.SUPER_ADMIN;
|
||||||
|
}
|
||||||
|
|
||||||
/** 携带板块授权的最小用户形状(/me、帖子详情作者等均满足) */
|
/** 携带板块授权的最小用户形状(/me、帖子详情作者等均满足) */
|
||||||
export interface RoleUserLike {
|
export interface RoleUserLike {
|
||||||
role?: string | null;
|
role?: string | null;
|
||||||
|
|||||||
@@ -190,10 +190,15 @@ export function deriveAccentPair(input: string): AccentDerivation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 生成可直接注入的 CSS 文本(覆盖 globals.css 默认 accent 令牌);
|
// 生成可直接注入的 CSS 文本(覆盖 globals.css 默认 accent 令牌);
|
||||||
// 未配置或等于默认色时返回空串,完全使用内置样式
|
// 未配置或等于默认色时返回空串,完全使用内置样式(SSR 场景)
|
||||||
export function accentStyleCSS(input: string): string {
|
export function accentStyleCSS(input: string): string {
|
||||||
if (!input || input.toLowerCase() === DEFAULT_ACCENT) return "";
|
if (!input || input.toLowerCase() === DEFAULT_ACCENT) return "";
|
||||||
const { light, dark } = deriveAccentPair(input);
|
return buildAccentCSS(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 始终输出一套 accent 覆盖(含默认色),供客户端 runtime 盖住 SSR 自定义 style */
|
||||||
|
function buildAccentCSS(input: string): string {
|
||||||
|
const { light, dark } = deriveAccentPair(input || DEFAULT_ACCENT);
|
||||||
const hi = mix(light, "#000000", 0.1);
|
const hi = mix(light, "#000000", 0.1);
|
||||||
const darkHi = mix(dark, "#ffffff", 0.14);
|
const darkHi = mix(dark, "#ffffff", 0.14);
|
||||||
return [
|
return [
|
||||||
@@ -222,22 +227,44 @@ export function accentStyleCSS(input: string): string {
|
|||||||
// 客户端:实时换肤(后台预览 / 保存后即时生效)
|
// 客户端:实时换肤(后台预览 / 保存后即时生效)
|
||||||
// ---------------------------------------------------------------
|
// ---------------------------------------------------------------
|
||||||
|
|
||||||
const STYLE_ELEMENT_ID = "j13-accent-vars";
|
/** SSR 注入的 style(React 托管,客户端禁止 remove/改写) */
|
||||||
|
const SSR_STYLE_ID = "j13-accent-vars";
|
||||||
|
/** 客户端专用覆盖节点,挂在 body 末尾以压过 SSR */
|
||||||
|
const RUNTIME_STYLE_ID = "j13-accent-runtime";
|
||||||
|
|
||||||
// 将主题色应用到当前文档;传 null 移除覆盖、恢复内置默认
|
function ensureRuntimeStyle(): HTMLStyleElement {
|
||||||
|
let el = document.getElementById(RUNTIME_STYLE_ID) as HTMLStyleElement | null;
|
||||||
|
if (el) return el;
|
||||||
|
el = document.createElement("style");
|
||||||
|
el.id = RUNTIME_STYLE_ID;
|
||||||
|
el.setAttribute("data-accent-source", "runtime");
|
||||||
|
document.body.appendChild(el);
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeRuntimeStyle(): void {
|
||||||
|
const el = document.getElementById(RUNTIME_STYLE_ID);
|
||||||
|
// 只移除我们自己创建的节点,绝不碰 React 的 SSR <style>
|
||||||
|
el?.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将主题色应用到当前文档;传 null/默认色时恢复内置令牌(不拆 SSR 节点)
|
||||||
export function applyAccentTheme(input: string | null): void {
|
export function applyAccentTheme(input: string | null): void {
|
||||||
if (typeof document === "undefined") return;
|
if (typeof document === "undefined") return;
|
||||||
let el = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement | null;
|
const raw = (input || "").trim().toLowerCase();
|
||||||
const css = input === null ? "" : accentStyleCSS(input);
|
const isDefault = !raw || raw === DEFAULT_ACCENT.toLowerCase();
|
||||||
if (!css) {
|
|
||||||
el?.remove();
|
if (isDefault) {
|
||||||
|
const ssr = document.getElementById(SSR_STYLE_ID);
|
||||||
|
const ssrHasCustom = !!(ssr && ssr.textContent && ssr.textContent.trim());
|
||||||
|
if (ssrHasCustom) {
|
||||||
|
// SSR 仍挂着旧自定义色:用 runtime 写回默认覆盖,等 refresh 后再卸
|
||||||
|
ensureRuntimeStyle().textContent = buildAccentCSS(DEFAULT_ACCENT);
|
||||||
|
} else {
|
||||||
|
removeRuntimeStyle();
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!el) {
|
|
||||||
el = document.createElement("style");
|
ensureRuntimeStyle().textContent = buildAccentCSS(raw);
|
||||||
el.id = STYLE_ELEMENT_ID;
|
|
||||||
document.head.appendChild(el);
|
|
||||||
}
|
|
||||||
el.setAttribute("data-accent-source", "runtime");
|
|
||||||
el.textContent = css;
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user