feat: add attachment download and message attachment links

This commit is contained in:
2026-11-05 15:23:15 +03:00
parent fa0211eecb
commit f523cad721
10 changed files with 486 additions and 17 deletions
+36 -1
View File
@@ -1,13 +1,15 @@
import {
Controller,
Get,
HttpCode,
Param,
Post,
Query,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { FastifyReply, FastifyRequest } from 'fastify';
import { Readable } from 'stream';
import { AuthGuard } from '../auth/auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -41,4 +43,37 @@ export class AttachmentsController {
});
return toAttachmentResponse(attachment);
}
@Get('api/v1/attachments/:attachmentId')
async metadata(
@Param('attachmentId') attachmentId: string,
@CurrentUser() user: User,
): Promise<AttachmentResponse> {
return toAttachmentResponse(
await this.attachments.getVisible(attachmentId, user.id),
);
}
@Get('api/v1/attachments/:attachmentId/content')
async content(
@Param('attachmentId') attachmentId: string,
@Query('variant') variant: unknown,
@CurrentUser() user: User,
@Res() reply: FastifyReply,
): Promise<void> {
const { attachment, content } = await this.attachments.openContent(
attachmentId,
user.id,
variant,
);
await reply
.header('content-type', attachment.contentType)
.header('content-length', attachment.sizeBytes)
.header('x-content-type-options', 'nosniff')
.header(
'content-disposition',
`inline; filename*=UTF-8''${encodeURIComponent(attachment.filename)}`,
)
.send(content);
}
}
+38
View File
@@ -8,6 +8,7 @@ import { Readable } from 'stream';
import { assertChatMember } from '../chats/chat-access';
import { codePointLength } from '../common/dto/code-point-length.validator';
import { ApiError } from '../common/filters/api-error';
import { validate as isUuid } from '../common/uuid';
import { isDatabaseUnavailable, PrismaService } from '../db/prisma.service';
import { S3Service } from '../storage/s3.service';
import { assertValidImage, isSupportedContentType } from './image-validation';
@@ -17,6 +18,7 @@ const TEMP_PREFIX = 'messenger-upload-';
const STALE_TEMP_MS = 60 * 60 * 1000;
const MAX_FILENAME_CODE_POINTS = 255;
const FORBIDDEN_FILENAME = /[/\\\p{Cc}\p{Zl}\p{Zp}]/u;
const KNOWN_VARIANTS = new Set(['thumbnail', 'crop', 'optimized']);
export interface UploadInput {
chatId: string;
@@ -65,6 +67,32 @@ export class AttachmentsService implements OnModuleInit {
}
}
async getVisible(attachmentId: string, userId: string): Promise<Attachment> {
if (!isUuid(attachmentId)) {
throw new ApiError('invalid_request', 'attachmentId must be a valid UUID');
}
const row = await this.prisma.attachment.findFirst({
where: {
id: attachmentId,
chat: { members: { some: { userId } } },
},
});
if (!row) {
throw new ApiError('not_found', 'attachment not found');
}
return row;
}
async openContent(
attachmentId: string,
userId: string,
variant: unknown,
): Promise<{ attachment: Attachment; content: Readable }> {
const attachment = await this.getVisible(attachmentId, userId);
assertOriginalVariant(variant);
return { attachment, content: await this.s3.getStream(attachment.objectKey) };
}
private async store(
input: UploadInput,
filename: string,
@@ -126,6 +154,16 @@ export class AttachmentsService implements OnModuleInit {
}
}
function assertOriginalVariant(raw: unknown): void {
if (raw === undefined || raw === 'original') {
return;
}
if (typeof raw === 'string' && KNOWN_VARIANTS.has(raw)) {
throw new ApiError('not_found', 'attachment variant not found');
}
throw new ApiError('invalid_request', 'unknown attachment variant');
}
function isDefiniteRejection(error: unknown): boolean {
return (
error instanceof Prisma.PrismaClientKnownRequestError &&
+1
View File
@@ -18,4 +18,5 @@ export interface Message {
senderId: string;
text: string;
createdAt: string;
attachmentIds: string[];
}
+31 -3
View File
@@ -1,5 +1,32 @@
import { ArrayMaxSize, IsArray, IsString, ValidateIf } from 'class-validator';
import {
ArrayMaxSize,
IsArray,
IsString,
Validate,
ValidateIf,
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import { CodePointLength } from '../../common/dto/code-point-length.validator';
import { validate as isUuid } from '../../common/uuid';
@ValidatorConstraint({ name: 'uniqueUuidList' })
class UniqueUuidList implements ValidatorConstraintInterface {
validate(value: unknown): boolean {
if (
!Array.isArray(value) ||
!value.every((id) => typeof id === 'string' && isUuid(id))
) {
return false;
}
const normalized = (value as string[]).map((id) => id.toLowerCase());
return new Set(normalized).size === normalized.length;
}
defaultMessage(): string {
return 'attachment_ids must contain unique UUIDs';
}
}
export class CreateMessageDto {
@IsString()
@@ -8,6 +35,7 @@ export class CreateMessageDto {
@ValidateIf((dto: CreateMessageDto) => dto.attachment_ids !== undefined)
@IsArray()
@ArrayMaxSize(0, { message: 'attachment_ids must be empty: attachments are not supported' })
attachment_ids?: unknown[];
@ArrayMaxSize(10)
@Validate(UniqueUuidList)
attachment_ids?: string[];
}
+1 -1
View File
@@ -21,6 +21,6 @@ export function toMessageResponse(message: Message): MessageResponse {
sender_id: message.senderId,
text: message.text,
created_at: message.createdAt,
attachment_ids: [],
attachment_ids: message.attachmentIds,
};
}
+7 -1
View File
@@ -36,7 +36,13 @@ export class MessagesController {
@CurrentUser() user: User,
): Promise<MessageResponse> {
const key = parseIdempotencyKey(keyRaw);
const message = await this.messages.create(chatId, user.id, dto.text, key);
const message = await this.messages.create(
chatId,
user.id,
dto.text,
(dto.attachment_ids ?? []).map((id) => id.toLowerCase()),
key,
);
return toMessageResponse(message);
}
+61 -8
View File
@@ -15,8 +15,20 @@ interface MessageRow {
senderId: string;
text: string;
createdAt: Date;
attachmentIds: string[];
}
const ATTACHMENT_LINKS = {
attachments: {
orderBy: { position: 'asc' },
select: { attachmentId: true },
},
} satisfies Prisma.MessageInclude;
type MessageWithLinks = Prisma.MessageGetPayload<{
include: typeof ATTACHMENT_LINKS;
}>;
class KeyAlreadyUsed extends Error {}
@Injectable()
@@ -30,18 +42,20 @@ export class MessagesService {
chatId: string,
callerId: string,
text: string,
attachmentIds: string[],
key: string,
): Promise<Message> {
await this.assertMember(chatId, callerId);
if (codePointLength(text.trim()) === 0) {
if (codePointLength(text.trim()) === 0 && attachmentIds.length === 0) {
throw new ApiError(
'invalid_request',
'text must not be empty or whitespace-only',
'text must not be empty or whitespace-only without attachments',
);
}
await this.assertAttachmentsInChat(chatId, attachmentIds);
const scope = { userId: callerId, chatId, key };
const requestHash = createHash('sha256')
.update(JSON.stringify({ text }))
.update(JSON.stringify({ text, attachment_ids: attachmentIds }))
.digest('hex');
try {
return await this.prisma.$transaction(async (tx) => {
@@ -52,7 +66,18 @@ export class MessagesService {
},
});
const row = await tx.message.create({
data: { chatId, senderId: callerId, text },
data: {
chatId,
senderId: callerId,
text,
attachments: {
create: attachmentIds.map((attachmentId, position) => ({
attachmentId,
position,
})),
},
},
include: ATTACHMENT_LINKS,
});
const { count } = await tx.idempotencyKey.createMany({
data: [{ ...scope, requestHash, messageId: row.id }],
@@ -61,7 +86,7 @@ export class MessagesService {
if (count === 0) {
throw new KeyAlreadyUsed();
}
return toMessage(row);
return linkedMessage(row);
});
} catch (error) {
if (!(error instanceof KeyAlreadyUsed)) {
@@ -70,7 +95,7 @@ export class MessagesService {
}
const stored = await this.prisma.idempotencyKey.findUnique({
where: { userId_chatId_key: scope },
include: { message: true },
include: { message: { include: ATTACHMENT_LINKS } },
});
if (!stored || stored.requestHash !== requestHash) {
throw new ApiError(
@@ -78,7 +103,7 @@ export class MessagesService {
'Idempotency-Key was already used with a different request',
);
}
return toMessage(stored.message);
return linkedMessage(stored.message);
}
async list(
@@ -109,7 +134,12 @@ export class MessagesService {
after = Prisma.sql`AND (created_at, id) > (${anchor.createdAt}::timestamptz, ${anchor.id}::uuid)`;
}
const rows = await this.prisma.$queryRaw<MessageRow[]>`
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt"
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt",
ARRAY(
SELECT attachment_id::text FROM message_attachments
WHERE message_id = messages.id
ORDER BY position
) AS "attachmentIds"
FROM messages
WHERE chat_id = ${chatId}::uuid ${after}
ORDER BY created_at, id
@@ -128,6 +158,28 @@ export class MessagesService {
private assertMember(chatId: string, callerId: string): Promise<void> {
return assertChatMember(this.prisma, chatId, callerId);
}
private async assertAttachmentsInChat(
chatId: string,
attachmentIds: string[],
): Promise<void> {
if (attachmentIds.length === 0) {
return;
}
const found = await this.prisma.attachment.count({
where: { id: { in: attachmentIds }, chatId },
});
if (found !== attachmentIds.length) {
throw new ApiError('not_found', 'attachment not found');
}
}
}
function linkedMessage(row: MessageWithLinks): Message {
return toMessage({
...row,
attachmentIds: row.attachments.map((link) => link.attachmentId),
});
}
function toMessage(row: MessageRow): Message {
@@ -137,5 +189,6 @@ function toMessage(row: MessageRow): Message {
senderId: row.senderId,
text: row.text,
createdAt: row.createdAt.toISOString(),
attachmentIds: row.attachmentIds,
};
}
+33 -1
View File
@@ -1,10 +1,12 @@
import {
DeleteObjectCommand,
GetObjectCommand,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { createReadStream, readFileSync } from 'fs';
import { Readable } from 'stream';
import { ApiError } from '../common/filters/api-error';
const CONNECT_TIMEOUT_MS = 1000;
@@ -23,10 +25,11 @@ export interface StoredFile {
export class S3Service implements OnModuleDestroy {
private readonly logger = new Logger('S3Service');
private readonly client: S3Client;
private readonly streamClient: S3Client;
private readonly bucket = process.env.S3_BUCKET ?? 'messenger-attachments';
constructor() {
this.client = new S3Client({
const config = {
endpoint: process.env.S3_ENDPOINT ?? 'http://s3:9000',
region: process.env.S3_REGION ?? 'us-east-1',
forcePathStyle: true,
@@ -35,11 +38,18 @@ export class S3Service implements OnModuleDestroy {
accessKeyId: readSecret('S3_ACCESS_KEY_ID'),
secretAccessKey: readSecret('S3_SECRET_ACCESS_KEY'),
},
};
this.client = new S3Client({
...config,
requestHandler: {
connectionTimeout: CONNECT_TIMEOUT_MS,
requestTimeout: IDLE_TIMEOUT_MS,
},
});
this.streamClient = new S3Client({
...config,
requestHandler: { connectionTimeout: CONNECT_TIMEOUT_MS },
});
}
async putFile(file: StoredFile): Promise<void> {
@@ -58,6 +68,27 @@ export class S3Service implements OnModuleDestroy {
);
}
async getStream(key: string): Promise<Readable> {
const deadline = new AbortController();
const timer = setTimeout(() => deadline.abort(), IDLE_TIMEOUT_MS);
try {
const { Body } = await this.streamClient.send(
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
{ abortSignal: deadline.signal },
);
return Body as Readable;
} catch (error) {
const name = error instanceof Error ? error.name : 'unknown error';
this.logger.error(`get ${key} failed: ${name}`);
if (name === 'NoSuchKey') {
throw new Error(`object ${key} is missing from storage`);
}
throw new ApiError('unavailable', 'object storage unavailable');
} finally {
clearTimeout(timer);
}
}
async delete(key: string): Promise<void> {
await this.guard(`delete ${key}`, () =>
this.client.send(
@@ -69,6 +100,7 @@ export class S3Service implements OnModuleDestroy {
onModuleDestroy(): void {
this.client.destroy();
this.streamClient.destroy();
}
private async guard<T>(action: string, run: () => Promise<T>): Promise<T> {