forked from mtusi2026/mtusi2026lab3
78 lines
2.0 KiB
Go
78 lines
2.0 KiB
Go
package application
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"mtusi2026lab3/internal/domain"
|
|
)
|
|
|
|
type canonicalMessageRequest struct {
|
|
Text string `json:"text"`
|
|
AttachmentIDs []string `json:"attachment_ids"`
|
|
}
|
|
|
|
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
|
|
if err := domain.ValidateMessageText(command.Text); err != nil {
|
|
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
|
}
|
|
|
|
canonicalBody, err := json.Marshal(canonicalMessageRequest{
|
|
Text: command.Text,
|
|
AttachmentIDs: make([]string, 0),
|
|
})
|
|
if err != nil {
|
|
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
|
|
}
|
|
|
|
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
|
|
ActorID: command.ActorID,
|
|
ChatID: command.ChatID,
|
|
Text: command.Text,
|
|
Method: command.Method,
|
|
CanonicalPath: command.CanonicalPath,
|
|
Key: command.IdempotencyKey,
|
|
RequestHash: sha256.Sum256(canonicalBody),
|
|
TTL: s.idempotencyTTL,
|
|
})
|
|
}
|
|
|
|
func (s *Service) ListMessages(
|
|
ctx context.Context,
|
|
actorID string,
|
|
chatID string,
|
|
limit int,
|
|
cursorToken string,
|
|
) (domain.MessagePage, error) {
|
|
var cursor *domain.MessageCursor
|
|
if cursorToken != "" {
|
|
decoded, err := s.cursors.DecodeMessage(cursorToken, chatID)
|
|
if err != nil {
|
|
return domain.MessagePage{}, ErrInvalidCursor
|
|
}
|
|
cursor = decoded
|
|
}
|
|
|
|
items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor)
|
|
if err != nil {
|
|
return domain.MessagePage{}, err
|
|
}
|
|
page := domain.MessagePage{Items: items}
|
|
if page.Items == nil {
|
|
page.Items = make([]domain.Message, 0)
|
|
}
|
|
if hasMore {
|
|
last := page.Items[len(page.Items)-1]
|
|
next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{
|
|
CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID,
|
|
})
|
|
if encodeErr != nil {
|
|
return domain.MessagePage{}, encodeErr
|
|
}
|
|
page.NextCursor = &next
|
|
}
|
|
return page, nil
|
|
}
|