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
+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 &&