forked from mtusi2026/mtusi2026lab2
159 lines
5.8 KiB
Go
159 lines
5.8 KiB
Go
package chat
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"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 !validRequiredText(message.Text, 4000) {
|
|
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
|
|
}
|
|
created, err := u.repository.CreateMessage(ctx, chatID, callerID, message.Text)
|
|
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, "Объект не найден")
|
|
}
|