|
| 1 | +import { Controller, Get, NotFoundException, Param, Res } from '@nestjs/common'; |
| 2 | +import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger'; |
| 3 | +import { InjectRepository } from '@nestjs/typeorm'; |
| 4 | +import { Response } from 'express'; |
| 5 | +import { Repository } from 'typeorm'; |
| 6 | +import { Chunks } from '../entities/files/chunks.entity'; |
| 7 | +import { Files } from '../entities/files/files.entity'; |
| 8 | +import { FileRetrieverService } from '../services/file-retriever.sevice'; |
| 9 | + |
| 10 | +@ApiTags('Files') |
| 11 | +@Controller('files') |
| 12 | +export class FilesController { |
| 13 | + constructor( |
| 14 | + private fileRetrieverService: FileRetrieverService, |
| 15 | + @InjectRepository(Files) |
| 16 | + private filesRepository: Repository<Files>, |
| 17 | + @InjectRepository(Chunks) |
| 18 | + private chunksRepository: Repository<Chunks>, |
| 19 | + ) {} |
| 20 | + |
| 21 | + @Get(':cid') |
| 22 | + @ApiOperation({ |
| 23 | + operationId: 'getFile', |
| 24 | + summary: 'Download file by CID', |
| 25 | + }) |
| 26 | + @ApiParam({ name: 'cid', description: 'CID of the file' }) |
| 27 | + @ApiResponse({ |
| 28 | + status: 200, |
| 29 | + description: 'Returns the file content as a byte stream', |
| 30 | + headers: { |
| 31 | + 'Content-Type': { |
| 32 | + description: 'The MIME type of the file', |
| 33 | + example: 'application/octet-stream', |
| 34 | + }, |
| 35 | + }, |
| 36 | + }) |
| 37 | + async getFile( |
| 38 | + @Param('cid') cid: string, |
| 39 | + @Res() res: Response, |
| 40 | + ): Promise<void> { |
| 41 | + const file = await this.filesRepository.findOne({ |
| 42 | + where: { |
| 43 | + id: cid, |
| 44 | + }, |
| 45 | + }); |
| 46 | + if (!file) { |
| 47 | + throw new NotFoundException(`File with CID ${cid} not found`); |
| 48 | + } |
| 49 | + |
| 50 | + const chunk = await this.chunksRepository.findOne({ |
| 51 | + where: { |
| 52 | + id: cid, |
| 53 | + }, |
| 54 | + }); |
| 55 | + |
| 56 | + const contentType = file.contentType() || 'application/octet-stream'; |
| 57 | + res.setHeader('Content-Type', contentType); |
| 58 | + res.setHeader('Content-Length', file.size); |
| 59 | + res.setHeader('Content-Disposition', `filename="${file.name}"`); |
| 60 | + |
| 61 | + const isCompressedAndPlainText = |
| 62 | + chunk?.upload_options?.encryption?.algorithm === undefined && |
| 63 | + chunk?.upload_options?.compression?.algorithm !== undefined; |
| 64 | + if (isCompressedAndPlainText) { |
| 65 | + res.setHeader('Content-Encoding', 'deflate'); |
| 66 | + } |
| 67 | + |
| 68 | + const fileBuffer = await this.fileRetrieverService.getBuffer(cid); |
| 69 | + |
| 70 | + res.send(fileBuffer); |
| 71 | + } |
| 72 | +} |
0 commit comments