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
+50 -143
View File
@@ -2,161 +2,68 @@
icon: wifi
---
# ChatHub
# ChatsHub — сообщения
**Route**: `hubs/chats`\
**Authorize**: Requires authentication (user must be logged in)
Подключение: /hubs/chats, Bearer access token. Серверный класс называется ChatsHub. Команды возвращают HubResult, события приходят независимо от ответа команды.
***
## Команды
### Hub Methods
| Имя | Запрос | Успешный Result |
| ------ | ---------------------------------- | ---------------------- |
| Send | MessageRequest | UserMessageResponse |
| Read | { messageId } | MessageReadResponse |
| Edit | { messageId, newEncryptedContent } | MessageEditResponse |
| Remove | { messageId, requestType } | MessageRemovedResponse |
#### <mark style="color:$primary;">OnConnectedAsync</mark>
**Description**: Automatically invoked when a client establishes a connection to the hub. Adds the user to their personal group for private messages and notifications.
**Behavior**:
* Retrieves the user's ID from the connection context.
* If the user ID is invalid (`Guid.Empty`), logs a warning and aborts the connection.
* Adds the user to a group named after their user ID (e.g., `userId.ToString()`).
* Logs the connection event with the user ID and connection ID.
**Notes**:
* Future enhancements may include adding the user to their chat groups (currently a TODO in the code).
***
#### <mark style="color:$primary;">OnDisconnectedAsync</mark>
**Description**: Automatically invoked when a client disconnects from the hub. Removes the user from their personal group.
**Behavior**:
* Retrieves the user's ID from the connection context, suppressing exceptions if the ID is unavailable (e.g., due to an early abort).
* If the user ID is valid, removes the user from their personal group.
* Logs the disconnection event with the user ID and connection ID.
* If an exception occurs, logs it as a warning along with the connection ID.
* If no exception occurs but the user ID is invalid, logs the disconnection with the connection ID.
**Notes**:
* Future enhancements may include removing the user from their chat groups (currently a TODO in the code).
***
#### <mark style="color:$info;">Send</mark>
**Description**: Allows a client to send a message to a recipient, which can be either a user or a group.
**Request**:
* **Method Name**: `Send`
* **Parameters**:
* `request`: An object of type `MessageRequest` with the following structure:
```json
{
"encryptedContent": "string",
"replyToMessageId": "Guid",
"recipientId": "Guid",
"recipientType": "string", // "User" or "Group"
"mediaAttachments": [
{
"mediaId": "Guid",
"encryptedKey": "string",
"type": "string",
"mimeType": "string"
}
]
}
```
**Responses**:
* <mark style="color:$success;">**Success**</mark>:
* Sends the message to the recipient (user or group) via the `ReceiveMessage` event.
* Notifies the sender with a confirmation via the `MessageSent` event.
* Logs the successful message send with the message ID, sender ID, recipient ID, and recipient type.
* <mark style="color:$danger;">**Error**</mark>:
* If the message is empty (no `encryptedContent` and no `mediaAttachments`), logs a warning and throws an `ArgumentException`.
* If the message fails to send (e.g., due to an internal error), logs the error and throws a `HubException`.
**Client-Side Events**:
* <mark style="color:$primary;">**ReceiveMessage**</mark>: Triggered on the recipient's client(s) to deliver the message.
* Payload: `UserMessageResponse` object.
* <mark style="color:$primary;">**MessageSent**</mark>: Triggered on the sender's client to confirm the message was sent.
* Payload: `UserMessageResponse` object.
**Notes**:
* The message must contain either `encryptedContent` or `mediaAttachments`; otherwise, it is invalid.
* The recipient is determined by `recipientType`:
* `"User"`: Sends to the recipient’s personal group (e.g., `recipientId.ToString()`).
* `"Group"`: Sends to all members of the group (e.g., `group_{recipientId}`).
***
### Data Models
#### MessageRequest
MessageRequest:
```json
{
"encryptedContent": "string",
"replyToMessageId": "Guid",
"recipientId": "Guid",
"recipientType": "string", // "User" or "Group"
"mediaAttachments": [
{
"mediaId": "Guid",
"encryptedKey": "string",
"type": "string",
"mimeType": "string"
}
]
"recipientId":"11111111-1111-1111-1111-111111111111",
"recipientType":0,
"encryptedContent":"<содержимое>",
"replyToMessageId":null,
"mediaAttachments":[]
}
```
#### UserMessageResponse
RecipientType.User=0 означает **личный чат**, recipientId — PrivateChat.Id. Group=1 означает ChatGroup.Id. Вложение: { mediaId, encryptedKey }.
```json
{
"messageId": "Guid",
"senderId": "Guid",
"recipientId": "Guid",
"recipientType": "string",
"encryptedContent": "string",
"sentAt": "DateTime",
"isEdited": "bool",
"mediaAttachments": [
{
"mediaId": "Guid",
"encryptedKey": "string",
"type": "string",
"mimeType": "string"
}
],
"replyToMessageId": "Guid"
}
```
Содержимое или вложение обязательно. Хаб ограничивает текст 50 000 символами, хотя атрибут DTO указывает 100 000. SignalR не выполняет MVC DataAnnotations автоматически; транспортный лимит входящего сообщения отдельно ограничивает размер JSON. При null encryptedContent с вложением возможна ошибка на Length.
## События
| Имя события (точно) | Payload |
| ------------------- | ---------------------- |
| ReceiveMessage | UserMessageResponse |
| MessageEdited | MessageEditResponse |
| MessageRemoved | MessageRemovedResponse |
| MessageReaded | MessageReadResponse |
Опечатка MessageReaded является текущим именем wire-контракта. Константа MessageSent есть, но отправка этого события закомментирована; не ожидайте его.
UserMessageResponse: messageId, senderId, recipientId, recipientType, encryptedContent, replyToMessageId, sentAt, isEdited, mediaAttachments. mediaAttachments — список MediaFile, не HTTP MediaAttachmentResponse; навигация MediaFile после Send явно не загружается и элементы могут быть null.
MessageEditResponse: messageId, editorId, recipientId, recipientType, newEncryptedContent, editedAt. MessageReadResponse: viewId, messageId, readerId, recipientId, whenWas, recipientType. MessageRemovedResponse: messageId, senderId, recipientId, requestType, recipientType.
## Семантика и ошибки
Edit проверяет автора и срок из MessageEditingOptions (по умолчанию 15 минут при Enabled=true), но не применяет лимит текста Send. Многие сервисные ошибки хаб превращает в InvalidOperationException и возвращает status=500, теряя исходный код.
RemoveMessageRequestType: HideForMe=0, ForceRemove=1. **HideForMe сейчас не реализован**: если автор вызывает Remove, сервис физически удаляет сообщение независимо от флага. Групповое удаление сравнивает DeleterId с ID группы вместо автора/прав администратора.
Read проверяет наличие у пользователя любого личного чата вместо участия в чате сообщения. Для групп прочтение не реализовано; хаб может упасть на First при отсутствии MessageView. Параллельные Read могут конфликтовать по уникальному индексу (MessageId, UserId).
Уведомления Edit/Remove/Read в личных чатах отправляются инициатору и группе с именем ID чата, хотя второй адресат должен быть участником. Поэтому собеседник может не получить событие.
Send для личного чата проверяет только его существование, не участие отправителя. Исправление доступа обязательно.
## Доставка
Успех сохранения и доставка события — разные этапы. После reconnect загрузите историю через HTTP, объединяйте ответ Send и ReceiveMessage по messageId. Без clientMessageId/idempotency-key повтор Send после сбоя может создать дубль.
***
### Error Handling
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
* **Invalid User ID**: If the user ID is `Guid.Empty` during connection, the connection is aborted with a logged warning.
* **Empty Message**: If a message lacks both content and attachments, an `ArgumentException` is thrown with a logged warning.
* **Message Send Failure**: If sending fails (e.g., due to a service error), a `HubException` is thrown with the error logged.
***
### Logging
* Logs connection events with user ID and connection ID.
* Logs disconnection events, including exceptions if present.
* Logs message send attempts, successes, and failures for monitoring and debugging.
***
Источник: [Govor.API/Hubs/ChatsHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/ChatsHub.cs).
+51
View File
@@ -0,0 +1,51 @@
---
description: >-
Description: SignalR hub for managing real-time friend request operations,
including sending, accepting, and rejecting friend requests.
icon: wifi
---
# FriendsHub — заявки
Подключение: /hubs/friends с access token, содержащим userId. Атрибут Authorize у класса отсутствует; HubUserAccessor читает claim и бросает исключение при его отсутствии. Это не следует считать полноценной endpoint-политикой авторизации: её нужно добавить явно.
## Команды
| Команда | Аргумент | Успех |
| ------------- | ----------------- | ----------------------- |
| SendRequest | Guid targetUserId | status 201, result null |
| AcceptRequest | Guid friendshipId | status 200, result null |
| RejectRequest | Guid friendshipId | status 200, result null |
SendRequest запрещает заявку себе и повтор при Pending/Accepted/Blocked. После Rejected запись переиспользуется. Accept разрешён только адресату и только Pending; после сохранения дружбы создаётся личный чат. Reject разрешён адресату для Pending/Rejected.
## Все события
| Событие | Кому |
| ------------------------- | --------------------------- |
| FriendRequestReceived | Адресату новой заявки |
| YourFriendRequestReceived | Отправителю |
| FriendRequestAccepted | Принимающему адресату |
| YourFriendRequestAccepted | Отправителю исходной заявки |
| FriendRequestRejected | Отклоняющему адресату |
| YourFriendRequestRejected | Отправителю исходной заявки |
Каждое событие передаёт **FriendshipDto**, не строку Guid:
```json
{"id":"11111111-1111-1111-1111-111111111111","requesterId":"22222222-2222-2222-2222-222222222222","addresseeId":"33333333-3333-3333-3333-333333333333","status":0}
```
Status: Pending=0, Accepted=1, Rejected=2, Blocked=3.
## Ошибки и восстановление
Сервисные Failure в SendRequest преобразуются в status 500; Accept/Reject — в 400. Поэтому не обещайте 409/403/404 для всех соответствующих бизнес-ошибок.
Дружба сохраняется до создания чата/рассылки; сбой может оставить частично завершённый сценарий. На reconnect перечитывайте /api/friends, /requests, /responses и /api/user/private-chats. Клиенту нужны дедупликация и обновление cache по id.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
Источник: [Govor.API/Hubs/FriendsHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/FriendsHub.cs).
@@ -0,0 +1,67 @@
---
description: >-
Description: This sub-documentation provides example Java client code for
interacting with the FriendsHub SignalR hub using the microsoft/signalr
library. It covers connecting to the hub, handling con
icon: java
---
# Клиент SignalR на C# для MAUI
Эта страница заменяет устаревший Java-пример: он принимал FriendshipDto как String и не соответствовал серверу. Ниже минимальный пример подключения C#; это пример интеграции, а не проверенный end-to-end тест.
Используйте Microsoft.AspNetCore.SignalR.Client и Govor.Contracts либо эквивалентные DTO с теми же полями.
```csharp
using Govor.Contracts.DTOs;
using Govor.Contracts.Responses.SignalR;
using Microsoft.AspNetCore.SignalR.Client;
var connection = new HubConnectionBuilder()
.WithUrl($"{baseUrl.TrimEnd('/')}/hubs/friends", options =>
{
options.AccessTokenProvider = async () =>
await jwtProvider.GetAccessTokenAsync();
})
.WithAutomaticReconnect()
.Build();
using var received = connection.On<FriendshipDto>(
"FriendRequestReceived", dto =>
{
MainThread.BeginInvokeOnMainThread(() => ApplyFriendship(dto));
});
using var accepted = connection.On<FriendshipDto>(
"YourFriendRequestAccepted", dto =>
{
MainThread.BeginInvokeOnMainThread(() => ApplyFriendship(dto));
});
await connection.StartAsync();
var response = await connection.InvokeAsync<HubResult<object>>(
"SendRequest", targetUserId);
if (response.Status != HubResultStatus.Created)
ShowError(response.ErrorMessage);
```
baseUrl, jwtProvider, ApplyFriendship, ShowError и targetUserId предоставляет приложение. Зарегистрируйте остальные четыре события аналогично с FriendshipDto. AcceptRequest/RejectRequest получают friendshipId.
## Жизненный цикл MAUI
1. Подпишитесь на события до подключения.
2. Первоначальный StartAsync требует собственной обработки повторов; automatic reconnect относится к потерянному соединению.
3. После Reconnected перечитайте HTTP-списки, чтобы восстановить пропущенные события.
4. Изменяйте ObservableCollection на MainThread.
5. Отменяйте повторные попытки при logout и DisposeAsync; не запускайте бесконечный StartAsync из Closed после намеренного StopAsync.
6. AccessTokenProvider должен получать актуальный access token; refresh должен быть сериализован.
В текущем Govor.Mobile ChatHub фильтрует ReceiveMessage по непустому encryptedContent, поэтому сообщение только с вложением может игнорироваться. Closed пытается перезапуститься даже после намеренного DisconnectAsync. JwtProviderService очищает токены при любом неуспешном HTTP-refresh, включая временную ошибку сервера: это следует исправить отдельно.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
Источник: [Govor.API/Hubs/FriendsHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/FriendsHub.cs).
+16 -36
View File
@@ -3,51 +3,31 @@ description: SignalR hub for managing user online presence and notifications.
icon: wifi
---
# PresenceHub
# PresenceHub — online и offline
### Controller Description
Подключение: /hubs/presence. Требуется роль User/Admin.
* **Route**: `hubs/presence`
* **Authorize**: Requires authenticated user with roles "Admin" or "User" (`[Authorize(Roles = "Admin, User")]`).
Публичных команд у хаба нет. На подключении сервер добавляет connectionId в OnlineUserStore и группу userId. Первая связь пользователя вызывает событие UserOnline; отключение последней — UserOffline.
### Hub Methods
| Событие | Payload |
| ----------- | ----------------- |
| UserOnline | Guid пользователя |
| UserOffline | Guid пользователя |
#### <mark style="color:$info;">OnConnectedAsync</mark>
Получатели определяются IUserNotificationScopeService. Несколько соединений одного пользователя учитываются отдельно.
* **Description**: Invoked when a client connects, updates online status and notifies friends.
* **Behavior**:
* Retrieves user ID from context.
* Aborts connection if user ID is `Guid.Empty` or user does not exist.
* Adds user to online store and their personal group.
* Notifies friends of user going online via `UserOnline` event.
* **Client-Side Events**:
* **UserOnline**: Triggered for friends with payload `userId` (Guid).
* **Responses**: None (connection aborted on invalid user ID).
## Ограничения
#### <mark style="color:$info;">OnDisconnectedAsync</mark>
OnlineUserStore хранится в памяти одного процесса. Перезапуск теряет состояние; несколько серверов не согласованы. Online означает наличие соединения этого хаба, не доступность устройства для push.
* **Description**: Invoked when a client disconnects, updates offline status and notifies friends.
* **Behavior**:
* Retrieves user ID from context, suppressing exceptions.
* Removes user from personal group if ID is valid.
* Updates user's `WasOnline` timestamp.
* Sets user as offline in store.
* Notifies friends of user going offline via `UserOffline` event.
* **Client-Side Events**:
* **UserOffline**: Triggered for friends with payload `userId` (Guid).
* **Responses**: None.
PresenceHub не сохраняет lastSeen в БД при отключении. Для него есть отдельный HTTP ping; нужна единая политика обновления lastSeen.
### Data Models
Для первоначального экрана получайте доступные данные профиля/друзей; события только изменяют локальный cache. После reconnect перечитайте состояние. HTTP /api/online/status сейчас сломан из-за отсутствующих зависимостей.
* **N/A**: No specific data models defined for hub methods.
Обработчики должны быть зарегистрированы до StartAsync. Не используйте события присутствия как гарантированный журнал активности.
### Error Handling
***
* **Invalid User ID**: Aborts connection with logged warning if `Guid.Empty` or user not found.
* **Unexpected Errors**: Logged, but no specific response (handled by base method).
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
### Logging
* Logs warnings for invalid user ID on connection.
* Logs information for disconnections with user ID and connection ID.
* Logs errors for unexpected exceptions during disconnection.
Источник: [Govor.API/Hubs/PresenceHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/PresenceHub.cs).
+29
View File
@@ -0,0 +1,29 @@
# ProfileHub — изменения профиля
Подключение: /hubs/profiles; требуется Authorize.
| Метод | Аргумент | Успех |
| -------------- | ------------------ | ---------------------------------- |
| SetDescription | string description | HubResult, status=200, result=true |
| SetAvatar | Guid iconId | HubResult, status=200, result=true |
Описание не может быть null, переносы строк нормализуются, длина после нормализации ≤500; пустая строка допустима для очистки. Avatar требует непустой Guid и существующую запись медиа.
| Событие | Payload |
| ------------------ | ----------------------- |
| DescriptionUpdated | { userId, description } |
| AvatarUpdated | { userId, iconId } |
Получатели: пользователь, друзья и потенциальные друзья согласно IFriendshipService. Группы имеют префикс user:.
## Ограничения
Result от записи профиля не проверяется хабом, поэтому true не всегда подтверждает запись. Ошибка рассылки логируется, но не меняет успешный ответ.
SetAvatar не проверяет владельца файла. REST UploadAvatar не отправляет AvatarUpdated. Политика приватности не применяется к этой рассылке. После reconnect перечитайте профиль; события не гарантированно сохраняются.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
Источник: [Govor.API/Hubs/ProfileHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/ProfileHub.cs).