Add reactions, reliable push & session checks

Implements message reactions and reaction packs (domain models, services, admin HTTP API, media processing via ImageSharp and limits) and adds reliable push delivery (ChatPushNotification, ChatPushDispatcher, ChatPushWorker, improved ChatNotificationService). Enhances message reading (ReadChat API, unread counts, concurrency-safe receipts) and tightens session security (access-token session validation in JWT, hub filter, SessionAuthorization). Improves SignalR behavior (session groups, reaction/channel events, hub/error mappings). Adds EF migrations, many controller fixes (Forbid handling, password API), tests (Govor.Server.Tests), docs, CI and tooling updates (Dockerfile → .NET 10, GH Actions matrix for sqlite/postgres, Govor.Server.slnx, global.json), and small infra changes (AutoMapper bump, NullPushProvider, storage/token handling).
This commit is contained in:
Artemy
2026-10-03 17:42:24 +07:00
parent 4603be9f71
commit 29cc51ee0c
127 changed files with 7290 additions and 2488 deletions
+40 -105
View File
@@ -1,107 +1,42 @@
# Медиа
Требуется роль User/Admin.
## POST /api/media/upload
Content-Type: multipart/form-data. Поля:
| Поле | Тип | Назначение |
| --- | --- | --- |
| FromFile | файл | Непустое содержимое |
| Type | число | Image=0, Video=1, Audio=2, File=3, Voice=4 |
| MimeType | строка ≤255 | MIME типа файла |
| EncryptedKey | строка | Обязательное поле запроса; сохранение ключа не реализовано |
| OwnerType | число | Message=0, Avatar=1, GroupAvatar=2, System=3 |
Ограничение запроса — 20 000 000 байт, включая multipart; проверка файла также ≤20 000 000. Не следует обещать загрузку файла ровно этого размера: overhead тоже входит в лимит.
Успех 200:
```json
{"mediaId":"11111111-1111-1111-1111-111111111111","url":"2026/10/<имя файла>"}
```
url — относительный путь хранилища, не публичный URL. Для скачивания используйте endpoint.
## GET /api/media/download/{id}
Проверяет HasAccessAsync, затем возвращает бинарный файл с MIME и Content-Disposition. Если доступа нет или запись не найдена — 403, потому что проверка доступа выполняется первой. Сервисные ошибки — через ResultExtensions.
## Ограничения
Для личного сообщения accesser сравнивает Message.RecipientId с userId, хотя там ID чата: получатель может получить 403. При Send принадлежность вложения загрузившему пользователю не проверяется. OwnerType задаёт клиент, включая публично доступный System, — нужна серверная политика владения.
EncryptedKey не хранится ни в MediaFile, ни в MediaAttachments. Нельзя обещать восстановление ключа из истории.
Файлы целиком буферизуются в памяти, MIME принимается от клиента. Запись файла и БД не атомарна: возможны файлы без записи. Очистка неиспользуемых загрузок и stream-based выдача требуют реализации.
---
description: Controller for uploading and downloading media files.
---
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
# MediaController
### Controller Description
* **Route**: `api/media`
* **Authorize**: Requires authenticated user with roles "User" or "Admin" (`[Authorize(Roles = "User,Admin")]`).
### Endpoints
#### <mark style="color:$info;">Upload</mark>
* **Description**: Uploads a media file with associated metadata.
* **Route**: `[POST] api/media/upload`
* **HTTP Method**: `POST`
* **Request**:
* **Content-Type**: `multipart/form-data`
* **Request Body**: `MediaUploadRequest` object with the following structure:
```json
{
"fromFile": "IFormFile",
"type": "MediaType",
"mimeType": "string",
"encryptedKey": "string"
}
```
* **Constraints**: File size limit of 20 MB.
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns the upload result.
```json
"string" // Media ID or similar result
```
* <mark style="color:$danger;">**400 Bad Request**</mark>:
* If model validation fails.
* If no file is uploaded: `"No file uploaded"`
* If file exceeds 20 MB: `"File is too large"`
* If MIME type is missing: `"Missing MIME type"`
* If operation is invalid: `"string"`
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
```json
"Internal server error"
```
#### <mark style="color:$info;">Download</mark>
* **Description**: Downloads a media file by its ID.
* **Route**: `[GET] api/media/download/{id}`
* **HTTP Method**: `GET`
* **Request**:
* **Path Parameter**: `id` (Guid, required): ID of the media file.
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns the media file as a stream.
* **Content-Type**: Matches `MimeType` of the media.
* **Content-Disposition**: Includes `filename` from `FileName`.
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks access.
* No body.
* <mark style="color:$danger;">**404 Not Found**</mark>: If media is not found.
```json
"Media not found"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
```json
"Internal server error"
```
### Data Models
#### MediaUploadRequest
* **Description**: Model for media upload request data.
* **Structure**:
```json
{
"fromFile": "IFormFile",
"type": "MediaType",
"mimeType": "string",
"encryptedKey": "string"
}
```
### Error Handling
* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid.
* **Invalid Operations**: Returns `400 Bad Request` for `InvalidOperationException`.
* **Unauthorized Access**: Returns `403 Forbidden` for `UnauthorizedAccessException`.
* **Resource Not Found**: Returns `404 Not Found` for `KeyNotFoundException`.
* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`.
### Logging
* Logs warnings for `UnauthorizedAccessException`, `InvalidOperationException`, and `KeyNotFoundException`.
* Logs information for successful file uploads.
* Logs errors for unexpected exceptions during upload and download.
Источник: [Govor.API/Controllers/MediaController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/MediaController.cs).