forked from mtusi2026/mtusi2026lab2
224 lines
5.7 KiB
Go
224 lines
5.7 KiB
Go
package domain
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
var (
|
|
//регулярка по контракту
|
|
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
|
)
|
|
|
|
type User struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
type Chat struct {
|
|
ID string `json:"id"`
|
|
Title string `json:"title"`
|
|
MemberIDs []string `json:"member_ids"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
type Message struct {
|
|
ID string `json:"id"`
|
|
ChatID string `json:"chat_id"`
|
|
SenderID string `json:"sender_id"`
|
|
Text string `json:"text"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
// страница выдачи истории сообщений
|
|
type MessagePage struct {
|
|
Items []Message `json:"items"`
|
|
NextCursor *string `json:"next_cursor"`
|
|
}
|
|
|
|
func (u *User) Validate() error {
|
|
if !usernameRegex.MatchString(u.Username) {
|
|
return fmt.Errorf("username must match [a-z0-9_]{3,32}")
|
|
}
|
|
|
|
nameRunes := utf8.RuneCountInString(u.DisplayName)
|
|
if nameRunes < 1 || nameRunes > 100 {
|
|
return fmt.Errorf("display_name length must be between 1 and 100 code points")
|
|
}
|
|
|
|
if strings.TrimSpace(u.DisplayName) == "" {
|
|
return fmt.Errorf("display_name cannot be only whitespace")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func ValidateChatInput(title string, memberIDs []string, callerID string) error {
|
|
titleRunes := utf8.RuneCountInString(title)
|
|
if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" {
|
|
return fmt.Errorf("invalid chat title")
|
|
}
|
|
|
|
if len(memberIDs) == 0 {
|
|
return fmt.Errorf("member_ids cannot be empty")
|
|
}
|
|
|
|
hasCaller := false
|
|
seen := make(map[string]bool)
|
|
|
|
for _, id := range memberIDs {
|
|
if _, err := uuid.Parse(id); err != nil {
|
|
return fmt.Errorf("invalid member uuid: %s", id)
|
|
}
|
|
if seen[id] {
|
|
return fmt.Errorf("duplicate member_id: %s", id)
|
|
}
|
|
seen[id] = true
|
|
|
|
if id == callerID {
|
|
hasCaller = true
|
|
}
|
|
}
|
|
|
|
if !hasCaller {
|
|
return fmt.Errorf("caller must be in member_ids")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func ValidateMessageText(text string) error {
|
|
textRunes := utf8.RuneCountInString(text)
|
|
if textRunes < 1 || textRunes > 4000 {
|
|
return fmt.Errorf("message text length must be between 1 and 4000 code points")
|
|
}
|
|
if strings.TrimSpace(text) == "" {
|
|
return fmt.Errorf("message text cannot be only whitespace")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type CursorData struct {
|
|
CreatedAt time.Time
|
|
MessageID string
|
|
ChatID string
|
|
}
|
|
|
|
// EncodeCursor превращает время, message_id и chat_id в непрозрачную base64 строку
|
|
func EncodeCursor(createdAt time.Time, messageID, chatID string) string {
|
|
raw := fmt.Sprintf("%s|%s|%s", createdAt.Format(time.RFC3339Nano), messageID, chatID)
|
|
return base64.StdEncoding.EncodeToString([]byte(raw))
|
|
}
|
|
|
|
// DecodeCursor декодирует строку курсора и проверяет, что он принадлежит именно этому чату
|
|
func DecodeCursor(cursorStr string, expectedChatID string) (*CursorData, error) {
|
|
bytes, err := base64.StdEncoding.DecodeString(cursorStr)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid base64 cursor")
|
|
}
|
|
|
|
parts := strings.Split(string(bytes), "|")
|
|
if len(parts) != 3 {
|
|
return nil, fmt.Errorf("malformed cursor")
|
|
}
|
|
|
|
t, err := time.Parse(time.RFC3339Nano, parts[0])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid cursor timestamp")
|
|
}
|
|
|
|
chatID := parts[2]
|
|
//защита из контракта: курсор от другого чата должен давать 400
|
|
if chatID != expectedChatID {
|
|
return nil, fmt.Errorf("cursor belongs to another chat")
|
|
}
|
|
|
|
return &CursorData{
|
|
CreatedAt: t,
|
|
MessageID: parts[1],
|
|
ChatID: chatID,
|
|
}, nil
|
|
}
|
|
|
|
// страница со списком чатов пользователя
|
|
type ChatPage struct {
|
|
Items []Chat `json:"items"`
|
|
NextCursor *string `json:"next_cursor"`
|
|
}
|
|
|
|
const chatCursorVersion = "v1"
|
|
|
|
type ChatCursorData struct {
|
|
CreatedAt time.Time
|
|
ChatID string
|
|
UserID string
|
|
}
|
|
|
|
// EncodeChatCursor создаёт непрозрачную границу списка чатов.
|
|
// Версия позволяет в будущем изменить внутренний формат курсора.
|
|
func EncodeChatCursor(createdAt time.Time, chatID, userID string) string {
|
|
raw := fmt.Sprintf(
|
|
"%s|%s|%s|%s",
|
|
chatCursorVersion,
|
|
createdAt.UTC().Format(time.RFC3339Nano),
|
|
chatID,
|
|
userID,
|
|
)
|
|
|
|
// RawURLEncoding не использует символы +, / и завершающий =,
|
|
// поэтому курсор безопаснее передавать в query string.
|
|
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
|
}
|
|
|
|
func DecodeChatCursor(
|
|
cursorStr string,
|
|
expectedUserID string,
|
|
) (*ChatCursorData, error) {
|
|
decoded, err := base64.RawURLEncoding.DecodeString(cursorStr)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid base64 chat cursor")
|
|
}
|
|
|
|
parts := strings.Split(string(decoded), "|")
|
|
if len(parts) != 4 {
|
|
return nil, fmt.Errorf("malformed chat cursor")
|
|
}
|
|
|
|
if parts[0] != chatCursorVersion {
|
|
return nil, fmt.Errorf("unsupported chat cursor version")
|
|
}
|
|
|
|
createdAt, err := time.Parse(time.RFC3339Nano, parts[1])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid chat cursor timestamp")
|
|
}
|
|
|
|
chatID := parts[2]
|
|
if _, err = uuid.Parse(chatID); err != nil {
|
|
return nil, fmt.Errorf("invalid chat cursor chat_id")
|
|
}
|
|
|
|
userID := parts[3]
|
|
if _, err = uuid.Parse(userID); err != nil {
|
|
return nil, fmt.Errorf("invalid chat cursor user_id")
|
|
}
|
|
|
|
if userID != expectedUserID {
|
|
return nil, fmt.Errorf("chat cursor belongs to another user")
|
|
}
|
|
|
|
return &ChatCursorData{
|
|
CreatedAt: createdAt,
|
|
ChatID: chatID,
|
|
UserID: userID,
|
|
}, nil
|
|
}
|