spark-server/internal/transport/http/handler/message/handler.go
2026-09-18 14:50:41 +08:00

113 lines
2.4 KiB
Go

package msghandler
import (
"strconv"
"github.com/gin-gonic/gin"
msglogic "spark-server/internal/module/message/logic"
"spark-server/internal/pkg/errs"
"spark-server/internal/pkg/reqctx"
"spark-server/internal/transport/http/respond"
)
// Handler is the messages HTTP controller.
type Handler struct {
msgs *msglogic.Service
}
func New(msgs *msglogic.Service) *Handler {
return &Handler{msgs: msgs}
}
func (h *Handler) Send(c *gin.Context) {
uid, did, ok := currentUser(c)
if !ok {
return
}
var in msglogic.SendInput
if err := respond.BindJSON(c, &in); err != nil {
respond.JSONError(c, err)
return
}
out, err := h.msgs.SendMessage(c.Request.Context(), uid, did, &in)
if err != nil {
respond.JSONError(c, err)
return
}
respond.JSON(c, out)
}
func (h *Handler) History(c *gin.Context) {
uid, _, ok := currentUser(c)
if !ok {
return
}
convID, err := strconv.ParseInt(c.Query("conversation_id"), 10, 64)
if err != nil || convID <= 0 {
respond.JSONError(c, errs.ErrInvalidArgument)
return
}
lastID, _ := strconv.ParseInt(c.Query("last_msg_id"), 10, 64)
limit, _ := strconv.Atoi(c.Query("limit"))
out, err := h.msgs.GetHistory(c.Request.Context(), uid, msglogic.HistoryRequest{
ConversationID: convID, LastMsgID: lastID, Limit: limit,
})
if err != nil {
respond.JSONError(c, err)
return
}
respond.JSON(c, out)
}
func (h *Handler) Recall(c *gin.Context) {
uid, did, ok := currentUser(c)
if !ok {
return
}
id, err := pathMsgID(c)
if err != nil {
respond.JSONError(c, err)
return
}
if err := h.msgs.RecallMessage(c.Request.Context(), uid, did, id); err != nil {
respond.JSONError(c, err)
return
}
respond.JSON(c, gin.H{})
}
func (h *Handler) Delete(c *gin.Context) {
uid, did, ok := currentUser(c)
if !ok {
return
}
id, err := pathMsgID(c)
if err != nil {
respond.JSONError(c, err)
return
}
if err := h.msgs.DeleteMessage(c.Request.Context(), uid, did, id); err != nil {
respond.JSONError(c, err)
return
}
respond.JSON(c, gin.H{})
}
func pathMsgID(c *gin.Context) (int64, error) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || id <= 0 {
return 0, errs.ErrInvalidArgument
}
return id, nil
}
func currentUser(c *gin.Context) (int64, uint64, bool) {
rc := reqctx.From(c.Request.Context())
if rc == nil || rc.UserID <= 0 {
respond.JSONError(c, errs.ErrUnauthorized)
return 0, 0, false
}
return rc.UserID, rc.DeviceID, true
}