import { Body, Controller, HttpCode, Header, Param, Post, Req, UseGuards, } from '@nestjs/common'; import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags, } from '@nestjs/swagger'; import { UserGuard, type AuthenticatedRequest } from '../User/user.guard'; import { DirectUploadService } from './direct-upload.service'; @ApiTags('direct uploads') @ApiBearerAuth('bearerAuth') @UseGuards(UserGuard) @Controller('api/v1/chats/:chat_id/attachment-uploads') @ApiParam({ name: 'chat_id', type: 'string', format: 'uuid', required: true }) @ApiResponse({ status: 401, description: 'Требуется Bearer-сессия', schema: { $ref: '#/components/schemas/Error' }, }) @ApiResponse({ status: 404, description: 'Чат/разрешение недоступно пользователю', schema: { $ref: '#/components/schemas/Error' }, }) @ApiResponse({ status: 503, description: 'БД или хранилище временно недоступно', schema: { $ref: '#/components/schemas/Error' }, }) export class DirectUploadController { constructor(private readonly uploads: DirectUploadService) {} @Post() @HttpCode(201) @Header('Cache-Control', 'no-store') @ApiOperation({ operationId: 'initiateDirectUpload', summary: 'Выдать короткоживущее разрешение PUT в staging', }) @ApiBody({ schema: { type: 'object', additionalProperties: false, required: ['filename', 'content_type', 'size_bytes', 'sha256'], properties: { filename: { type: 'string', minLength: 1, maxLength: 255 }, content_type: { type: 'string', enum: ['image/png', 'image/jpeg'] }, size_bytes: { type: 'integer', minimum: 1, maximum: 10485760 }, sha256: { type: 'string', pattern: '^[a-f0-9]{64}$' }, expires_in: { type: 'integer', minimum: 1, maximum: 300, description: 'Не больше серверного DIRECT_UPLOAD_TTL_SECONDS (60 по умолчанию)', }, }, }, }) @ApiResponse({ status: 201, description: 'PUT URL и обязательные заголовки; URL не логировать', schema: { type: 'object', required: [ 'upload_id', 'expires_at', 'method', 'url', 'headers', 'complete_url', ], properties: { upload_id: { type: 'string', format: 'uuid' }, expires_at: { type: 'string', format: 'date-time' }, method: { type: 'string', enum: ['PUT'] }, url: { type: 'string', format: 'uri' }, headers: { type: 'object', additionalProperties: { type: 'string' } }, complete_url: { type: 'string' }, }, }, }) @ApiResponse({ status: 400, description: 'Некорректные поля разрешения' }) @ApiResponse({ status: 413, description: 'Запрошен размер больше 10 MiB' }) @ApiResponse({ status: 415, description: 'Разрешены только PNG и JPEG' }) initiate( @Req() request: AuthenticatedRequest, @Param('chat_id') chatId: string, @Body() body: unknown, ) { return this.uploads.initiate(chatId, request.currentUser.id, body); } @Post(':upload_id/complete') @HttpCode(201) @ApiParam({ name: 'upload_id', type: 'string', format: 'uuid', required: true, }) @ApiBody({ required: false, schema: { type: 'object', additionalProperties: false, properties: {} }, }) @ApiOperation({ operationId: 'completeDirectUpload', summary: 'Проверить байты и опубликовать вложение; идемпотентно для владельца', }) @ApiResponse({ status: 201, description: 'Готовое Attachment; повтор возвращает то же вложение', schema: { $ref: '#/components/schemas/Attachment' }, }) @ApiResponse({ status: 400, description: 'Размер/checksum не совпадает или некорректные параметры', }) @ApiResponse({ status: 404, description: 'Чужая или неизвестная загрузка' }) @ApiResponse({ status: 409, description: 'Истёкшее/отклонённое разрешение, нет файла или complete выполняется другой репликой', }) @ApiResponse({ status: 413, description: 'Превышен лимит bytes/pixels' }) @ApiResponse({ status: 415, description: 'Повреждённое изображение или неверный MIME', }) complete( @Req() request: AuthenticatedRequest, @Param('chat_id') chatId: string, @Param('upload_id') uploadId: string, @Body() body: unknown, ) { return this.uploads.complete( chatId, uploadId, request.currentUser.id, body, ); } }