GITBOOK-14: Govor.API: документация по текущему коду и диагностика 03.10.2026

This commit is contained in:
stalcke2288969
2026-10-03 06:20:45 +00:00
committed by gitbook-bot
parent 4603be9f71
commit 6c8abb23e3
27 changed files with 827 additions and 1901 deletions
+32 -242
View File
@@ -2,258 +2,48 @@
description: Controller for loading chat messages for users and groups with pagination.
---
# ChatLoadController
# История сообщений
### Controller Description
Требуется роль User/Admin.
* **Route**: `api/chats`
* **Authorize**: Requires authenticated user with roles "Admin" or "User" (`[Authorize(Roles = "Admin, User")]`).
| Метод | Маршрут | Идентификатор |
| ----- | ------------------------------ | -------------------------------------- |
| GET | /api/user/{userId}/messages | В userId передаётся **ID PrivateChat** |
| GET | /api/groups/{groupId}/messages | ID ChatGroup |
### Endpoints
Query: StartMessageId (Guid?, необязателен), Before=20, After=2. Before и After неотрицательные, сумма ≤100.
#### <mark style="color:$info;">GetGroupMessages</mark>
Без StartMessageId возвращаются последние Before сообщений, упорядоченные по SentAt по возрастанию; After не используется. С якорем возвращаются Before старых, якорное сообщение и After новых: максимум 101 запись. Неизвестный якорь — \[].
* **Description**: Retrieves messages from a specified group chat with pagination.
* **Route**: `[GET] api/chats/group-messages`
* **HTTP Method**: `GET`
* **Request**:
* **Path Parameter**: `chatId` (Guid, required): ID of the group chat.
* **Query Parameter**: `query` (`MessageQuery`, required) with:
* `startMessageId` (Guid?, optional): ID of the starting message.
* `before` (int, default=20): Number of messages before the start.
* `after` (int, default=2): Number of messages after the start.
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns a list of group chat messages.
Успех 200, MessageResponse\[]:
```json
[
{
"id": "Guid",
"senderId": "Guid",
"recipientId": "Guid",
"recipientType": "string",
"encryptedContent": "string",
"sentAt": "DateTime",
"isEdited": "boolean",
"editedAt": "DateTime?",
"replyToMessageId": "Guid?",
"mediaAttachments": [
{
"id": "Guid",
"messageId": "Guid",
"mediaFileId": "Guid"
}
],
"reactions": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"reactionCode": "string",
"reactedAt": "DateTime"
}
],
"messageViews": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"viewedAt": "DateTime"
}
]
}
]
```
* <mark style="color:$danger;">**400 Bad Request**</mark>:
* If `before` or `after` is negative or total exceeds 100: `"Values must be non-negative and total must not exceed 100."`
* If an argument or resource is invalid: `"string"`
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
[{
"id":"11111111-1111-1111-1111-111111111111",
"senderId":"22222222-2222-2222-2222-222222222222",
"recipientId":"33333333-3333-3333-3333-333333333333",
"recipientType":0,
"encryptedContent":"<строка>",
"sentAt":"2026-10-03T00:00:00Z",
"isEdited":false,
"editedAt":null,
"replyToMessageId":null,
"mediaAttachments":[],
"reactions":[],
"messageViews":[]
}]
```
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
У HTTP-ответа поле id; у SignalR UserMessageResponse — messageId. Вложения HTTP имеют id, messageId, mediaFileId.
```json
"Unexpected Error! Please try again later."
```
## Известные проблемы
#### <mark style="color:$info;">GetUserMessages</mark>
Личный загрузчик принимает currentUser, но не проверяет участие в указанном чате. Это критичная ошибка доступа. Для группы участие проверяется; неучастнику возвращается \[].
* **Description**: Retrieves messages from a specified user chat with pagination.
* **Route**: `[GET] api/chats/user-messages`
* **HTTP Method**: `GET`
* **Request**:
* **Path Parameter**: `userId` (Guid, required): ID of the target user.
* **Query Parameter**: `query` (`MessageQuery`, required) with:
* `startMessageId` (Guid?, optional): ID of the starting message.
* `before` (int, default=20): Number of messages before the start.
* `after` (int, default=2): Number of messages after the start.
* **Responses**:
* **200 OK**: Returns a list of user chat messages.
Пагинация сравнивает только SentAt: сообщения с одинаковой датой могут выпадать вокруг якоря. Reactions и MessageViews не включаются явным Include, поэтому эти массивы не являются надёжным источником состояния. Нужны проверки доступа и стабильный курсор (SentAt, Id).
```json
[
{
"id": "Guid",
"senderId": "Guid",
"recipientId": "Guid",
"recipientType": "string",
"encryptedContent": "string",
"sentAt": "DateTime",
"isEdited": "boolean",
"editedAt": "DateTime?",
"replyToMessageId": "Guid?",
"mediaAttachments": [
{
"id": "Guid",
"messageId": "Guid",
"mediaFileId": "Guid"
}
],
"reactions": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"reactionCode": "string",
"reactedAt": "DateTime"
}
],
"messageViews": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"viewedAt": "DateTime"
}
]
}
]
```
* **400 Bad Request**:
* If `before` or `after` is negative or total exceeds 100: `"Values must be non-negative and total must not exceed 100."`
* If an operation or resource is invalid: `"string"`
* **403 Forbidden**: If user lacks authorization.
***
```json
"string"
```
* **500 Internal Server Error**: Indicates an unexpected error.
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
"Unexpected Error! Please try again later."
```
### Data Models
#### MessageQuery
* **Description**: Model for pagination query parameters.
* **Structure**:
```json
{
"startMessageId": "Guid?",
"before": "int",
"after": "int"
}
```
#### MessageResponse
* **Description**: Data transfer object for chat message details.
* **Structure**:
```json
{
"id": "Guid",
"senderId": "Guid",
"recipientId": "Guid",
"recipientType": "string",
"encryptedContent": "string",
"sentAt": "DateTime",
"isEdited": "boolean",
"editedAt": "DateTime?",
"replyToMessageId": "Guid?",
"mediaAttachments": [
{
"id": "Guid",
"messageId": "Guid",
"mediaFileId": "Guid"
}
],
"reactions": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"reactionCode": "string",
"reactedAt": "DateTime"
}
],
"messageViews": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"viewedAt": "DateTime"
}
]
}
```
#### MediaAttachmentResponse
* **Description**: Data transfer object for media attachments in messages.
* **Structure**:
```json
{
"id": "Guid",
"messageId": "Guid",
"mediaFileId": "Guid"
}
```
#### MessageReactionResponse
* **Description**: Data transfer object for message reactions.
* **Structure**:
```json
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"reactionCode": "string",
"reactedAt": "DateTime"
}
```
#### MessageViewResponse
* **Description**: Data transfer object for message view tracking.
* **Structure**:
```json
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"viewedAt": "DateTime"
}
```
### Error Handling
* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid.
* **Invalid Operations**: Returns `400 Bad Request` for negative values, total exceeding 100, or `InvalidOperationException`.
* **Unauthorized Access**: Returns `403 Forbidden` for `UnauthorizedAccessException`.
* **Resource Not Found**: Returns `400 Bad Request` for `NotFoundException`.
* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`.
### Logging
* Logs warnings for `UnauthorizedAccessException`, `NotFoundException`, `ArgumentException`, and `InvalidOperationException`.
* Logs errors for unexpected exceptions.
Источник: [Govor.Application/Messages/MessagesLoader.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Application/Messages/MessagesLoader.cs).