SSE 推送替代轮训
This commit is contained in:
@@ -16,11 +16,19 @@ const (
|
|||||||
ContextUsername = "username"
|
ContextUsername = "username"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func extractToken(c *gin.Context) string {
|
||||||
|
header := c.GetHeader("Authorization")
|
||||||
|
tokenText := strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
||||||
|
if tokenText != "" && tokenText != header {
|
||||||
|
return tokenText
|
||||||
|
}
|
||||||
|
return c.Query("token")
|
||||||
|
}
|
||||||
|
|
||||||
func Auth(jwtManager *auth.JWTManager) gin.HandlerFunc {
|
func Auth(jwtManager *auth.JWTManager) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
header := c.GetHeader("Authorization")
|
tokenText := extractToken(c)
|
||||||
tokenText := strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
if tokenText == "" {
|
||||||
if tokenText == "" || tokenText == header {
|
|
||||||
response.Unauthorized(c, "缺少访问令牌")
|
response.Unauthorized(c, "缺少访问令牌")
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
@@ -41,9 +49,8 @@ func Auth(jwtManager *auth.JWTManager) gin.HandlerFunc {
|
|||||||
|
|
||||||
func AdminAuth(jwtManager *auth.JWTManager) gin.HandlerFunc {
|
func AdminAuth(jwtManager *auth.JWTManager) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
header := c.GetHeader("Authorization")
|
tokenText := extractToken(c)
|
||||||
tokenText := strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
if tokenText == "" {
|
||||||
if tokenText == "" || tokenText == header {
|
|
||||||
response.Unauthorized(c, "缺少后台访问令牌")
|
response.Unauthorized(c, "缺少后台访问令牌")
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/modules/chathub"
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
"gorm.io/datatypes"
|
"gorm.io/datatypes"
|
||||||
@@ -16,7 +17,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Repository struct {
|
type Repository struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
hub *chathub.Hub
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -25,8 +27,8 @@ const (
|
|||||||
defaultSupportNickname = "超级管理员"
|
defaultSupportNickname = "超级管理员"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewRepository(db *gorm.DB) *Repository {
|
func NewRepository(db *gorm.DB, hub *chathub.Hub) *Repository {
|
||||||
return &Repository{db: db}
|
return &Repository{db: db, hub: hub}
|
||||||
}
|
}
|
||||||
|
|
||||||
func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatConversation, error) {
|
func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatConversation, error) {
|
||||||
@@ -101,6 +103,17 @@ func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatC
|
|||||||
return &conversation, nil
|
return &conversation, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NotifyNewConversation 推送群聊创建事件给会话参与者。应在事务提交后调用。
|
||||||
|
func (r *Repository) NotifyNewConversation(conversationID uint64) {
|
||||||
|
if r.hub == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.hub.NotifyConversation(conversationID, &chathub.ChatEvent{
|
||||||
|
Type: "conversation_updated",
|
||||||
|
ConversationID: conversationID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Repository) ListConversations(principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
func (r *Repository) ListConversations(principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
||||||
page, pageSize = normalizePagination(page, pageSize)
|
page, pageSize = normalizePagination(page, pageSize)
|
||||||
var total int64
|
var total int64
|
||||||
@@ -241,6 +254,26 @@ func (r *Repository) SendMessage(principal Principal, conversationID uint64, req
|
|||||||
if len(items) == 0 {
|
if len(items) == 0 {
|
||||||
return nil, ErrConversationNotFound
|
return nil, ErrConversationNotFound
|
||||||
}
|
}
|
||||||
|
// 推送新消息事件给会话中的在线参与者
|
||||||
|
if r.hub != nil {
|
||||||
|
msg := items[0]
|
||||||
|
r.hub.NotifyConversation(conversationID, &chathub.ChatEvent{
|
||||||
|
Type: "new_message",
|
||||||
|
ConversationID: conversationID,
|
||||||
|
Message: &chathub.MessageData{
|
||||||
|
ID: msg.ID,
|
||||||
|
ConversationID: msg.ConversationID,
|
||||||
|
SenderType: msg.SenderType,
|
||||||
|
SenderID: msg.SenderID,
|
||||||
|
SenderRole: msg.SenderRole,
|
||||||
|
SenderName: msg.SenderName,
|
||||||
|
ContentType: msg.ContentType,
|
||||||
|
Content: msg.Content,
|
||||||
|
AttachmentURLS: msg.AttachmentURLS,
|
||||||
|
CreatedAt: msg.CreatedAt.Format(time.RFC3339),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
return &items[0], nil
|
return &items[0], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package chathub
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/middleware"
|
||||||
|
"hfb_sys/backend/pkg/response"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
const heartbeatInterval = 30 * time.Second
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
hub *Hub
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(hub *Hub) *Handler {
|
||||||
|
return &Handler{hub: hub}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserEvents 处理用户端 SSE 连接: GET /api/chats/events
|
||||||
|
func (h *Handler) UserEvents(c *gin.Context) {
|
||||||
|
value, ok := c.Get(middleware.ContextUserID)
|
||||||
|
if !ok {
|
||||||
|
response.Unauthorized(c, "缺少用户上下文")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userID, ok := value.(uint64)
|
||||||
|
if !ok {
|
||||||
|
response.Unauthorized(c, "用户上下文无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.serveSSE(c, "user", userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminEvents 处理管理端 SSE 连接: GET /api/admin/chats/events
|
||||||
|
func (h *Handler) AdminEvents(c *gin.Context) {
|
||||||
|
value, ok := c.Get(middleware.ContextAdminID)
|
||||||
|
if !ok {
|
||||||
|
response.Unauthorized(c, "缺少管理员上下文")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
adminID, ok := value.(uint64)
|
||||||
|
if !ok {
|
||||||
|
response.Unauthorized(c, "管理员上下文无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.serveSSE(c, "admin", adminID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) serveSSE(c *gin.Context, pType string, pID uint64) {
|
||||||
|
ch := h.hub.Subscribe(pType, pID)
|
||||||
|
defer h.hub.Unsubscribe(pType, pID, ch)
|
||||||
|
|
||||||
|
c.Header("Content-Type", "text/event-stream")
|
||||||
|
c.Header("Cache-Control", "no-cache")
|
||||||
|
c.Header("Connection", "keep-alive")
|
||||||
|
c.Header("X-Accel-Buffering", "no")
|
||||||
|
|
||||||
|
// 发送初始连接确认
|
||||||
|
fmt.Fprintf(c.Writer, "event: connected\ndata: {\"ok\":true}\n\n")
|
||||||
|
c.Writer.Flush()
|
||||||
|
|
||||||
|
heartbeat := time.NewTicker(heartbeatInterval)
|
||||||
|
defer heartbeat.Stop()
|
||||||
|
|
||||||
|
clientGone := c.Request.Context().Done()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-clientGone:
|
||||||
|
return
|
||||||
|
case <-heartbeat.C:
|
||||||
|
fmt.Fprintf(c.Writer, ":heartbeat\n\n")
|
||||||
|
c.Writer.Flush()
|
||||||
|
case event, ok := <-ch:
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data := MarshalEvent(event)
|
||||||
|
fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", event.Type, data)
|
||||||
|
c.Writer.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
package chathub
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatEvent 是通过 SSE 推送给客户端的事件。
|
||||||
|
type ChatEvent struct {
|
||||||
|
Type string `json:"type"` // "new_message" | "conversation_updated"
|
||||||
|
ConversationID uint64 `json:"conversation_id"`
|
||||||
|
Message *MessageData `json:"message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MessageData 是事件中携带的消息数据,与 chat.MessageDTO 对齐。
|
||||||
|
type MessageData struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
ConversationID uint64 `json:"conversation_id"`
|
||||||
|
SenderType string `json:"sender_type"`
|
||||||
|
SenderID uint64 `json:"sender_id"`
|
||||||
|
SenderRole string `json:"sender_role"`
|
||||||
|
SenderName string `json:"sender_name"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
AttachmentURLS []string `json:"attachment_urls"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// principal 标识一个连接方。
|
||||||
|
type principal struct {
|
||||||
|
Type string // "user" or "admin"
|
||||||
|
ID uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hub 管理所有 SSE 连接。
|
||||||
|
type Hub struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
clients map[principal]map[chan *ChatEvent]struct{}
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHub 创建 Hub 实例。
|
||||||
|
func NewHub(db *gorm.DB) *Hub {
|
||||||
|
return &Hub{
|
||||||
|
clients: make(map[principal]map[chan *ChatEvent]struct{}),
|
||||||
|
db: db,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subscribe 注册一个 SSE 连接,返回事件 channel。
|
||||||
|
func (h *Hub) Subscribe(pType string, pID uint64) <-chan *ChatEvent {
|
||||||
|
ch := make(chan *ChatEvent, 16)
|
||||||
|
key := principal{Type: pType, ID: pID}
|
||||||
|
h.mu.Lock()
|
||||||
|
if h.clients[key] == nil {
|
||||||
|
h.clients[key] = make(map[chan *ChatEvent]struct{})
|
||||||
|
}
|
||||||
|
h.clients[key][ch] = struct{}{}
|
||||||
|
h.mu.Unlock()
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unsubscribe 注销 SSE 连接。
|
||||||
|
func (h *Hub) Unsubscribe(pType string, pID uint64, ch <-chan *ChatEvent) {
|
||||||
|
key := principal{Type: pType, ID: pID}
|
||||||
|
h.mu.Lock()
|
||||||
|
if clients, ok := h.clients[key]; ok {
|
||||||
|
// 找到对应的发送 channel 并删除
|
||||||
|
for sendCh := range clients {
|
||||||
|
if sendCh == ch {
|
||||||
|
delete(clients, sendCh)
|
||||||
|
close(sendCh)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(clients) == 0 {
|
||||||
|
delete(h.clients, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// NotifyConversation 查询会话参与者,向所有在线参与者推送事件。
|
||||||
|
func (h *Hub) NotifyConversation(conversationID uint64, event *ChatEvent) {
|
||||||
|
if h.db == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 查询会话参与者
|
||||||
|
type participantRow struct {
|
||||||
|
ParticipantType string
|
||||||
|
ParticipantID uint64
|
||||||
|
}
|
||||||
|
var rows []participantRow
|
||||||
|
h.db.Table("chat_participants").
|
||||||
|
Select("participant_type, participant_id").
|
||||||
|
Where("conversation_id = ?", conversationID).
|
||||||
|
Find(&rows)
|
||||||
|
|
||||||
|
h.mu.RLock()
|
||||||
|
defer h.mu.RUnlock()
|
||||||
|
|
||||||
|
seen := make(map[principal]struct{})
|
||||||
|
for _, row := range rows {
|
||||||
|
key := principal{Type: row.ParticipantType, ID: row.ParticipantID}
|
||||||
|
if _, ok := seen[key]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[key] = struct{}{}
|
||||||
|
if clients, ok := h.clients[key]; ok {
|
||||||
|
for ch := range clients {
|
||||||
|
select {
|
||||||
|
case ch <- event:
|
||||||
|
default:
|
||||||
|
// channel 满了,丢弃事件避免阻塞
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NotifyUser 直接向指定用户/Admin 推送事件。
|
||||||
|
func (h *Hub) NotifyUser(pType string, pID uint64, event *ChatEvent) {
|
||||||
|
key := principal{Type: pType, ID: pID}
|
||||||
|
h.mu.RLock()
|
||||||
|
defer h.mu.RUnlock()
|
||||||
|
if clients, ok := h.clients[key]; ok {
|
||||||
|
for ch := range clients {
|
||||||
|
select {
|
||||||
|
case ch <- event:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalEvent 将事件序列化为 SSE data 行。
|
||||||
|
func MarshalEvent(event *ChatEvent) string {
|
||||||
|
raw, _ := json.Marshal(event)
|
||||||
|
return string(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
// OnlineCount 返回当前在线连接数。
|
||||||
|
func (h *Hub) OnlineCount() int {
|
||||||
|
h.mu.RLock()
|
||||||
|
defer h.mu.RUnlock()
|
||||||
|
count := 0
|
||||||
|
for _, clients := range h.clients {
|
||||||
|
count += len(clients)
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
@@ -20,7 +20,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Repository struct {
|
type Repository struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
chatRepo *chat.Repository
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultPendingPaymentTimeoutMinutes = 15
|
const defaultPendingPaymentTimeoutMinutes = 15
|
||||||
@@ -29,6 +30,10 @@ func NewRepository(db *gorm.DB) *Repository {
|
|||||||
return &Repository{db: db}
|
return &Repository{db: db}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *Repository) SetChatRepo(cr *chat.Repository) {
|
||||||
|
r.chatRepo = cr
|
||||||
|
}
|
||||||
|
|
||||||
type orderPricing struct {
|
type orderPricing struct {
|
||||||
RentAmount float64
|
RentAmount float64
|
||||||
OwnerRentAmount float64
|
OwnerRentAmount float64
|
||||||
@@ -178,7 +183,8 @@ func (r *Repository) Create(renterID uint64, req CreateRequest) (*OrderDTO, erro
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) Pay(userID uint64, orderID uint64) error {
|
func (r *Repository) Pay(userID uint64, orderID uint64) error {
|
||||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
var newConvID uint64
|
||||||
|
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
var order model.RentalOrder
|
var order model.RentalOrder
|
||||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
Where("id = ? AND renter_id = ?", orderID, userID).
|
Where("id = ? AND renter_id = ?", orderID, userID).
|
||||||
@@ -238,9 +244,11 @@ func (r *Repository) Pay(userID uint64, orderID uint64) error {
|
|||||||
order.HandoffStatus = "pending_owner"
|
order.HandoffStatus = "pending_owner"
|
||||||
listing.Status = "rented"
|
listing.Status = "rented"
|
||||||
account.Status = "rented"
|
account.Status = "rented"
|
||||||
if _, err := chat.EnsureOrderConversation(tx, order); err != nil {
|
conv, err := chat.EnsureOrderConversation(tx, order)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
newConvID = conv.ID
|
||||||
orderID := order.ID
|
orderID := order.ID
|
||||||
if err := notification.Append(tx,
|
if err := notification.Append(tx,
|
||||||
notification.Entry{
|
notification.Entry{
|
||||||
@@ -270,6 +278,14 @@ func (r *Repository) Pay(userID uint64, orderID uint64) error {
|
|||||||
}
|
}
|
||||||
return tx.Save(&account).Error
|
return tx.Save(&account).Error
|
||||||
})
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// 事务成功后推送群聊创建事件
|
||||||
|
if newConvID > 0 && r.chatRepo != nil {
|
||||||
|
r.chatRepo.NotifyNewConversation(newConvID)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) Cancel(userID uint64, orderID uint64) error {
|
func (r *Repository) Cancel(userID uint64, orderID uint64) error {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"hfb_sys/backend/internal/modules/adminuser"
|
"hfb_sys/backend/internal/modules/adminuser"
|
||||||
"hfb_sys/backend/internal/modules/auth"
|
"hfb_sys/backend/internal/modules/auth"
|
||||||
"hfb_sys/backend/internal/modules/chat"
|
"hfb_sys/backend/internal/modules/chat"
|
||||||
|
"hfb_sys/backend/internal/modules/chathub"
|
||||||
"hfb_sys/backend/internal/modules/dispute"
|
"hfb_sys/backend/internal/modules/dispute"
|
||||||
filemodule "hfb_sys/backend/internal/modules/file"
|
filemodule "hfb_sys/backend/internal/modules/file"
|
||||||
"hfb_sys/backend/internal/modules/listing"
|
"hfb_sys/backend/internal/modules/listing"
|
||||||
@@ -98,12 +99,23 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
|||||||
}
|
}
|
||||||
notificationService := notification.NewService(notificationRepo)
|
notificationService := notification.NewService(notificationRepo)
|
||||||
notificationHandler := notification.NewHandler(notificationService)
|
notificationHandler := notification.NewHandler(notificationService)
|
||||||
|
var chatHub *chathub.Hub
|
||||||
|
if deps.DB != nil {
|
||||||
|
chatHub = chathub.NewHub(deps.DB)
|
||||||
|
}
|
||||||
var chatRepo *chat.Repository
|
var chatRepo *chat.Repository
|
||||||
if deps.DB != nil {
|
if deps.DB != nil {
|
||||||
chatRepo = chat.NewRepository(deps.DB)
|
chatRepo = chat.NewRepository(deps.DB, chatHub)
|
||||||
}
|
}
|
||||||
chatService := chat.NewService(chatRepo)
|
chatService := chat.NewService(chatRepo)
|
||||||
chatHandler := chat.NewHandler(chatService)
|
chatHandler := chat.NewHandler(chatService)
|
||||||
|
var chatHubHandler *chathub.Handler
|
||||||
|
if chatHub != nil {
|
||||||
|
chatHubHandler = chathub.NewHandler(chatHub)
|
||||||
|
}
|
||||||
|
if orderRepo != nil && chatRepo != nil {
|
||||||
|
orderRepo.SetChatRepo(chatRepo)
|
||||||
|
}
|
||||||
var disputeRepo *dispute.Repository
|
var disputeRepo *dispute.Repository
|
||||||
if deps.DB != nil {
|
if deps.DB != nil {
|
||||||
disputeRepo = dispute.NewRepository(deps.DB)
|
disputeRepo = dispute.NewRepository(deps.DB)
|
||||||
@@ -232,6 +244,9 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
|||||||
|
|
||||||
chatRoutes := api.Group("/chats", requireAuth)
|
chatRoutes := api.Group("/chats", requireAuth)
|
||||||
{
|
{
|
||||||
|
if chatHubHandler != nil {
|
||||||
|
chatRoutes.GET("/events", chatHubHandler.UserEvents)
|
||||||
|
}
|
||||||
chatRoutes.GET("", chatHandler.List)
|
chatRoutes.GET("", chatHandler.List)
|
||||||
chatRoutes.GET("/:id", chatHandler.Detail)
|
chatRoutes.GET("/:id", chatHandler.Detail)
|
||||||
chatRoutes.GET("/:id/messages", chatHandler.Messages)
|
chatRoutes.GET("/:id/messages", chatHandler.Messages)
|
||||||
@@ -280,6 +295,9 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
|||||||
adminRoutes.GET("/system-configs", requirePerm("system_config:view"), systemConfigHandler.List)
|
adminRoutes.GET("/system-configs", requirePerm("system_config:view"), systemConfigHandler.List)
|
||||||
adminRoutes.PUT("/system-configs/:key", requirePerm("system_config:update"), systemConfigHandler.Update)
|
adminRoutes.PUT("/system-configs/:key", requirePerm("system_config:update"), systemConfigHandler.Update)
|
||||||
adminRoutes.GET("/audit-logs", requirePerm("audit_log:view"), adminAuditHandler.List)
|
adminRoutes.GET("/audit-logs", requirePerm("audit_log:view"), adminAuditHandler.List)
|
||||||
|
if chatHubHandler != nil {
|
||||||
|
adminRoutes.GET("/chats/events", requirePerm("chat:view"), chatHubHandler.AdminEvents)
|
||||||
|
}
|
||||||
adminRoutes.GET("/chats", requirePerm("chat:view"), chatHandler.AdminList)
|
adminRoutes.GET("/chats", requirePerm("chat:view"), chatHandler.AdminList)
|
||||||
adminRoutes.GET("/chats/:id", requirePerm("chat:view"), chatHandler.AdminDetail)
|
adminRoutes.GET("/chats/:id", requirePerm("chat:view"), chatHandler.AdminDetail)
|
||||||
adminRoutes.GET("/chats/:id/messages", requirePerm("chat:view"), chatHandler.AdminMessages)
|
adminRoutes.GET("/chats/:id/messages", requirePerm("chat:view"), chatHandler.AdminMessages)
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { onBeforeUnmount, ref, type Ref } from 'vue'
|
||||||
|
import { getAccessToken, type AuthScope } from '@/utils/authStorage'
|
||||||
|
|
||||||
|
export interface SSEMessage {
|
||||||
|
id: number
|
||||||
|
conversation_id: number
|
||||||
|
sender_type: string
|
||||||
|
sender_id: number
|
||||||
|
sender_role: string
|
||||||
|
sender_name: string
|
||||||
|
content_type: string
|
||||||
|
content: string
|
||||||
|
attachment_urls: string[]
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatEvent {
|
||||||
|
type: 'new_message' | 'conversation_updated'
|
||||||
|
conversation_id: number
|
||||||
|
message?: SSEMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
type EventHandler = (event: ChatEvent) => void
|
||||||
|
|
||||||
|
const reconnectDelay = 3000
|
||||||
|
|
||||||
|
export function useChatSSE(scope: AuthScope, endpoint: string) {
|
||||||
|
const connected: Ref<boolean> = ref(false)
|
||||||
|
let source: EventSource | null = null
|
||||||
|
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
let stopped = false
|
||||||
|
const handlers: EventHandler[] = []
|
||||||
|
|
||||||
|
function onEvent(handler: EventHandler) {
|
||||||
|
handlers.push(handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
const token = getAccessToken(scope)
|
||||||
|
if (!token) return
|
||||||
|
|
||||||
|
const url = `${endpoint}?token=${encodeURIComponent(token)}`
|
||||||
|
source = new EventSource(url)
|
||||||
|
|
||||||
|
source.addEventListener('connected', () => {
|
||||||
|
connected.value = true
|
||||||
|
})
|
||||||
|
|
||||||
|
source.addEventListener('new_message', (e) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse((e as MessageEvent).data) as ChatEvent
|
||||||
|
handlers.forEach(h => h(data))
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
})
|
||||||
|
|
||||||
|
source.addEventListener('conversation_updated', (e) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse((e as MessageEvent).data) as ChatEvent
|
||||||
|
handlers.forEach(h => h(data))
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
})
|
||||||
|
|
||||||
|
source.onerror = () => {
|
||||||
|
connected.value = false
|
||||||
|
source?.close()
|
||||||
|
source = null
|
||||||
|
if (!stopped) {
|
||||||
|
reconnectTimer = setTimeout(connect, reconnectDelay)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function disconnect() {
|
||||||
|
stopped = true
|
||||||
|
if (reconnectTimer) {
|
||||||
|
clearTimeout(reconnectTimer)
|
||||||
|
reconnectTimer = null
|
||||||
|
}
|
||||||
|
source?.close()
|
||||||
|
source = null
|
||||||
|
connected.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
disconnect()
|
||||||
|
})
|
||||||
|
|
||||||
|
connect()
|
||||||
|
|
||||||
|
return { connected, onEvent, disconnect }
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
import {
|
import {
|
||||||
fetchAdminChat,
|
fetchAdminChat,
|
||||||
@@ -10,8 +10,11 @@ import {
|
|||||||
type ChatConversation,
|
type ChatConversation,
|
||||||
type ChatMessage,
|
type ChatMessage,
|
||||||
} from '@/api/chats'
|
} from '@/api/chats'
|
||||||
|
import { useChatSSE, type ChatEvent } from '@/composables/useChatSSE'
|
||||||
import { formatDateMinute } from '@/utils/time'
|
import { formatDateMinute } from '@/utils/time'
|
||||||
|
|
||||||
|
const currentAdminId = Number(localStorage.getItem('admin_id') || 0)
|
||||||
|
|
||||||
const conversations = ref<ChatConversation[]>([])
|
const conversations = ref<ChatConversation[]>([])
|
||||||
const active = ref<ChatConversation | null>(null)
|
const active = ref<ChatConversation | null>(null)
|
||||||
const messages = ref<ChatMessage[]>([])
|
const messages = ref<ChatMessage[]>([])
|
||||||
@@ -20,23 +23,43 @@ const messageLoading = ref(false)
|
|||||||
const sending = ref(false)
|
const sending = ref(false)
|
||||||
const content = ref('')
|
const content = ref('')
|
||||||
const listRef = ref<HTMLElement | null>(null)
|
const listRef = ref<HTMLElement | null>(null)
|
||||||
let timer: number | undefined
|
|
||||||
|
|
||||||
const activeMembers = computed(() => {
|
const activeMembers = computed(() => {
|
||||||
const participants = active.value?.participants || []
|
const participants = active.value?.participants || []
|
||||||
return participants.map(item => `${roleLabel(item.role)}:${item.display_name}`).join(' / ')
|
return participants.map(item => `${roleLabel(item.role)}:${item.display_name}`).join(' / ')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function handleSSEEvent(event: ChatEvent) {
|
||||||
|
if (event.type === 'conversation_updated') {
|
||||||
|
loadConversations(false)
|
||||||
|
}
|
||||||
|
if (event.type === 'new_message' && active.value && event.conversation_id === active.value.id) {
|
||||||
|
const msg = event.message
|
||||||
|
if (msg && !messages.value.some(m => m.id === msg.id)) {
|
||||||
|
messages.value = [...messages.value, {
|
||||||
|
id: msg.id,
|
||||||
|
conversation_id: msg.conversation_id,
|
||||||
|
sender_type: msg.sender_type as ChatMessage['sender_type'],
|
||||||
|
sender_id: msg.sender_id,
|
||||||
|
sender_role: msg.sender_role as ChatMessage['sender_role'],
|
||||||
|
sender_name: msg.sender_name,
|
||||||
|
sender_avatar: '',
|
||||||
|
is_self: msg.sender_type === 'admin' && msg.sender_id === currentAdminId,
|
||||||
|
content_type: msg.content_type as ChatMessage['content_type'],
|
||||||
|
content: msg.content,
|
||||||
|
attachment_urls: msg.attachment_urls || [],
|
||||||
|
created_at: msg.created_at,
|
||||||
|
}]
|
||||||
|
nextTick(() => scrollBottom())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { onEvent } = useChatSSE('admin', '/api/admin/chats/events')
|
||||||
|
onEvent(handleSSEEvent)
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await loadConversations()
|
await loadConversations()
|
||||||
timer = window.setInterval(async () => {
|
|
||||||
await loadConversations(false)
|
|
||||||
if (active.value) await loadMessages(active.value.id, false)
|
|
||||||
}, 5000)
|
|
||||||
})
|
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
|
||||||
if (timer) window.clearInterval(timer)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
async function loadConversations(showLoading = true) {
|
async function loadConversations(showLoading = true) {
|
||||||
@@ -83,12 +106,8 @@ async function handleSend() {
|
|||||||
if (!active.value || !text || sending.value) return
|
if (!active.value || !text || sending.value) return
|
||||||
sending.value = true
|
sending.value = true
|
||||||
try {
|
try {
|
||||||
const message = await sendAdminChatMessage(active.value.id, text)
|
await sendAdminChatMessage(active.value.id, text)
|
||||||
messages.value = [...messages.value, message]
|
|
||||||
content.value = ''
|
content.value = ''
|
||||||
await nextTick()
|
|
||||||
scrollBottom()
|
|
||||||
await loadConversations(false)
|
|
||||||
} catch {
|
} catch {
|
||||||
ElMessage.error('发送失败')
|
ElMessage.error('发送失败')
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { showToast } from 'vant'
|
import { showToast } from 'vant'
|
||||||
import {
|
import {
|
||||||
@@ -10,8 +10,11 @@ import {
|
|||||||
type ChatConversation,
|
type ChatConversation,
|
||||||
type ChatMessage,
|
type ChatMessage,
|
||||||
} from '@/api/chats'
|
} from '@/api/chats'
|
||||||
|
import { useChatSSE, type ChatEvent } from '@/composables/useChatSSE'
|
||||||
import { formatDateMinute } from '@/utils/time'
|
import { formatDateMinute } from '@/utils/time'
|
||||||
|
|
||||||
|
const currentUserId = Number(localStorage.getItem('user_id') || 0)
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const conversation = ref<ChatConversation | null>(null)
|
const conversation = ref<ChatConversation | null>(null)
|
||||||
@@ -20,7 +23,6 @@ const loading = ref(false)
|
|||||||
const sending = ref(false)
|
const sending = ref(false)
|
||||||
const content = ref('')
|
const content = ref('')
|
||||||
const listRef = ref<HTMLElement | null>(null)
|
const listRef = ref<HTMLElement | null>(null)
|
||||||
let timer: number | undefined
|
|
||||||
|
|
||||||
const conversationID = computed(() => Number(route.params.id || 0))
|
const conversationID = computed(() => Number(route.params.id || 0))
|
||||||
const memberText = computed(() => {
|
const memberText = computed(() => {
|
||||||
@@ -29,15 +31,37 @@ const memberText = computed(() => {
|
|||||||
return participants.map(item => roleLabel(item.role)).join(' · ')
|
return participants.map(item => roleLabel(item.role)).join(' · ')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function handleSSEEvent(event: ChatEvent) {
|
||||||
|
if (event.type === 'new_message' && event.conversation_id === conversationID.value) {
|
||||||
|
const msg = event.message
|
||||||
|
if (msg && !messages.value.some(m => m.id === msg.id)) {
|
||||||
|
messages.value = [...messages.value, {
|
||||||
|
id: msg.id,
|
||||||
|
conversation_id: msg.conversation_id,
|
||||||
|
sender_type: msg.sender_type as ChatMessage['sender_type'],
|
||||||
|
sender_id: msg.sender_id,
|
||||||
|
sender_role: msg.sender_role as ChatMessage['sender_role'],
|
||||||
|
sender_name: msg.sender_name,
|
||||||
|
sender_avatar: '',
|
||||||
|
is_self: msg.sender_type === 'user' && msg.sender_id === currentUserId,
|
||||||
|
content_type: msg.content_type as ChatMessage['content_type'],
|
||||||
|
content: msg.content,
|
||||||
|
attachment_urls: msg.attachment_urls || [],
|
||||||
|
created_at: msg.created_at,
|
||||||
|
}]
|
||||||
|
nextTick(() => scrollBottom())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (event.type === 'conversation_updated' && event.conversation_id === conversationID.value) {
|
||||||
|
loadConversation()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { onEvent } = useChatSSE('user', '/api/chats/events')
|
||||||
|
onEvent(handleSSEEvent)
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await loadAll()
|
await loadAll()
|
||||||
timer = window.setInterval(() => {
|
|
||||||
loadMessages(false)
|
|
||||||
}, 5000)
|
|
||||||
})
|
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
|
||||||
if (timer) window.clearInterval(timer)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
async function loadAll() {
|
async function loadAll() {
|
||||||
@@ -57,6 +81,13 @@ async function loadAll() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadConversation() {
|
||||||
|
if (!conversationID.value) return
|
||||||
|
try {
|
||||||
|
conversation.value = await fetchChat(conversationID.value)
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
async function loadMessages(scrollToBottom = true) {
|
async function loadMessages(scrollToBottom = true) {
|
||||||
if (!conversationID.value) return
|
if (!conversationID.value) return
|
||||||
const res = await fetchChatMessages(conversationID.value, 1, 100)
|
const res = await fetchChatMessages(conversationID.value, 1, 100)
|
||||||
@@ -72,12 +103,8 @@ async function handleSend() {
|
|||||||
if (!text || sending.value) return
|
if (!text || sending.value) return
|
||||||
sending.value = true
|
sending.value = true
|
||||||
try {
|
try {
|
||||||
const message = await sendChatMessage(conversationID.value, text)
|
await sendChatMessage(conversationID.value, text)
|
||||||
content.value = ''
|
content.value = ''
|
||||||
messages.value = [...messages.value, message]
|
|
||||||
await markChatRead(conversationID.value)
|
|
||||||
await nextTick()
|
|
||||||
scrollBottom()
|
|
||||||
} catch {
|
} catch {
|
||||||
showToast({ message: '发送失败', icon: 'cross' })
|
showToast({ message: '发送失败', icon: 'cross' })
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
Reference in New Issue
Block a user