feat: 实时消息与管理端运营能力
新增群聊/私信与公共 WebSocket 总线,站长用户内容档案,并将通知与待审角标改为推送驱动;同步精简管理仪表盘并修复主题换肤 DOM 冲突。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -3,6 +3,7 @@ package model
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
@@ -29,9 +30,15 @@ func InitDB(dsn string) error {
|
||||
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(
|
||||
&User{}, &Board{}, &Post{}, &Comment{}, &RefreshToken{}, &Like{}, &Notification{}, &Checkin{},
|
||||
&Announcement{}, &SiteSetting{}, &Attachment{}, &UserBoard{}, &LoginLog{},
|
||||
&ChatRoom{}, &ChatRoomMember{}, &ChatMessage{},
|
||||
); err != nil {
|
||||
return fmt.Errorf("自动迁移失败: %w", err)
|
||||
}
|
||||
@@ -54,7 +61,20 @@ func InitDB(dsn string) error {
|
||||
}
|
||||
|
||||
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)
|
||||
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 数据库初始化完成")
|
||||
return nil
|
||||
}
|
||||
@@ -71,6 +91,22 @@ func PingDB() error {
|
||||
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 列,
|
||||
// 新版改为 token_hash(SHA-256,NOT NULL+唯一索引)。在 AutoMigrate 之前:
|
||||
// 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 (
|
||||
NotificationTypeComment = "comment" // 评论了你的帖子
|
||||
NotificationTypeReply = "reply" // 回复了你的评论
|
||||
NotificationTypeLike = "like" // 点赞了你的帖子
|
||||
NotificationTypeApproved = "approved" // 内容审核通过
|
||||
NotificationTypeRejected = "rejected" // 内容审核未通过
|
||||
NotificationTypeComment = "comment" // 评论了你的帖子
|
||||
NotificationTypeReply = "reply" // 回复了你的评论
|
||||
NotificationTypeLike = "like" // 点赞了你的帖子
|
||||
NotificationTypeApproved = "approved" // 内容审核通过
|
||||
NotificationTypeRejected = "rejected" // 内容审核未通过
|
||||
NotificationTypeMention = "mention" // 群聊中 @ 了你(PostID=0,用 RoomID/MessageID)
|
||||
NotificationTypePendingReview = "pending_review" // 有新内容待审核(发给可审者)
|
||||
)
|
||||
|
||||
// Notification 站内通知
|
||||
type Notification struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UserID uint `gorm:"index;not null" json:"user_id"` // 接收通知的用户
|
||||
ActorID uint `gorm:"not null" json:"actor_id"` // 触发通知的用户
|
||||
Type string `gorm:"size:16;not null;index" json:"type"` // comment | like
|
||||
PostID uint `gorm:"index;not null" json:"post_id"` // 关联帖子
|
||||
CommentID uint `gorm:"index" json:"comment_id"` // 关联评论(点赞时为 0)
|
||||
Content string `gorm:"size:256" json:"content"` // 内容预览
|
||||
UserID uint `gorm:"index;not null" json:"user_id"` // 接收通知的用户
|
||||
ActorID uint `gorm:"not null" json:"actor_id"` // 触发通知的用户
|
||||
Type string `gorm:"size:16;not null;index" json:"type"` // comment | like | mention ...
|
||||
PostID uint `gorm:"index;not null;default:0" json:"post_id"` // 关联帖子(mention 类为 0)
|
||||
CommentID uint `gorm:"index" json:"comment_id"` // 关联评论(点赞时为 0)
|
||||
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"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
Actor User `gorm:"foreignKey:ActorID" json:"actor,omitempty"`
|
||||
Post Post `gorm:"foreignKey:PostID" json:"post,omitempty"`
|
||||
Actor User `gorm:"foreignKey:ActorID" json:"actor,omitempty"`
|
||||
Post Post `gorm:"foreignKey:PostID" json:"post,omitempty"`
|
||||
Room *ChatRoom `gorm:"foreignKey:RoomID;constraint:-" json:"room,omitempty"`
|
||||
}
|
||||
|
||||
// Announcement 站点公告(后台文章管理:支持草稿、标签与标签预设色)
|
||||
@@ -252,3 +257,66 @@ type LoginLog struct {
|
||||
Success bool `gorm:"index;not null;default:false" json:"success"`
|
||||
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"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user