forked from mtusi2026/mtusi2026lab6
83 lines
2.2 KiB
Go
83 lines
2.2 KiB
Go
package model
|
||
|
||
import (
|
||
"crypto/sha256"
|
||
"encoding/hex"
|
||
"encoding/json"
|
||
"regexp"
|
||
"slices"
|
||
"strings"
|
||
"time"
|
||
"unicode/utf8"
|
||
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
const MaxMessageRunes = 4000
|
||
|
||
type Message struct {
|
||
ID uuid.UUID
|
||
ChatID uuid.UUID
|
||
SenderID uuid.UUID
|
||
Text string
|
||
CreatedAt time.Time
|
||
AttachmentIDs []uuid.UUID
|
||
}
|
||
|
||
// MessageDraft — проверенное сообщение; отправитель берётся из идентификации,
|
||
// а не из тела запроса.
|
||
type MessageDraft struct {
|
||
ChatID uuid.UUID
|
||
SenderID uuid.UUID
|
||
Text string
|
||
Key string
|
||
PayloadHash string
|
||
AttachmentIDs []uuid.UUID
|
||
}
|
||
|
||
var keyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||
|
||
func WithKey(d MessageDraft, key string) (MessageDraft, error) {
|
||
if !keyPattern.MatchString(key) {
|
||
return MessageDraft{}, invalidf("Idempotency-Key: 1–128 ASCII characters required")
|
||
}
|
||
canonical, _ := json.Marshal(struct {
|
||
Text string
|
||
Attachments []uuid.UUID
|
||
}{d.Text, d.AttachmentIDs})
|
||
sum := sha256.Sum256(canonical)
|
||
d.Key = key
|
||
d.PayloadHash = hex.EncodeToString(sum[:])
|
||
return d, nil
|
||
}
|
||
|
||
func NewMessageDraft(chatID, senderID uuid.UUID, text string, attachments ...[]uuid.UUID) (MessageDraft, error) {
|
||
ids := []uuid.UUID{}
|
||
if len(attachments) > 0 {
|
||
ids = slices.Clone(attachments[0])
|
||
if ids == nil {
|
||
ids = []uuid.UUID{}
|
||
}
|
||
}
|
||
if len(ids) > 10 {
|
||
return MessageDraft{}, invalidf("attachment_ids: at most 10")
|
||
}
|
||
seen := map[uuid.UUID]bool{}
|
||
for _, id := range ids {
|
||
if seen[id] {
|
||
return MessageDraft{}, invalidf("attachment_ids: duplicate")
|
||
}
|
||
seen[id] = true
|
||
}
|
||
if len(ids) == 0 || strings.TrimSpace(text) != "" {
|
||
if err := requireText("text", text, 1, MaxMessageRunes); err != nil {
|
||
return MessageDraft{}, err
|
||
}
|
||
} else if !utf8.ValidString(text) || utf8.RuneCountInString(text) > MaxMessageRunes || strings.ContainsRune(text, 0) {
|
||
return MessageDraft{}, invalidf("text: invalid optional text")
|
||
}
|
||
return MessageDraft{ChatID: chatID, SenderID: senderID, Text: text, AttachmentIDs: ids}, nil
|
||
}
|
||
|
||
func (m Message) Position() Position { return Position{CreatedAt: m.CreatedAt, ID: m.ID} }
|