forked from mtusi2026/mtusi2026lab3
52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package model
|
||
|
||
import (
|
||
"crypto/sha256"
|
||
"encoding/hex"
|
||
"regexp"
|
||
"time"
|
||
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
const MaxMessageRunes = 4000
|
||
|
||
type Message struct {
|
||
ID uuid.UUID
|
||
ChatID uuid.UUID
|
||
SenderID uuid.UUID
|
||
Text string
|
||
CreatedAt time.Time
|
||
}
|
||
|
||
// MessageDraft — проверенное сообщение; отправитель берётся из идентификации,
|
||
// а не из тела запроса.
|
||
type MessageDraft struct {
|
||
ChatID uuid.UUID
|
||
SenderID uuid.UUID
|
||
Text string
|
||
Key string
|
||
PayloadHash string
|
||
}
|
||
|
||
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")
|
||
}
|
||
sum := sha256.Sum256([]byte(d.Text))
|
||
d.Key = key
|
||
d.PayloadHash = hex.EncodeToString(sum[:])
|
||
return d, nil
|
||
}
|
||
|
||
func NewMessageDraft(chatID, senderID uuid.UUID, text string) (MessageDraft, error) {
|
||
if err := requireText("text", text, 1, MaxMessageRunes); err != nil {
|
||
return MessageDraft{}, err
|
||
}
|
||
return MessageDraft{ChatID: chatID, SenderID: senderID, Text: text}, nil
|
||
}
|
||
|
||
func (m Message) Position() Position { return Position{CreatedAt: m.CreatedAt, ID: m.ID} }
|