forked from mtusi2026/mtusi2026lab4
231 lines
5.7 KiB
Go
231 lines
5.7 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"mtusi2026lab2/internal/middleware"
|
|
"mtusi2026lab2/internal/model"
|
|
"mtusi2026lab2/internal/storage"
|
|
)
|
|
|
|
type MessageHandler struct {
|
|
chats *storage.ChatStore
|
|
messages *storage.MessageStore
|
|
}
|
|
|
|
func NewMessageHandler(
|
|
chats *storage.ChatStore,
|
|
messages *storage.MessageStore,
|
|
) *MessageHandler {
|
|
return &MessageHandler{
|
|
chats: chats,
|
|
messages: messages,
|
|
}
|
|
}
|
|
|
|
type createMessageRequest struct {
|
|
Text string `json:"text"`
|
|
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
|
|
}
|
|
|
|
type messagePage struct {
|
|
Items []model.Message `json:"items"`
|
|
NextCursor *string `json:"next_cursor"`
|
|
}
|
|
|
|
func (h *MessageHandler) accessibleChat(
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
) (uuid.UUID, bool) {
|
|
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
|
if !ok {
|
|
writeError(w, r, http.StatusUnauthorized,
|
|
"unauthorized", "authentication required")
|
|
return uuid.Nil, false
|
|
}
|
|
|
|
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
|
if err != nil {
|
|
writeError(w, r, http.StatusBadRequest,
|
|
"invalid_request", "invalid chat id")
|
|
return uuid.Nil, false
|
|
}
|
|
|
|
_, err = h.chats.GetChatForUser(
|
|
r.Context(), chatID, currentUser.ID,
|
|
)
|
|
if errors.Is(err, storage.ErrChatNotFound) {
|
|
writeError(w, r, http.StatusNotFound,
|
|
"not_found", "chat not found")
|
|
return uuid.Nil, false
|
|
}
|
|
if err != nil {
|
|
writeError(w, r, http.StatusServiceUnavailable,
|
|
"unavailable", "service unavailable")
|
|
return uuid.Nil, false
|
|
}
|
|
|
|
return chatID, true
|
|
}
|
|
|
|
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
|
|
|
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
|
key := r.Header.Get("Idempotency-Key")
|
|
if !idempotencyKeyPattern.MatchString(key) {
|
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid or missing Idempotency-Key")
|
|
return
|
|
}
|
|
|
|
chatID, ok := h.accessibleChat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
currentUser, _ := middleware.GetCurrentUser(r.Context())
|
|
|
|
var req createMessageRequest
|
|
if err := decodeOneObject(r, &req); err != nil {
|
|
writeError(w, r, http.StatusBadRequest,
|
|
"invalid_request", "invalid request body")
|
|
return
|
|
}
|
|
|
|
textLength := utf8.RuneCountInString(req.Text)
|
|
if (strings.TrimSpace(req.Text) == "" && len(req.AttachmentIDs) == 0) || textLength > 4000 || len(req.AttachmentIDs) > 10 {
|
|
writeError(w, r, http.StatusBadRequest,
|
|
"invalid_request", "text must contain from 1 to 4000 characters")
|
|
return
|
|
}
|
|
|
|
seen := make(map[uuid.UUID]bool)
|
|
for _, id := range req.AttachmentIDs {
|
|
if id == uuid.Nil || seen[id] {
|
|
writeError(w, r, 400, "invalid_request", "invalid attachment_ids")
|
|
return
|
|
}
|
|
seen[id] = true
|
|
}
|
|
if req.AttachmentIDs == nil {
|
|
req.AttachmentIDs = []uuid.UUID{}
|
|
}
|
|
message := model.Message{
|
|
ID: uuid.New(),
|
|
ChatID: chatID,
|
|
SenderID: currentUser.ID,
|
|
Text: req.Text,
|
|
AttachmentIDs: req.AttachmentIDs,
|
|
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
|
}
|
|
|
|
message, err := h.messages.CreateMessageIdempotent(r.Context(), message, key)
|
|
if errors.Is(err, storage.ErrIdempotencyConflict) {
|
|
writeError(w, r, http.StatusConflict, "conflict", "Idempotency-Key reused with different body")
|
|
return
|
|
}
|
|
if errors.Is(err, storage.ErrAttachmentNotFound) {
|
|
writeError(w, r, 404, "not_found", "attachment not found")
|
|
return
|
|
}
|
|
if errors.Is(err, storage.ErrMessageMemberNotFound) {
|
|
writeError(w, r, http.StatusNotFound,
|
|
"not_found", "chat not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, r, http.StatusServiceUnavailable,
|
|
"unavailable", "service unavailable")
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusCreated, message)
|
|
}
|
|
|
|
func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) {
|
|
chatID, ok := h.accessibleChat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
limit := 50
|
|
if raw := r.URL.Query().Get("limit"); raw != "" {
|
|
parsed, err := strconv.Atoi(raw)
|
|
if err != nil || parsed < 1 || parsed > 100 {
|
|
writeError(w, r, http.StatusBadRequest,
|
|
"invalid_request", "limit must be between 1 and 100")
|
|
return
|
|
}
|
|
limit = parsed
|
|
}
|
|
|
|
var cursorTime *time.Time
|
|
var cursorID *uuid.UUID
|
|
|
|
if raw := r.URL.Query().Get("cursor"); raw != "" {
|
|
t, id, err := decodeMessageCursor(raw, chatID)
|
|
if err != nil {
|
|
writeError(w, r, http.StatusBadRequest,
|
|
"invalid_request", "invalid cursor")
|
|
return
|
|
}
|
|
cursorTime = &t
|
|
cursorID = &id
|
|
}
|
|
|
|
items, hasMore, err := h.messages.ListMessages(
|
|
r.Context(), chatID, limit, cursorTime, cursorID,
|
|
)
|
|
if err != nil {
|
|
writeError(w, r, http.StatusServiceUnavailable,
|
|
"unavailable", "service unavailable")
|
|
return
|
|
}
|
|
|
|
var nextCursor *string
|
|
if hasMore && len(items) > 0 {
|
|
cursor := encodeMessageCursor(items[len(items)-1])
|
|
nextCursor = &cursor
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, messagePage{
|
|
Items: items,
|
|
NextCursor: nextCursor,
|
|
})
|
|
}
|
|
|
|
// Cursor contains the chat UUID to prevent cross-chat replay.
|
|
func encodeMessageCursor(message model.Message) string {
|
|
value := fmt.Sprintf("%s|%s|%s", message.ChatID, message.CreatedAt.Format(time.RFC3339Nano), message.ID)
|
|
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
|
}
|
|
|
|
func decodeMessageCursor(cursor string, chatID uuid.UUID) (time.Time, uuid.UUID, error) {
|
|
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
|
if err != nil {
|
|
return time.Time{}, uuid.Nil, err
|
|
}
|
|
parts := strings.Split(string(data), "|")
|
|
if len(parts) != 3 || parts[0] != chatID.String() {
|
|
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor for chat")
|
|
}
|
|
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
|
if err != nil {
|
|
return time.Time{}, uuid.Nil, err
|
|
}
|
|
id, err := uuid.Parse(parts[2])
|
|
if err != nil {
|
|
return time.Time{}, uuid.Nil, err
|
|
}
|
|
return t, id, nil
|
|
}
|