forked from mtusi2026/mtusi2026lab2
212 lines
4.6 KiB
Go
212 lines
4.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"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"`
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
|
chatID, ok := h.accessibleChat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
currentUser, _ := middleware.GetCurrentUser(r.Context())
|
|
|
|
var req createMessageRequest
|
|
decoder := json.NewDecoder(r.Body)
|
|
decoder.DisallowUnknownFields()
|
|
|
|
if err := decoder.Decode(&req); err != nil {
|
|
writeError(w, r, http.StatusBadRequest,
|
|
"invalid_request", "invalid request body")
|
|
return
|
|
}
|
|
|
|
textLength := utf8.RuneCountInString(req.Text)
|
|
if textLength < 1 || textLength > 4000 {
|
|
writeError(w, r, http.StatusBadRequest,
|
|
"invalid_request", "text must contain from 1 to 4000 characters")
|
|
return
|
|
}
|
|
|
|
message := model.Message{
|
|
ID: uuid.New(),
|
|
ChatID: chatID,
|
|
SenderID: currentUser.ID,
|
|
Text: req.Text,
|
|
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
|
}
|
|
|
|
err := h.messages.CreateMessage(r.Context(), message)
|
|
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 := decodeCursor(raw)
|
|
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 := encodeCursor(items[len(items)-1])
|
|
nextCursor = &cursor
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, messagePage{
|
|
Items: items,
|
|
NextCursor: nextCursor,
|
|
})
|
|
}
|
|
|
|
func encodeCursor(message model.Message) string {
|
|
value := fmt.Sprintf(
|
|
"%s|%s",
|
|
message.CreatedAt.Format(time.RFC3339Nano),
|
|
message.ID.String(),
|
|
)
|
|
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
|
}
|
|
|
|
func decodeCursor(cursor string) (time.Time, uuid.UUID, error) {
|
|
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
|
if err != nil {
|
|
return time.Time{}, uuid.Nil, err
|
|
}
|
|
|
|
parts := strings.SplitN(string(data), "|", 2)
|
|
if len(parts) != 2 {
|
|
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor")
|
|
}
|
|
|
|
createdAt, err := time.Parse(time.RFC3339Nano, parts[0])
|
|
if err != nil {
|
|
return time.Time{}, uuid.Nil, err
|
|
}
|
|
|
|
id, err := uuid.Parse(parts[1])
|
|
if err != nil {
|
|
return time.Time{}, uuid.Nil, err
|
|
}
|
|
|
|
return createdAt, id, nil
|
|
}
|