forked from mtusi2026/mtusi2026lab4
90 lines
2.5 KiB
TypeScript
90 lines
2.5 KiB
TypeScript
import {
|
|
Controller,
|
|
Get,
|
|
Headers,
|
|
HttpCode,
|
|
Param,
|
|
ParseUUIDPipe,
|
|
Post,
|
|
Query,
|
|
Req,
|
|
Res,
|
|
StreamableFile,
|
|
UseGuards,
|
|
} from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
import type { Readable } from 'node:stream';
|
|
import { CurrentUser } from '../common/auth/current-user.decorator.js';
|
|
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
|
import type { AppConfig } from '../config/app-config.schema.js';
|
|
import type { User } from '../users/user.js';
|
|
import { AttachmentsService } from './attachments.service.js';
|
|
import { contentDisposition } from './filename.js';
|
|
|
|
@Controller('api/v1')
|
|
@UseGuards(CurrentUserGuard)
|
|
export class AttachmentsController {
|
|
private readonly maxUploadBytes: number;
|
|
|
|
constructor(
|
|
private readonly attachments: AttachmentsService,
|
|
config: ConfigService<AppConfig>,
|
|
) {
|
|
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
|
|
}
|
|
|
|
@Post('chats/:chatId/attachments')
|
|
@HttpCode(201)
|
|
upload(
|
|
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
|
@CurrentUser() user: User,
|
|
@Query('filename') filename: unknown,
|
|
@Headers('content-type') contentType: string | undefined,
|
|
@Headers('content-length') contentLength: string | undefined,
|
|
@Req() request: FastifyRequest,
|
|
@Res({ passthrough: true }) reply: FastifyReply,
|
|
) {
|
|
// A gigantic body is not worth draining: close the connection after the answer.
|
|
if (Number(contentLength) > 2 * this.maxUploadBytes)
|
|
reply.header('Connection', 'close');
|
|
return this.attachments.uploadProxy(
|
|
chatId,
|
|
user,
|
|
filename,
|
|
contentType,
|
|
contentLength,
|
|
request.body as Readable | undefined,
|
|
);
|
|
}
|
|
|
|
@Get('attachments/:attachmentId')
|
|
metadata(
|
|
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
|
|
@CurrentUser() user: User,
|
|
) {
|
|
return this.attachments.getMetadata(attachmentId, user);
|
|
}
|
|
|
|
@Get('attachments/:attachmentId/content')
|
|
async content(
|
|
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
|
|
@CurrentUser() user: User,
|
|
@Res({ passthrough: true }) reply: FastifyReply,
|
|
@Query('variant') variant?: string,
|
|
) {
|
|
const { row, stream } = await this.attachments.openContent(
|
|
attachmentId,
|
|
user,
|
|
variant,
|
|
);
|
|
reply.header('X-Content-Type-Options', 'nosniff');
|
|
reply.header('Cache-Control', 'private, no-store');
|
|
return new StreamableFile(stream, {
|
|
type: row.content_type,
|
|
length: Number(row.size_bytes),
|
|
disposition: contentDisposition(row.filename),
|
|
});
|
|
}
|
|
}
|