112 lines
2.2 KiB
Go
112 lines
2.2 KiB
Go
package service
|
|
|
|
import (
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
|
)
|
|
|
|
func validText(value string, maxLength int) bool {
|
|
return utf8.ValidString(value) &&
|
|
strings.TrimSpace(value) != "" &&
|
|
utf8.RuneCountInString(value) <= maxLength
|
|
}
|
|
|
|
func (m *Messenger) CreateChat(
|
|
actorID string,
|
|
title string,
|
|
memberIDs []string,
|
|
) (model.Chat, error) {
|
|
if !validText(title, 100) ||
|
|
len(memberIDs) < 1 ||
|
|
len(memberIDs) > 100 {
|
|
return model.Chat{}, ErrInvalidRequest
|
|
}
|
|
|
|
normalized := make([]string, len(memberIDs))
|
|
|
|
for i, id := range memberIDs {
|
|
if !uuidPattern.MatchString(id) {
|
|
return model.Chat{}, ErrInvalidRequest
|
|
}
|
|
normalized[i] = strings.ToLower(id)
|
|
}
|
|
|
|
return m.store.CreateChat(actorID, title, normalized)
|
|
}
|
|
|
|
func (m *Messenger) GetChat(
|
|
actorID string,
|
|
chatID string,
|
|
) (model.Chat, error) {
|
|
if !uuidPattern.MatchString(chatID) {
|
|
return model.Chat{}, ErrInvalidRequest
|
|
}
|
|
|
|
return m.store.GetChat(actorID, strings.ToLower(chatID))
|
|
}
|
|
|
|
func (m *Messenger) ListChats(
|
|
actorID string,
|
|
limit int,
|
|
cursor string,
|
|
) (Page[model.Chat], error) {
|
|
chats := m.store.ListChats(actorID)
|
|
|
|
return paginate(
|
|
chats,
|
|
"chats:"+actorID,
|
|
limit,
|
|
cursor,
|
|
func(chat model.Chat) position {
|
|
return position{CreatedAt: chat.CreatedAt, ID: chat.ID}
|
|
},
|
|
)
|
|
}
|
|
|
|
func (m *Messenger) CreateMessage(
|
|
actorID string,
|
|
chatID string,
|
|
text string,
|
|
) (model.Message, error) {
|
|
chat, err := m.GetChat(actorID, chatID)
|
|
if err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
|
|
if !validText(text, 4000) {
|
|
return model.Message{}, ErrInvalidRequest
|
|
}
|
|
|
|
return m.store.CreateMessage(actorID, chat.ID, text)
|
|
}
|
|
|
|
func (m *Messenger) ListMessages(
|
|
actorID string,
|
|
chatID string,
|
|
limit int,
|
|
cursor string,
|
|
) (Page[model.Message], error) {
|
|
if !uuidPattern.MatchString(chatID) {
|
|
return Page[model.Message]{}, ErrInvalidRequest
|
|
}
|
|
|
|
chatID = strings.ToLower(chatID)
|
|
|
|
messages, err := m.store.ListMessages(actorID, chatID)
|
|
if err != nil {
|
|
return Page[model.Message]{}, err
|
|
}
|
|
|
|
return paginate(
|
|
messages,
|
|
"messages:"+chatID,
|
|
limit,
|
|
cursor,
|
|
func(message model.Message) position {
|
|
return position{CreatedAt: message.CreatedAt, ID: message.ID}
|
|
},
|
|
)
|
|
}
|