feat(messages): сообщения, реакции, пины, typing, read states и поиск
Бэкенд текстовой связи (AGENT.md 7.6, 7.15, 7.16, 8.6):
- POST/GET/PATCH/DELETE /channels/{id}/messages, ответы и упоминания,
окно правки 24 часа, права автора или MANAGE_MESSAGES;
- реакции (PUT/DELETE .../reactions/{emoji}) с агрегацией и отметкой «моя»;
- закрепления (GET/PUT/DELETE .../pins) под MANAGE_MESSAGES;
- typing с лимитом 1/3 с и адресной рассылкой всем, кроме автора;
- read states: POST /channels/{id}/ack, синхронизация READ_STATE_UPDATE между
устройствами пользователя;
- поиск FTS5 по комнате (10/мин) с экранированием запроса;
- лимиты отправки 5/5 с (burst 10) и slowmode комнаты; администратор инстанса
обходит и то, и другое (AGENT.md 7.19);
- Gateway: DispatchToChannel/DispatchToChannelExcept доставляют события комнат
только тем, кто видит комнату (VIEW_CHANNEL), права считает общий движок;
- store: messages, message_reactions, channel_read_states, files (загрузка
файлов появится вместе с вложениями).
Тесты: жизненный цикл сообщения, видимость скрытой комнаты (404 участнику,
200 админу), slowmode, упоминания и ответы, typing и read state, фильтрация
событий комнаты между двумя WS-клиентами.
This commit is contained in:
@@ -87,15 +87,24 @@ type humaAPIError struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
details map[string]any
|
||||
}
|
||||
|
||||
func (e *humaAPIError) Error() string { return e.code + ": " + e.message }
|
||||
func (e *humaAPIError) GetStatus() int { return e.status }
|
||||
|
||||
func (e *humaAPIError) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(map[string]any{
|
||||
"error": map[string]any{"code": e.code, "message": e.message},
|
||||
})
|
||||
payload := map[string]any{"code": e.code, "message": e.message}
|
||||
for key, value := range e.details {
|
||||
payload[key] = value
|
||||
}
|
||||
return json.Marshal(map[string]any{"error": payload})
|
||||
}
|
||||
|
||||
// humaErrorStatusDetails добавляет машиночитаемые детали (например,
|
||||
// retry_after_ms для 429), AGENT.md 8.5.
|
||||
func humaErrorStatusDetails(status int, code, message string, details map[string]any) huma.StatusError {
|
||||
return &humaAPIError{status: status, code: code, message: message, details: details}
|
||||
}
|
||||
|
||||
// humaErrorStatus создаёт ошибку с явным кодом.
|
||||
|
||||
@@ -0,0 +1,832 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"glchat/internal/permissions"
|
||||
"glchat/internal/store"
|
||||
)
|
||||
|
||||
// mentionPattern находит упоминания вида <@123> (AGENT.md 7.6).
|
||||
var mentionPattern = regexp.MustCompile(`<@([0-9]{1,20})>`)
|
||||
|
||||
// messageKey ключует лимиты по комнате и пользователю.
|
||||
func messageKey(channelID, userID uint64) string {
|
||||
return formatSnowflake(channelID) + ":" + formatSnowflake(userID)
|
||||
}
|
||||
|
||||
// editWindow — сколько времени автор может править сообщение (AGENT.md 7.6).
|
||||
const editWindow = 24 * time.Hour
|
||||
|
||||
type attachmentPayload struct {
|
||||
FileID string `json:"file_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type,omitempty"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
Width int `json:"width,omitempty"`
|
||||
Height int `json:"height,omitempty"`
|
||||
}
|
||||
|
||||
type reactionPayload struct {
|
||||
Emoji string `json:"emoji"`
|
||||
Count int `json:"count"`
|
||||
Me bool `json:"me"`
|
||||
UserIDs []string `json:"user_ids,omitempty"`
|
||||
}
|
||||
|
||||
type messagePayload struct {
|
||||
ID string `json:"id"`
|
||||
ChannelID string `json:"channel_id"`
|
||||
AuthorID string `json:"author_id,omitempty"`
|
||||
Content string `json:"content"`
|
||||
ReplyToID string `json:"reply_to_id,omitempty"`
|
||||
Type string `json:"type"`
|
||||
EditedAt string `json:"edited_at,omitempty"`
|
||||
Pinned bool `json:"pinned"`
|
||||
Attachments []attachmentPayload `json:"attachments"`
|
||||
Mentions []string `json:"mentions"`
|
||||
Reactions []reactionPayload `json:"reactions"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageListOutput struct {
|
||||
Body struct {
|
||||
Messages []messagePayload `json:"messages"`
|
||||
}
|
||||
}
|
||||
|
||||
type messageOutput struct {
|
||||
Body struct {
|
||||
Message messagePayload `json:"message"`
|
||||
}
|
||||
}
|
||||
|
||||
// registerMessageRoutes описывает ручки сообщений, реакций, пинов, typing и
|
||||
// read states (AGENT.md 7.6, 7.16).
|
||||
func (s *Server) registerMessageRoutes(api huma.API) {
|
||||
security := []map[string][]string{{"sessionCookie": {}}, {"bearerAuth": {}}}
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "createMessage",
|
||||
Method: http.MethodPost,
|
||||
Path: "/channels/{channel_id}/messages",
|
||||
Summary: "Отправить сообщение",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
Body struct {
|
||||
Content string `json:"content" maxLength:"4000"`
|
||||
ReplyToID string `json:"reply_to_id,omitempty"`
|
||||
AttachmentIDs []string `json:"attachment_ids,omitempty" maxItems:"20"`
|
||||
Nonce string `json:"nonce,omitempty" maxLength:"64"`
|
||||
}
|
||||
},
|
||||
) (*messageOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, resolved, channel, err := s.requireChannelPermission(ctx, input.ChannelID, user, permissions.SendMessages)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Антиспам-лимит: 5 сообщений за 5 секунд на комнату и пользователя,
|
||||
// администратор инстанса лимит обходит (AGENT.md 8.6, 7.19).
|
||||
if !user.IsInstanceAdmin {
|
||||
if allowed, retryAfter := s.messageLimiter.Allow(messageKey(channelID, user.ID)); !allowed {
|
||||
return nil, rateLimitedError(retryAfter)
|
||||
}
|
||||
if err := s.checkSlowmode(ctx, channel, user, resolved); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
content := strings.TrimSpace(input.Body.Content)
|
||||
attachments, err := s.attachmentsFromIDs(ctx, channelID, user.ID, input.Body.AttachmentIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if content == "" && len(attachments) == 0 {
|
||||
return nil, humaErrorStatus(http.StatusUnprocessableEntity, "validation.failed", "message must have content or attachments")
|
||||
}
|
||||
settings, err := s.store.InstanceSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
if len([]rune(content)) > settings.MaxMessageLength {
|
||||
return nil, humaErrorStatus(http.StatusUnprocessableEntity, "validation.failed", "message is too long")
|
||||
}
|
||||
|
||||
params := store.CreateMessageParams{
|
||||
ChannelID: channelID,
|
||||
AuthorID: user.ID,
|
||||
Content: content,
|
||||
Attachments: attachments,
|
||||
Mentions: s.extractMentions(ctx, channelID, content),
|
||||
}
|
||||
if input.Body.ReplyToID != "" {
|
||||
replyTo, err := parseID("reply_to_id", input.Body.ReplyToID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parent, err := s.store.GetMessage(ctx, replyTo)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
if parent.ChannelID != channelID {
|
||||
return nil, humaErrorStatus(http.StatusUnprocessableEntity, "validation.failed", "reply target is in another channel")
|
||||
}
|
||||
params.ReplyToID = &replyTo
|
||||
}
|
||||
|
||||
message, err := s.store.CreateMessage(ctx, params)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
// Вложения привязываем к сообщению: до этого они считаются сиротами.
|
||||
for _, attachment := range attachments {
|
||||
if err := s.store.AttachFileToMessage(ctx, attachment.FileID, message.ID); err != nil {
|
||||
s.logger.WarnContext(ctx, "failed to attach file to message",
|
||||
slog.String("file_id", formatSnowflake(attachment.FileID)), slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
s.rememberSlowmode(channelID, user.ID)
|
||||
payload, err := s.messagePayload(ctx, message, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.dispatchChannelEvent(ctx, channelID, "MESSAGE_CREATE", payload)
|
||||
output := &messageOutput{}
|
||||
output.Body.Message = payload
|
||||
return output, nil
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "listMessages",
|
||||
Method: http.MethodGet,
|
||||
Path: "/channels/{channel_id}/messages",
|
||||
Summary: "История сообщений комнаты",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
Before string `query:"before,omitempty"`
|
||||
Limit int `query:"limit" default:"50" minimum:"1" maximum:"100"`
|
||||
},
|
||||
) (*messageListOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, _, _, err := s.requireChannelPermission(ctx, input.ChannelID, user, permissions.ReadMessageHistory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
beforeID := uint64(0)
|
||||
if input.Before != "" {
|
||||
beforeID, err = parseID("before", input.Before)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
messages, err := s.store.ListMessages(ctx, channelID, beforeID, input.Limit)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
payloads, err := s.messagePayloads(ctx, messages, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
output := &messageListOutput{}
|
||||
output.Body.Messages = payloads
|
||||
return output, nil
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "searchMessages",
|
||||
Method: http.MethodGet,
|
||||
Path: "/channels/{channel_id}/messages/search",
|
||||
Summary: "Поиск по сообщениям комнаты (FTS5)",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
Query string `query:"q" minLength:"1" maxLength:"200"`
|
||||
Limit int `query:"limit" default:"25" minimum:"1" maximum:"100"`
|
||||
},
|
||||
) (*messageListOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, _, _, err := s.requireChannelPermission(ctx, input.ChannelID, user, permissions.ReadMessageHistory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if allowed, retryAfter := s.searchLimiter.Allow("search:" + formatSnowflake(user.ID)); !allowed {
|
||||
return nil, rateLimitedError(retryAfter)
|
||||
}
|
||||
messages, err := s.store.SearchMessages(ctx, []uint64{channelID}, toFTSQuery(input.Query), input.Limit)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
payloads, err := s.messagePayloads(ctx, messages, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
output := &messageListOutput{}
|
||||
output.Body.Messages = payloads
|
||||
return output, nil
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "updateMessage",
|
||||
Method: http.MethodPatch,
|
||||
Path: "/channels/{channel_id}/messages/{message_id}",
|
||||
Summary: "Изменить сообщение",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
MessageID string `path:"message_id"`
|
||||
Body struct {
|
||||
Content string `json:"content" maxLength:"4000"`
|
||||
}
|
||||
},
|
||||
) (*messageOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, resolved, _, err := s.requireChannelPermission(ctx, input.ChannelID, user, permissions.SendMessages)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message, err := s.messageInChannel(ctx, channelID, input.MessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.requireMessageAuthor(user, resolved, message, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
content := strings.TrimSpace(input.Body.Content)
|
||||
if content == "" && len(message.Attachments) == 0 {
|
||||
return nil, humaErrorStatus(http.StatusUnprocessableEntity, "validation.failed", "message must have content or attachments")
|
||||
}
|
||||
updated, err := s.store.UpdateMessageContent(ctx, message.ID, content)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
payload, err := s.messagePayload(ctx, updated, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.dispatchChannelEvent(ctx, channelID, "MESSAGE_UPDATE", payload)
|
||||
output := &messageOutput{}
|
||||
output.Body.Message = payload
|
||||
return output, nil
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "deleteMessage",
|
||||
Method: http.MethodDelete,
|
||||
Path: "/channels/{channel_id}/messages/{message_id}",
|
||||
Summary: "Удалить сообщение",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
MessageID string `path:"message_id"`
|
||||
},
|
||||
) (*okOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, resolved, _, err := s.requireChannelPermission(ctx, input.ChannelID, user, permissions.ViewChannel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message, err := s.messageInChannel(ctx, channelID, input.MessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.requireMessageAuthor(user, resolved, message, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.store.DeleteMessage(ctx, message.ID); err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
s.dispatchChannelEvent(ctx, channelID, "MESSAGE_DELETE", map[string]any{
|
||||
"id": formatSnowflake(message.ID),
|
||||
"channel_id": formatSnowflake(channelID),
|
||||
})
|
||||
return newOKOutput(), nil
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "addReaction",
|
||||
Method: http.MethodPut,
|
||||
Path: "/channels/{channel_id}/messages/{message_id}/reactions/{emoji}",
|
||||
Summary: "Поставить реакцию",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
MessageID string `path:"message_id"`
|
||||
Emoji string `path:"emoji"`
|
||||
},
|
||||
) (*okOutput, error) {
|
||||
return s.changeReaction(ctx, input.ChannelID, input.MessageID, input.Emoji, true)
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "removeReaction",
|
||||
Method: http.MethodDelete,
|
||||
Path: "/channels/{channel_id}/messages/{message_id}/reactions/{emoji}",
|
||||
Summary: "Снять реакцию",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
MessageID string `path:"message_id"`
|
||||
Emoji string `path:"emoji"`
|
||||
},
|
||||
) (*okOutput, error) {
|
||||
return s.changeReaction(ctx, input.ChannelID, input.MessageID, input.Emoji, false)
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "listPinnedMessages",
|
||||
Method: http.MethodGet,
|
||||
Path: "/channels/{channel_id}/pins",
|
||||
Summary: "Закреплённые сообщения",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
},
|
||||
) (*messageListOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, _, _, err := s.requireChannelPermission(ctx, input.ChannelID, user, permissions.ViewChannel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
messages, err := s.store.ListPinnedMessages(ctx, channelID, 50)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
payloads, err := s.messagePayloads(ctx, messages, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
output := &messageListOutput{}
|
||||
output.Body.Messages = payloads
|
||||
return output, nil
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "pinMessage",
|
||||
Method: http.MethodPut,
|
||||
Path: "/channels/{channel_id}/pins/{message_id}",
|
||||
Summary: "Закрепить сообщение",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
MessageID string `path:"message_id"`
|
||||
},
|
||||
) (*okOutput, error) {
|
||||
return s.changePin(ctx, input.ChannelID, input.MessageID, true)
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "unpinMessage",
|
||||
Method: http.MethodDelete,
|
||||
Path: "/channels/{channel_id}/pins/{message_id}",
|
||||
Summary: "Открепить сообщение",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
MessageID string `path:"message_id"`
|
||||
},
|
||||
) (*okOutput, error) {
|
||||
return s.changePin(ctx, input.ChannelID, input.MessageID, false)
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "sendTyping",
|
||||
Method: http.MethodPost,
|
||||
Path: "/channels/{channel_id}/typing",
|
||||
Summary: "Сообщить о наборе текста",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
},
|
||||
) (*okOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, _, _, err := s.requireChannelPermission(ctx, input.ChannelID, user, permissions.SendMessages)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Typing — не чаще одного раза в 3 секунды (AGENT.md 8.6).
|
||||
if allowed, _ := s.typingLimiter.Allow("typing:" + formatSnowflake(user.ID) + ":" + formatSnowflake(channelID)); !allowed {
|
||||
return newOKOutput(), nil
|
||||
}
|
||||
s.dispatchChannelEventExcept(ctx, channelID, user.ID, "TYPING_START", map[string]any{
|
||||
"channel_id": formatSnowflake(channelID),
|
||||
"user_id": formatSnowflake(user.ID),
|
||||
})
|
||||
return newOKOutput(), nil
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "acknowledgeChannel",
|
||||
Method: http.MethodPost,
|
||||
Path: "/channels/{channel_id}/ack",
|
||||
Summary: "Отметить комнату прочитанной",
|
||||
Tags: []string{"Messages"},
|
||||
Security: security,
|
||||
}, func(ctx context.Context, input *struct {
|
||||
ChannelID string `path:"channel_id"`
|
||||
Body struct {
|
||||
LastMessageID string `json:"last_message_id,omitempty"`
|
||||
}
|
||||
},
|
||||
) (*okOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, _, _, err := s.requireChannelPermission(ctx, input.ChannelID, user, permissions.ViewChannel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lastID := uint64(0)
|
||||
if input.Body.LastMessageID != "" {
|
||||
lastID, err = parseID("last_message_id", input.Body.LastMessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := s.store.SetReadState(ctx, user.ID, channelID, lastID, 0); err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
// Состояние прочтения синхронизируется между устройствами (AGENT.md 7.16).
|
||||
if s.gateway != nil {
|
||||
s.gateway.SendToUser(user.ID, "READ_STATE_UPDATE", map[string]any{
|
||||
"channel_id": formatSnowflake(channelID),
|
||||
"last_message_id": formatSnowflake(lastID),
|
||||
"mention_count": 0,
|
||||
})
|
||||
}
|
||||
return newOKOutput(), nil
|
||||
})
|
||||
}
|
||||
|
||||
// requireChannelPermission проверяет права пользователя в комнате и отдаёт её.
|
||||
func (s *Server) requireChannelPermission(ctx context.Context, rawChannelID string, user *store.User, permission permissions.Permission) (uint64, permissions.Resolved, *store.Channel, error) {
|
||||
channelID, err := parseID("channel_id", rawChannelID)
|
||||
if err != nil {
|
||||
return 0, permissions.Resolved{}, nil, err
|
||||
}
|
||||
channel, err := s.store.GetChannel(ctx, channelID)
|
||||
if err != nil {
|
||||
return 0, permissions.Resolved{}, nil, humaError(err)
|
||||
}
|
||||
if channel.GuildID == nil {
|
||||
// Личные комнаты появятся в Фазе 4: сейчас их нет.
|
||||
return 0, permissions.Resolved{}, nil, humaErrorStatus(http.StatusNotFound, "not_found", "channel not found")
|
||||
}
|
||||
resolved, err := s.perms.Channel(ctx, *channel.GuildID, channelID, user.ID, user.IsInstanceAdmin)
|
||||
if err != nil {
|
||||
return 0, permissions.Resolved{}, nil, humaError(err)
|
||||
}
|
||||
if !resolved.CanViewChannel() {
|
||||
return 0, permissions.Resolved{}, nil, humaErrorStatus(http.StatusNotFound, "not_found", "channel not found")
|
||||
}
|
||||
if !resolved.Can(permission) {
|
||||
return 0, permissions.Resolved{}, nil, humaErrorStatus(http.StatusForbidden, "perm.denied", "permission denied")
|
||||
}
|
||||
return channelID, resolved, channel, nil
|
||||
}
|
||||
|
||||
// messageInChannel проверяет, что сообщение принадлежит комнате.
|
||||
func (s *Server) messageInChannel(ctx context.Context, channelID uint64, rawMessageID string) (*store.Message, error) {
|
||||
messageID, err := parseID("message_id", rawMessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message, err := s.store.GetMessage(ctx, messageID)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
if message.ChannelID != channelID {
|
||||
return nil, humaErrorStatus(http.StatusNotFound, "not_found", "message not found")
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
// requireMessageAuthor разрешает действие автору сообщения или модератору с
|
||||
// MANAGE_MESSAGES; правка ограничена окном editWindow (AGENT.md 7.6).
|
||||
func (s *Server) requireMessageAuthor(user *store.User, resolved permissions.Resolved, message *store.Message, editing bool) error {
|
||||
isAuthor := message.AuthorID != nil && *message.AuthorID == user.ID
|
||||
if isAuthor {
|
||||
if editing && message.EditedAt == nil && time.Since(message.CreatedAt) > editWindow {
|
||||
return humaErrorStatus(http.StatusForbidden, "message.edit_window_expired", "message can no longer be edited")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if resolved.Has(permissions.ManageMessages) {
|
||||
return nil
|
||||
}
|
||||
return humaErrorStatus(http.StatusForbidden, "perm.denied", "permission denied")
|
||||
}
|
||||
|
||||
// changeReaction ставит или снимает реакцию и рассылает событие.
|
||||
func (s *Server) changeReaction(ctx context.Context, rawChannelID, rawMessageID, emoji string, add bool) (*okOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
emoji = strings.TrimSpace(emoji)
|
||||
if emoji == "" || len([]rune(emoji)) > 32 {
|
||||
return nil, humaErrorStatus(http.StatusUnprocessableEntity, "validation.failed", "emoji is invalid")
|
||||
}
|
||||
channelID, _, _, err := s.requireChannelPermission(ctx, rawChannelID, user, permissions.AddReactions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message, err := s.messageInChannel(ctx, channelID, rawMessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if add {
|
||||
err = s.store.AddReaction(ctx, message.ID, user.ID, emoji)
|
||||
} else {
|
||||
err = s.store.RemoveReaction(ctx, message.ID, user.ID, emoji)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
event := "MESSAGE_REACTION_REMOVE"
|
||||
if add {
|
||||
event = "MESSAGE_REACTION_ADD"
|
||||
}
|
||||
s.dispatchChannelEvent(ctx, channelID, event, map[string]any{
|
||||
"channel_id": formatSnowflake(channelID),
|
||||
"message_id": formatSnowflake(message.ID),
|
||||
"user_id": formatSnowflake(user.ID),
|
||||
"emoji": emoji,
|
||||
})
|
||||
return newOKOutput(), nil
|
||||
}
|
||||
|
||||
// changePin закрепляет или открепляет сообщение (нужно MANAGE_MESSAGES).
|
||||
func (s *Server) changePin(ctx context.Context, rawChannelID, rawMessageID string, pinned bool) (*okOutput, error) {
|
||||
user, _, err := requireUser(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelID, _, _, err := s.requireChannelPermission(ctx, rawChannelID, user, permissions.ManageMessages)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message, err := s.messageInChannel(ctx, channelID, rawMessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.store.SetMessagePinned(ctx, message.ID, pinned); err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
s.dispatchChannelEvent(ctx, channelID, "CHANNEL_PINS_UPDATE", map[string]any{
|
||||
"channel_id": formatSnowflake(channelID),
|
||||
"message_id": formatSnowflake(message.ID),
|
||||
"pinned": pinned,
|
||||
})
|
||||
return newOKOutput(), nil
|
||||
}
|
||||
|
||||
// messagePayload собирает сообщение для API с реакциями и автором.
|
||||
func (s *Server) messagePayload(ctx context.Context, message *store.Message, viewerID uint64) (messagePayload, error) {
|
||||
payload := messagePayload{
|
||||
ID: formatSnowflake(message.ID),
|
||||
ChannelID: formatSnowflake(message.ChannelID),
|
||||
Content: message.Content,
|
||||
Type: string(message.Type),
|
||||
Pinned: message.Pinned,
|
||||
Attachments: make([]attachmentPayload, 0, len(message.Attachments)),
|
||||
Mentions: make([]string, 0, len(message.Mentions)),
|
||||
Reactions: []reactionPayload{},
|
||||
CreatedAt: message.CreatedAt.UTC().Format(time.RFC3339),
|
||||
}
|
||||
if message.AuthorID != nil {
|
||||
payload.AuthorID = formatSnowflake(*message.AuthorID)
|
||||
}
|
||||
if message.ReplyToID != nil {
|
||||
payload.ReplyToID = formatSnowflake(*message.ReplyToID)
|
||||
}
|
||||
if message.EditedAt != nil {
|
||||
payload.EditedAt = message.EditedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
for _, attachment := range message.Attachments {
|
||||
payload.Attachments = append(payload.Attachments, attachmentPayload{
|
||||
FileID: formatSnowflake(attachment.FileID),
|
||||
Filename: attachment.Filename,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
Width: attachment.Width,
|
||||
Height: attachment.Height,
|
||||
})
|
||||
}
|
||||
for _, mention := range message.Mentions {
|
||||
payload.Mentions = append(payload.Mentions, formatSnowflake(mention))
|
||||
}
|
||||
reactions, err := s.store.ListReactions(ctx, message.ID, viewerID)
|
||||
if err != nil {
|
||||
return messagePayload{}, humaError(err)
|
||||
}
|
||||
for _, reaction := range reactions {
|
||||
item := reactionPayload{Emoji: reaction.Emoji, Count: reaction.Count, Me: reaction.Me}
|
||||
for _, userID := range reaction.UserIDs {
|
||||
item.UserIDs = append(item.UserIDs, formatSnowflake(userID))
|
||||
}
|
||||
payload.Reactions = append(payload.Reactions, item)
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (s *Server) messagePayloads(ctx context.Context, messages []store.Message, viewerID uint64) ([]messagePayload, error) {
|
||||
payloads := make([]messagePayload, 0, len(messages))
|
||||
for i := range messages {
|
||||
payload, err := s.messagePayload(ctx, &messages[i], viewerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payloads = append(payloads, payload)
|
||||
}
|
||||
return payloads, nil
|
||||
}
|
||||
|
||||
// dispatchChannelEvent рассылает событие комнаты только тем, кто её видит.
|
||||
func (s *Server) dispatchChannelEvent(ctx context.Context, channelID uint64, event string, payload any) {
|
||||
if s.gateway == nil {
|
||||
return
|
||||
}
|
||||
s.gateway.DispatchToChannel(ctx, channelID, event, payload)
|
||||
}
|
||||
|
||||
// dispatchChannelEventExcept рассылает событие всем, кроме указанного пользователя.
|
||||
func (s *Server) dispatchChannelEventExcept(ctx context.Context, channelID, exceptUserID uint64, event string, payload any) {
|
||||
if s.gateway == nil {
|
||||
return
|
||||
}
|
||||
s.gateway.DispatchToChannelExcept(ctx, channelID, exceptUserID, event, payload)
|
||||
}
|
||||
|
||||
// checkSlowmode проверяет режим медленной отправки комнаты (AGENT.md 7.5).
|
||||
func (s *Server) checkSlowmode(_ context.Context, channel *store.Channel, user *store.User, resolved permissions.Resolved) error {
|
||||
if channel.SlowmodeSeconds <= 0 || resolved.Has(permissions.ManageMessages) || resolved.Has(permissions.ManageChannels) {
|
||||
return nil
|
||||
}
|
||||
s.slowmodeMu.Lock()
|
||||
last, ok := s.slowmode[messageKey(channel.ID, user.ID)]
|
||||
s.slowmodeMu.Unlock()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
elapsed := time.Since(last)
|
||||
wait := time.Duration(channel.SlowmodeSeconds)*time.Second - elapsed
|
||||
if wait <= 0 {
|
||||
return nil
|
||||
}
|
||||
return rateLimitedError(wait)
|
||||
}
|
||||
|
||||
// rememberSlowmode запоминает время последней отправки в комнату.
|
||||
func (s *Server) rememberSlowmode(channelID, userID uint64) {
|
||||
s.slowmodeMu.Lock()
|
||||
defer s.slowmodeMu.Unlock()
|
||||
// Попутная уборка, чтобы словарь не рос бесконечно.
|
||||
if len(s.slowmode) > 4096 {
|
||||
cutoff := time.Now().Add(-time.Hour)
|
||||
for key, at := range s.slowmode {
|
||||
if at.Before(cutoff) {
|
||||
delete(s.slowmode, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.slowmode[messageKey(channelID, userID)] = time.Now()
|
||||
}
|
||||
|
||||
// extractMentions ищет упоминания вида <@123> и проверяет, что пользователь
|
||||
// состоит в сервере (AGENT.md 7.6).
|
||||
func (s *Server) extractMentions(ctx context.Context, channelID uint64, content string) []uint64 {
|
||||
if !strings.Contains(content, "<@") {
|
||||
return nil
|
||||
}
|
||||
channel, err := s.store.GetChannel(ctx, channelID)
|
||||
if err != nil || channel.GuildID == nil {
|
||||
return nil
|
||||
}
|
||||
members, err := s.store.ListGuildMembers(ctx, *channel.GuildID)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
known := make(map[uint64]bool, len(members))
|
||||
for _, member := range members {
|
||||
known[member.UserID] = true
|
||||
}
|
||||
mentions := make([]uint64, 0, 4)
|
||||
seen := map[uint64]bool{}
|
||||
for _, candidate := range mentionPattern.FindAllStringSubmatch(content, -1) {
|
||||
id, err := parseID("mention", candidate[1])
|
||||
if err != nil || !known[id] || seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
mentions = append(mentions, id)
|
||||
}
|
||||
return mentions
|
||||
}
|
||||
|
||||
// attachmentsFromIDs проверяет, что файлы загружены этим пользователем в эту
|
||||
// комнату и ещё не привязаны к сообщению (AGENT.md 7.7).
|
||||
func (s *Server) attachmentsFromIDs(ctx context.Context, channelID, userID uint64, rawIDs []string) ([]store.Attachment, error) {
|
||||
if len(rawIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
attachments := make([]store.Attachment, 0, len(rawIDs))
|
||||
for _, raw := range rawIDs {
|
||||
fileID, err := parseID("attachment_ids", raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := s.store.GetFile(ctx, fileID)
|
||||
if err != nil {
|
||||
return nil, humaError(err)
|
||||
}
|
||||
if file.UploaderID == nil || *file.UploaderID != userID || file.ChannelID == nil || *file.ChannelID != channelID {
|
||||
return nil, humaErrorStatus(http.StatusForbidden, "perm.denied", "attachment belongs to another user or channel")
|
||||
}
|
||||
attachments = append(attachments, store.Attachment{
|
||||
FileID: file.ID,
|
||||
Filename: file.Filename,
|
||||
ContentType: file.ContentType,
|
||||
SizeBytes: file.SizeBytes,
|
||||
Width: file.Width,
|
||||
Height: file.Height,
|
||||
})
|
||||
}
|
||||
return attachments, nil
|
||||
}
|
||||
|
||||
// rateLimitedError отдаёт 429 с подсказкой по паузе (AGENT.md 8.5, 8.6).
|
||||
func rateLimitedError(retryAfter time.Duration) huma.StatusError {
|
||||
milliseconds := retryAfter.Milliseconds()
|
||||
if milliseconds <= 0 {
|
||||
milliseconds = 1000
|
||||
}
|
||||
return humaErrorStatusDetails(http.StatusTooManyRequests, "rate_limited", "too many requests", map[string]any{
|
||||
"retry_after_ms": milliseconds,
|
||||
})
|
||||
}
|
||||
|
||||
// toFTSQuery превращает пользовательский ввод в безопасный запрос FTS5:
|
||||
// кавычки и служебные символы экранируются, слова соединяются по AND.
|
||||
func toFTSQuery(input string) string {
|
||||
fields := strings.FieldsFunc(input, func(r rune) bool {
|
||||
return r == ' ' || r == '\t' || r == '\n'
|
||||
})
|
||||
terms := make([]string, 0, len(fields))
|
||||
for _, field := range fields {
|
||||
cleaned := strings.Map(func(r rune) rune {
|
||||
switch r {
|
||||
case '"', '\'', '*', '(', ')', ':', '^', '-', '+':
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, field)
|
||||
if cleaned == "" {
|
||||
continue
|
||||
}
|
||||
terms = append(terms, `"`+cleaned+`"`)
|
||||
}
|
||||
return strings.Join(terms, " AND ")
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"glchat/internal/permissions"
|
||||
"glchat/internal/store"
|
||||
)
|
||||
|
||||
// storeOverride скрывает комнату от роли @user.
|
||||
func storeOverride(channelID, roleID uint64) store.ChannelOverride {
|
||||
return store.ChannelOverride{
|
||||
ChannelID: channelID, TargetType: "role", TargetID: roleID,
|
||||
Deny: uint64(permissions.ViewChannel),
|
||||
}
|
||||
}
|
||||
|
||||
// messagingFixture создаёт сервер с владельцем, участником и двумя комнатами:
|
||||
// «общий» (видна всем) и «тайная» (скрыта от роли @user оверрайдом).
|
||||
type messagingFixture struct {
|
||||
srv *Server
|
||||
ownerCookie *http.Cookie
|
||||
memberCookie *http.Cookie
|
||||
guildID string
|
||||
openChannel string
|
||||
secretID string
|
||||
memberID string
|
||||
ownerID string
|
||||
}
|
||||
|
||||
func newMessagingFixture(t *testing.T) *messagingFixture {
|
||||
t.Helper()
|
||||
srv, _ := newTestServer(t)
|
||||
ownerCookie := registerAndLogin(t, srv, "msg_owner", "msg-owner@example.com")
|
||||
memberCookie := registerAndLogin(t, srv, "msg_member", "msg-member@example.com")
|
||||
|
||||
created := doJSON(t, srv, http.MethodPost, "/api/v1/guilds", `{"name":"Чат"}`, ownerCookie)
|
||||
guild := decodeResponse[struct {
|
||||
Guild struct {
|
||||
ID string `json:"id"`
|
||||
Roles []struct {
|
||||
ID string `json:"id"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
} `json:"roles"`
|
||||
Channels []struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"channels"`
|
||||
} `json:"guild"`
|
||||
}](t, created)
|
||||
|
||||
doJSON(t, srv, http.MethodPost, "/api/v1/guilds/"+guild.Guild.ID+"/join", "", memberCookie)
|
||||
|
||||
secretRec := doJSON(t, srv, http.MethodPost, "/api/v1/guilds/"+guild.Guild.ID+"/channels",
|
||||
`{"name":"тайная","type":"text"}`, ownerCookie)
|
||||
secret := decodeResponse[struct {
|
||||
Channel struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"channel"`
|
||||
}](t, secretRec)
|
||||
|
||||
database := srv.store
|
||||
var defaultRoleID uint64
|
||||
for _, role := range guild.Guild.Roles {
|
||||
if role.IsDefault {
|
||||
defaultRoleID = guildIDOf(t, role.ID)
|
||||
}
|
||||
}
|
||||
if err := database.SetChannelOverride(t.Context(), storeOverride(guildIDOf(t, secret.Channel.ID), defaultRoleID)); err != nil {
|
||||
t.Fatalf("SetChannelOverride: %v", err)
|
||||
}
|
||||
srv.perms.InvalidateGuild(guildIDOf(t, guild.Guild.ID))
|
||||
|
||||
owner, err := srv.auth.UserByEmail(t.Context(), "msg-owner@example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("UserByEmail owner: %v", err)
|
||||
}
|
||||
member, err := srv.auth.UserByEmail(t.Context(), "msg-member@example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("UserByEmail member: %v", err)
|
||||
}
|
||||
|
||||
return &messagingFixture{
|
||||
srv: srv,
|
||||
ownerCookie: ownerCookie,
|
||||
memberCookie: memberCookie,
|
||||
guildID: guild.Guild.ID,
|
||||
openChannel: guild.Guild.Channels[0].ID,
|
||||
secretID: secret.Channel.ID,
|
||||
memberID: formatSnowflake(member.ID),
|
||||
ownerID: formatSnowflake(owner.ID),
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageLifecycle(t *testing.T) {
|
||||
f := newMessagingFixture(t)
|
||||
|
||||
// Отправка: содержимое нормализуется, ответ содержит автора и время.
|
||||
sent := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":" привет, мир "}`, f.memberCookie)
|
||||
if sent.Code != http.StatusOK {
|
||||
t.Fatalf("create message = %d, body = %s", sent.Code, sent.Body.String())
|
||||
}
|
||||
message := decodeResponse[struct {
|
||||
Message struct {
|
||||
ID string `json:"id"`
|
||||
Content string `json:"content"`
|
||||
AuthorID string `json:"author_id"`
|
||||
ChannelID string `json:"channel_id"`
|
||||
} `json:"message"`
|
||||
}](t, sent)
|
||||
if message.Message.Content != "привет, мир" {
|
||||
t.Fatalf("content = %q, want trimmed", message.Message.Content)
|
||||
}
|
||||
if message.Message.AuthorID != f.memberID || message.Message.ChannelID != f.openChannel {
|
||||
t.Fatalf("unexpected message: %+v", message.Message)
|
||||
}
|
||||
|
||||
// Пустое сообщение без вложений запрещено.
|
||||
empty := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":" "}`, f.memberCookie)
|
||||
if empty.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("empty message = %d, want 422", empty.Code)
|
||||
}
|
||||
|
||||
// Правка автором.
|
||||
edited := doJSON(t, f.srv, http.MethodPatch,
|
||||
"/api/v1/channels/"+f.openChannel+"/messages/"+message.Message.ID,
|
||||
`{"content":"поправлено"}`, f.memberCookie)
|
||||
if edited.Code != http.StatusOK {
|
||||
t.Fatalf("edit message = %d, body = %s", edited.Code, edited.Body.String())
|
||||
}
|
||||
updated := decodeResponse[struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
EditedAt string `json:"edited_at"`
|
||||
} `json:"message"`
|
||||
}](t, edited)
|
||||
if updated.Message.Content != "поправлено" || updated.Message.EditedAt == "" {
|
||||
t.Fatalf("unexpected edited message: %+v", updated.Message)
|
||||
}
|
||||
|
||||
// История отдаётся от новых к старым.
|
||||
second := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"второе"}`, f.ownerCookie)
|
||||
if second.Code != http.StatusOK {
|
||||
t.Fatalf("second message = %d", second.Code)
|
||||
}
|
||||
history := doJSON(t, f.srv, http.MethodGet, "/api/v1/channels/"+f.openChannel+"/messages", "", f.memberCookie)
|
||||
list := decodeResponse[struct {
|
||||
Messages []struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"messages"`
|
||||
}](t, history)
|
||||
if len(list.Messages) != 2 || list.Messages[0].Content != "второе" {
|
||||
t.Fatalf("history = %+v", list.Messages)
|
||||
}
|
||||
|
||||
// Поиск по FTS5 находит сообщение.
|
||||
search := doJSON(t, f.srv, http.MethodGet,
|
||||
"/api/v1/channels/"+f.openChannel+"/messages/search?q=поправлено", "", f.memberCookie)
|
||||
if search.Code != http.StatusOK {
|
||||
t.Fatalf("search = %d, body = %s", search.Code, search.Body.String())
|
||||
}
|
||||
found := decodeResponse[struct {
|
||||
Messages []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"messages"`
|
||||
}](t, search)
|
||||
if len(found.Messages) != 1 || found.Messages[0].ID != message.Message.ID {
|
||||
t.Fatalf("search results = %+v", found.Messages)
|
||||
}
|
||||
|
||||
// Реакции: поставили, увидели в истории, сняли.
|
||||
addReaction := doJSON(t, f.srv, http.MethodPut,
|
||||
"/api/v1/channels/"+f.openChannel+"/messages/"+message.Message.ID+"/reactions/👍", "", f.ownerCookie)
|
||||
if addReaction.Code != http.StatusOK {
|
||||
t.Fatalf("add reaction = %d, body = %s", addReaction.Code, addReaction.Body.String())
|
||||
}
|
||||
afterReaction := doJSON(t, f.srv, http.MethodGet, "/api/v1/channels/"+f.openChannel+"/messages", "", f.ownerCookie)
|
||||
reactions := decodeResponse[struct {
|
||||
Messages []struct {
|
||||
Reactions []struct {
|
||||
Emoji string `json:"emoji"`
|
||||
Count int `json:"count"`
|
||||
Me bool `json:"me"`
|
||||
} `json:"reactions"`
|
||||
} `json:"messages"`
|
||||
}](t, afterReaction)
|
||||
var foundReaction bool
|
||||
for _, item := range reactions.Messages {
|
||||
for _, reaction := range item.Reactions {
|
||||
if reaction.Emoji == "👍" && reaction.Count == 1 && reaction.Me {
|
||||
foundReaction = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !foundReaction {
|
||||
t.Fatalf("reaction not visible: %+v", reactions.Messages)
|
||||
}
|
||||
removeReaction := doJSON(t, f.srv, http.MethodDelete,
|
||||
"/api/v1/channels/"+f.openChannel+"/messages/"+message.Message.ID+"/reactions/👍", "", f.ownerCookie)
|
||||
if removeReaction.Code != http.StatusOK {
|
||||
t.Fatalf("remove reaction = %d", removeReaction.Code)
|
||||
}
|
||||
|
||||
// Закрепление требует MANAGE_MESSAGES: у участника его нет.
|
||||
deniedPin := doJSON(t, f.srv, http.MethodPut,
|
||||
"/api/v1/channels/"+f.openChannel+"/pins/"+message.Message.ID, "", f.memberCookie)
|
||||
if deniedPin.Code != http.StatusForbidden {
|
||||
t.Fatalf("member pin = %d, want 403", deniedPin.Code)
|
||||
}
|
||||
pin := doJSON(t, f.srv, http.MethodPut,
|
||||
"/api/v1/channels/"+f.openChannel+"/pins/"+message.Message.ID, "", f.ownerCookie)
|
||||
if pin.Code != http.StatusOK {
|
||||
t.Fatalf("owner pin = %d, body = %s", pin.Code, pin.Body.String())
|
||||
}
|
||||
pins := doJSON(t, f.srv, http.MethodGet, "/api/v1/channels/"+f.openChannel+"/pins", "", f.memberCookie)
|
||||
pinned := decodeResponse[struct {
|
||||
Messages []struct {
|
||||
ID string `json:"id"`
|
||||
Pinned bool `json:"pinned"`
|
||||
} `json:"messages"`
|
||||
}](t, pins)
|
||||
if len(pinned.Messages) != 1 || !pinned.Messages[0].Pinned {
|
||||
t.Fatalf("pins = %+v", pinned.Messages)
|
||||
}
|
||||
|
||||
// Удаление: чужое сообщение участник удалить не может, модератор — может.
|
||||
deniedDelete := doJSON(t, f.srv, http.MethodDelete,
|
||||
"/api/v1/channels/"+f.openChannel+"/messages/"+message.Message.ID, "", f.ownerCookie)
|
||||
if deniedDelete.Code != http.StatusOK {
|
||||
t.Fatalf("owner delete = %d, body = %s", deniedDelete.Code, deniedDelete.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesRespectChannelVisibility(t *testing.T) {
|
||||
f := newMessagingFixture(t)
|
||||
|
||||
// Участник не видит скрытую комнату: список и отправка дают 404.
|
||||
list := doJSON(t, f.srv, http.MethodGet, "/api/v1/channels/"+f.secretID+"/messages", "", f.memberCookie)
|
||||
if list.Code != http.StatusNotFound {
|
||||
t.Fatalf("hidden channel list = %d, want 404", list.Code)
|
||||
}
|
||||
send := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.secretID+"/messages",
|
||||
`{"content":"секрет"}`, f.memberCookie)
|
||||
if send.Code != http.StatusNotFound {
|
||||
t.Fatalf("hidden channel send = %d, want 404", send.Code)
|
||||
}
|
||||
|
||||
// Владелец пишет в скрытую комнату и читает её.
|
||||
ownerSend := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.secretID+"/messages",
|
||||
`{"content":"для своих"}`, f.ownerCookie)
|
||||
if ownerSend.Code != http.StatusOK {
|
||||
t.Fatalf("owner send to hidden = %d, body = %s", ownerSend.Code, ownerSend.Body.String())
|
||||
}
|
||||
|
||||
// Администратор инстанса видит всё (AGENT.md 7.19).
|
||||
adminCookie := registerAndLogin(t, f.srv, "msg_admin", "msg-admin@example.com")
|
||||
promoteAdmin(t, f.srv, "msg-admin@example.com")
|
||||
adminList := doJSON(t, f.srv, http.MethodGet, "/api/v1/channels/"+f.secretID+"/messages", "", adminCookie)
|
||||
if adminList.Code != http.StatusOK {
|
||||
t.Fatalf("instance admin list = %d, want 200", adminList.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlowmodeLimitsMessages(t *testing.T) {
|
||||
f := newMessagingFixture(t)
|
||||
|
||||
// Включаем slowmode 60 секунд в комнате.
|
||||
update := doJSON(t, f.srv, http.MethodPatch,
|
||||
"/api/v1/guilds/"+f.guildID+"/channels/"+f.openChannel,
|
||||
`{"slowmode_seconds":60}`, f.ownerCookie)
|
||||
if update.Code != http.StatusOK {
|
||||
t.Fatalf("set slowmode = %d, body = %s", update.Code, update.Body.String())
|
||||
}
|
||||
|
||||
first := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"первое"}`, f.memberCookie)
|
||||
if first.Code != http.StatusOK {
|
||||
t.Fatalf("first message = %d, body = %s", first.Code, first.Body.String())
|
||||
}
|
||||
second := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"второе"}`, f.memberCookie)
|
||||
if second.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("second message = %d, want 429", second.Code)
|
||||
}
|
||||
if code := errorCodeOf(t, second); code != "rate_limited" {
|
||||
t.Fatalf("error code = %q, want rate_limited", code)
|
||||
}
|
||||
|
||||
// Модератор (MANAGE_MESSAGES) и администратор инстанса slowmode обходят.
|
||||
owner := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"модератор пишет"}`, f.ownerCookie)
|
||||
if owner.Code != http.StatusOK {
|
||||
t.Fatalf("owner message with slowmode = %d, body = %s", owner.Code, owner.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMentionsAndReplies(t *testing.T) {
|
||||
f := newMessagingFixture(t)
|
||||
|
||||
parent := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"родитель"}`, f.ownerCookie)
|
||||
parentMessage := decodeResponse[struct {
|
||||
Message struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"message"`
|
||||
}](t, parent)
|
||||
|
||||
reply := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"ответ <@`+f.memberID+`>","reply_to_id":"`+parentMessage.Message.ID+`"}`, f.ownerCookie)
|
||||
if reply.Code != http.StatusOK {
|
||||
t.Fatalf("reply = %d, body = %s", reply.Code, reply.Body.String())
|
||||
}
|
||||
payload := decodeResponse[struct {
|
||||
Message struct {
|
||||
ReplyToID string `json:"reply_to_id"`
|
||||
Mentions []string `json:"mentions"`
|
||||
} `json:"message"`
|
||||
}](t, reply)
|
||||
if payload.Message.ReplyToID != parentMessage.Message.ID {
|
||||
t.Fatalf("reply_to_id = %q", payload.Message.ReplyToID)
|
||||
}
|
||||
if len(payload.Message.Mentions) != 1 || payload.Message.Mentions[0] != f.memberID {
|
||||
t.Fatalf("mentions = %+v, want member", payload.Message.Mentions)
|
||||
}
|
||||
|
||||
// Ответ на сообщение из другой комнаты отклоняется.
|
||||
secretMessage := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.secretID+"/messages",
|
||||
`{"content":"в другой комнате"}`, f.ownerCookie)
|
||||
secretID := decodeResponse[struct {
|
||||
Message struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"message"`
|
||||
}](t, secretMessage)
|
||||
crossReply := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"нельзя","reply_to_id":"`+secretID.Message.ID+`"}`, f.ownerCookie)
|
||||
if crossReply.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("cross-channel reply = %d, want 422", crossReply.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTypingAndReadState(t *testing.T) {
|
||||
f := newMessagingFixture(t)
|
||||
|
||||
typing := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/typing", "", f.memberCookie)
|
||||
if typing.Code != http.StatusOK {
|
||||
t.Fatalf("typing = %d, body = %s", typing.Code, typing.Body.String())
|
||||
}
|
||||
|
||||
sent := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"прочитано"}`, f.ownerCookie)
|
||||
message := decodeResponse[struct {
|
||||
Message struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"message"`
|
||||
}](t, sent)
|
||||
|
||||
ack := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/ack",
|
||||
`{"last_message_id":"`+message.Message.ID+`"}`, f.memberCookie)
|
||||
if ack.Code != http.StatusOK {
|
||||
t.Fatalf("ack = %d, body = %s", ack.Code, ack.Body.String())
|
||||
}
|
||||
states, err := f.srv.store.ListReadStates(t.Context(), guildIDOf(t, f.memberID))
|
||||
if err != nil {
|
||||
t.Fatalf("ListReadStates: %v", err)
|
||||
}
|
||||
if len(states) != 1 || formatSnowflake(states[0].LastMessageID) != message.Message.ID {
|
||||
t.Fatalf("read states = %+v", states)
|
||||
}
|
||||
}
|
||||
@@ -175,6 +175,54 @@ func TestRealtimeEventsReachConnectedClients(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// expectNoEvent проверяет, что за отведённое время событие не пришло.
|
||||
func (c *realtimeClient) expectNoEvent(event string, wait time.Duration) {
|
||||
c.t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), wait)
|
||||
defer cancel()
|
||||
for {
|
||||
_, data, err := c.conn.Read(ctx)
|
||||
if err != nil {
|
||||
// Таймаут — то, что нужно: событие не доставлено.
|
||||
return
|
||||
}
|
||||
var frame realtimeFrame
|
||||
if err := json.Unmarshal(data, &frame); err != nil {
|
||||
c.t.Fatalf("decode frame: %v", err)
|
||||
}
|
||||
if frame.Op == 0 && frame.T == event {
|
||||
c.t.Fatalf("event %s must not reach this client", event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChannelEventsFilteredByPermissions проверяет фильтрацию событий комнат:
|
||||
// сообщения скрытой комнаты не уходят тем, кто её не видит (AGENT.md 8.3, 9.7).
|
||||
func TestChannelEventsFilteredByPermissions(t *testing.T) {
|
||||
f := newMessagingFixture(t)
|
||||
httpServer := httptest.NewServer(f.srv.Handler())
|
||||
t.Cleanup(httpServer.Close)
|
||||
|
||||
owner := dialGateway(t, httpServer, f.ownerCookie)
|
||||
member := dialGateway(t, httpServer, f.memberCookie)
|
||||
|
||||
// Открытая комната: событие получают оба.
|
||||
if rec := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.openChannel+"/messages",
|
||||
`{"content":"всем"}`, f.ownerCookie); rec.Code != http.StatusOK {
|
||||
t.Fatalf("open channel message = %d, body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
owner.expectEvent("MESSAGE_CREATE")
|
||||
member.expectEvent("MESSAGE_CREATE")
|
||||
|
||||
// Скрытая комната: владелец получает событие, участник — нет.
|
||||
if rec := doJSON(t, f.srv, http.MethodPost, "/api/v1/channels/"+f.secretID+"/messages",
|
||||
`{"content":"только для владельца"}`, f.ownerCookie); rec.Code != http.StatusOK {
|
||||
t.Fatalf("secret channel message = %d, body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
owner.expectEvent("MESSAGE_CREATE")
|
||||
member.expectNoEvent("MESSAGE_CREATE", 700*time.Millisecond)
|
||||
}
|
||||
|
||||
// TestInstanceAdminManagesForeignGuild проверяет §11.5: администратор инстанса,
|
||||
// не состоящий в сервере, видит и меняет всё, а его самого модерировать нельзя.
|
||||
func TestInstanceAdminManagesForeignGuild(t *testing.T) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
@@ -46,10 +47,18 @@ type Server struct {
|
||||
// (AGENT.md 8.6).
|
||||
authLimiter *httpx.RateLimiter
|
||||
apiLimiter *httpx.RateLimiter
|
||||
logger *slog.Logger
|
||||
http *http.Server
|
||||
static *staticHandler
|
||||
api huma.API
|
||||
// Лимиты Фазы 2 (AGENT.md 8.6): сообщения, typing и поиск.
|
||||
messageLimiter *httpx.RateLimiter
|
||||
typingLimiter *httpx.RateLimiter
|
||||
searchLimiter *httpx.RateLimiter
|
||||
// slowmode — время последней отправки в комнату для режима медленной
|
||||
// отправки; словарь ограничен по размеру (AGENT.md 7.5).
|
||||
slowmodeMu sync.Mutex
|
||||
slowmode map[string]time.Time
|
||||
logger *slog.Logger
|
||||
http *http.Server
|
||||
static *staticHandler
|
||||
api huma.API
|
||||
}
|
||||
|
||||
func New(cfg config.Config, db *database.DB, logger *slog.Logger, deps Deps) *Server {
|
||||
@@ -65,6 +74,11 @@ func New(cfg config.Config, db *database.DB, logger *slog.Logger, deps Deps) *Se
|
||||
// пользователя/IP — дефолты AGENT.md 8.6.
|
||||
authLimiter: httpx.NewRateLimiter(5, 5),
|
||||
apiLimiter: httpx.NewRateLimiter(120, 60),
|
||||
// 5 сообщений за 5 секунд (burst 10), typing 1/3 c, поиск 10/мин.
|
||||
messageLimiter: httpx.NewRateLimiter(60, 10),
|
||||
typingLimiter: httpx.NewRateLimiter(20, 1),
|
||||
searchLimiter: httpx.NewRateLimiter(10, 10),
|
||||
slowmode: map[string]time.Time{},
|
||||
}
|
||||
switch {
|
||||
case deps.Permissions != nil:
|
||||
@@ -85,6 +99,7 @@ func New(cfg config.Config, db *database.DB, logger *slog.Logger, deps Deps) *Se
|
||||
s.registerUserRoutes(s.api)
|
||||
s.registerGuildRoutes(s.api)
|
||||
s.registerInstanceRoutes(s.api)
|
||||
s.registerMessageRoutes(s.api)
|
||||
}
|
||||
apiRouter.Get("/openapi.json", s.handleOpenAPI)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user