forked from mtusi2026/mtusi2026lab4
42 lines
1.3 KiB
Go
42 lines
1.3 KiB
Go
package services
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"regexp"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"messenger/src/backend/repositories"
|
|
)
|
|
|
|
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
|
|
|
func (s *MessageService) CreateIdempotent(ctx context.Context, userID string, chat repositories.Chat, text, key string, attachments ...[]string) (repositories.Message, error) {
|
|
if !ChatHasMember(chat, userID) {
|
|
return repositories.Message{}, ErrChatNotFound
|
|
}
|
|
if !idempotencyKeyPattern.MatchString(key) {
|
|
return repositories.Message{}, InvalidInput{"Idempotency-Key must contain 1-128 ASCII letters, digits or ._:-"}
|
|
}
|
|
var ids []string
|
|
if len(attachments) > 0 {
|
|
ids = attachments[0]
|
|
}
|
|
ids, err := NormalizeAttachmentIDs(ids)
|
|
if err != nil {
|
|
return repositories.Message{}, err
|
|
}
|
|
if (strings.TrimSpace(text) == "" && len(ids) == 0) || utf8.RuneCountInString(text) > 4000 {
|
|
return repositories.Message{}, InvalidInput{"text must be at most 4000 characters; nonblank text or attachments required"}
|
|
}
|
|
message, err := s.messages.CreateIdempotent(ctx, chat.ID, userID, text, key, ids)
|
|
if errors.Is(err, repositories.ErrAttachmentNotFound) {
|
|
return repositories.Message{}, ErrAttachmentNotFound
|
|
}
|
|
if errors.Is(err, repositories.ErrIdempotencyConflict) {
|
|
return repositories.Message{}, ErrConflict
|
|
}
|
|
return message, err
|
|
}
|