Files
mtusi2026lab4/internal/usecase/chat/service.go
T
2026-10-28 22:41:10 +03:00

183 lines
6.9 KiB
Go

package chat
import (
"context"
"errors"
"strings"
"time"
"unicode/utf8"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
)
type UseCase struct {
repository Repository
sessions Sessions
sessionTTL time.Duration
}
func New(repository Repository, sessions Sessions, ttl time.Duration) *UseCase {
return &UseCase{repository: repository, sessions: sessions, sessionTTL: ttl}
}
func (u *UseCase) CreateUser(ctx context.Context, user domain.User, secret string) (domain.User, error) {
if !validUsername(user.Username) {
return domain.User{}, invalid("username должен соответствовать [a-z0-9_]{3,32}")
}
if !validRequiredText(user.DisplayName, 100) {
return domain.User{}, invalid("display_name должен содержать от 1 до 100 символов")
}
if !validPassword(secret) {
return domain.User{}, invalid("password должен содержать от 12 до 128 символов")
}
hash, err := password.Hash(ctx, secret)
if err != nil {
return domain.User{}, err
}
created, err := u.repository.CreateUser(ctx, user.Username, user.DisplayName, hash)
if errors.Is(err, ErrUsernameTaken) {
return domain.User{}, domain.NewApplicationError(domain.ErrorConflict, "Пользователь с таким username уже существует")
}
return created, err
}
func (u *UseCase) CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
if !validRequiredText(chat.Title, 100) {
return domain.Chat{}, invalid("title должен содержать от 1 до 100 символов")
}
if len(chat.MemberIDs) < 1 || len(chat.MemberIDs) > 100 {
return domain.Chat{}, invalid("member_ids должен содержать от 1 до 100 участников")
}
normalizedIDs := make([]string, len(chat.MemberIDs))
seen := make(map[string]struct{}, len(chat.MemberIDs))
callerIncluded := false
for index, memberID := range chat.MemberIDs {
normalized, valid := normalizeUUID(memberID)
if !valid {
return domain.Chat{}, invalid("member_ids содержит некорректный UUID")
}
if _, duplicate := seen[normalized]; duplicate {
return domain.Chat{}, invalid("member_ids содержит повторяющиеся UUID")
}
normalizedIDs[index] = normalized
seen[normalized] = struct{}{}
callerIncluded = callerIncluded || normalized == callerID
}
if !callerIncluded {
return domain.Chat{}, invalid("текущий пользователь должен входить в member_ids")
}
created, err := u.repository.CreateChat(ctx, chat.Title, normalizedIDs)
if errors.Is(err, ErrUserNotFound) {
return domain.Chat{}, invalid("member_ids содержит неизвестного пользователя")
}
return created, err
}
func (u *UseCase) GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
chatID, valid := normalizeUUID(chat.ID)
if !valid {
return domain.Chat{}, invalid("Некорректный chat_id")
}
return u.chatForUser(ctx, chatID, callerID)
}
func (u *UseCase) ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error) {
if pagination.Limit < 1 || pagination.Limit > 100 {
return domain.ChatPage{}, invalid("limit должен быть целым числом от 1 до 100")
}
items, err := u.repository.ListChats(ctx, callerID, pagination.After, pagination.Limit+1)
if err != nil {
return domain.ChatPage{}, err
}
page := domain.ChatPage{Items: items, HasMore: len(items) > pagination.Limit}
if page.HasMore {
page.Items = page.Items[:pagination.Limit]
}
return page, nil
}
func (u *UseCase) CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error) {
chatID, valid := normalizeUUID(message.ChatID)
if !valid {
return domain.Message{}, invalid("Некорректный chat_id")
}
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
return domain.Message{}, err
}
if !utf8.ValidString(message.Text) || utf8.RuneCountInString(message.Text) > 4000 || (strings.TrimSpace(message.Text) == "" && len(message.AttachmentIDs) == 0) {
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
}
if len(message.AttachmentIDs) > 10 {
return domain.Message{}, invalid("Не более 10 вложений")
}
seen := map[string]bool{}
for i, id := range message.AttachmentIDs {
normalized, ok := normalizeUUID(id)
if !ok || seen[normalized] {
return domain.Message{}, invalid("Некорректные или повторные attachment_ids")
}
seen[normalized] = true
message.AttachmentIDs[i] = normalized
}
var created domain.Message
var err error
if repository, ok := u.repository.(interface {
CreateMessageWithAttachments(context.Context, string, string, string, string, []string) (domain.Message, error)
}); ok {
created, err = repository.CreateMessageWithAttachments(ctx, chatID, callerID, message.Text, message.IdempotencyKey, message.AttachmentIDs)
} else if len(message.AttachmentIDs) > 0 {
return domain.Message{}, notFound()
} else {
created, err = u.repository.CreateMessage(ctx, chatID, callerID, message.Text, message.IdempotencyKey)
}
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
return domain.Message{}, notFound()
}
return created, err
}
func (u *UseCase) ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error) {
chatID, valid := normalizeUUID(chat.ID)
if !valid {
return domain.MessagePage{}, invalid("Некорректный chat_id")
}
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
return domain.MessagePage{}, err
}
if pagination.Limit < 1 || pagination.Limit > 100 {
return domain.MessagePage{}, invalid("limit должен быть целым числом от 1 до 100")
}
items, err := u.repository.ListMessages(ctx, chatID, pagination.After, pagination.Limit+1)
if err != nil {
return domain.MessagePage{}, err
}
page := domain.MessagePage{Items: items, HasMore: len(items) > pagination.Limit}
if page.HasMore {
page.Items = page.Items[:pagination.Limit]
}
return page, nil
}
func (u *UseCase) chatForUser(ctx context.Context, chatID, callerID string) (domain.Chat, error) {
chat, err := u.repository.ChatForUser(ctx, chatID, callerID)
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
return domain.Chat{}, notFound()
}
return chat, err
}
func invalid(message string) error {
return domain.NewApplicationError(domain.ErrorInvalid, message)
}
func unauthorized() error {
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительная сессия")
}
func notFound() error {
return domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
}