-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
File Uploads: Add download endpoint (#2409)
Adds an optional download endpoint to download file uploads. The endpoint is only enabled if a download secret is provided in the module config: ```ts FileUploadsModule.register({ /* ... */, download: { apiUrl: config.apiUrl, secret: "your secret", }, }) ``` We also add a timeout to the URL (1h). Example URL: `http://localhost:4000/file-uploads/6a61a9439a7d9073b3415f08c317366f89901e64/d4821356-809a-4585-bb16-c4ade214e13b/1723450853782` --------- Co-authored-by: Thomas Dax <thomas.dax@vivid-planet.com>
- Loading branch information
1 parent
ad151b0
commit a970190
Showing
11 changed files
with
224 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
--- | ||
"@comet/cms-api": minor | ||
--- | ||
|
||
File Uploads: Add download endpoint | ||
|
||
The endpoint can be enabled by providing the `download` option in the module config: | ||
|
||
```ts | ||
FileUploadsModule.register({ | ||
/* ... */, | ||
download: { | ||
secret: "your secret", | ||
}, | ||
}) | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
packages/api/cms-api/src/file-uploads/dto/file-uploads-download.params.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import { Type } from "class-transformer"; | ||
import { IsHash, IsNumber, IsUUID } from "class-validator"; | ||
|
||
export class DownloadParams { | ||
@IsUUID() | ||
id: string; | ||
|
||
@Type(() => Number) | ||
@IsNumber() | ||
timeout: number; | ||
} | ||
|
||
export class HashDownloadParams extends DownloadParams { | ||
@IsHash("sha1") | ||
hash: string; | ||
} |
108 changes: 108 additions & 0 deletions
108
packages/api/cms-api/src/file-uploads/file-uploads-download.controller.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
import { InjectRepository } from "@mikro-orm/nestjs"; | ||
import { EntityRepository } from "@mikro-orm/postgresql"; | ||
import { Controller, Get, GoneException, Headers, Inject, NotFoundException, Param, Res, Type } from "@nestjs/common"; | ||
import { Response } from "express"; | ||
|
||
import { DisableCometGuards } from "../auth/decorators/disable-comet-guards.decorator"; | ||
import { BlobStorageBackendService } from "../blob-storage/backends/blob-storage-backend.service"; | ||
import { calculatePartialRanges, createHashedPath } from "../dam/files/files.utils"; | ||
import { RequiredPermission } from "../user-permissions/decorators/required-permission.decorator"; | ||
import { DownloadParams, HashDownloadParams } from "./dto/file-uploads-download.params"; | ||
import { FileUpload } from "./entities/file-upload.entity"; | ||
import { FileUploadsConfig } from "./file-uploads.config"; | ||
import { FILE_UPLOADS_CONFIG } from "./file-uploads.constants"; | ||
import { FileUploadsService } from "./file-uploads.service"; | ||
|
||
export function createFileUploadsDownloadController(options: { public: boolean }): Type<unknown> { | ||
@Controller("file-uploads") | ||
class BaseFileUploadsDownloadController { | ||
constructor( | ||
@InjectRepository(FileUpload) private readonly fileUploadsRepository: EntityRepository<FileUpload>, | ||
@Inject(BlobStorageBackendService) private readonly blobStorageBackendService: BlobStorageBackendService, | ||
@Inject(FILE_UPLOADS_CONFIG) private readonly config: FileUploadsConfig, | ||
private readonly fileUploadsService: FileUploadsService, | ||
) {} | ||
|
||
@Get(":hash/:id/:timeout") | ||
async download(@Param() { hash, ...params }: HashDownloadParams, @Res() res: Response, @Headers("range") range?: string): Promise<void> { | ||
if (!this.isValidHash(hash, params)) { | ||
throw new NotFoundException(); | ||
} | ||
|
||
if (Date.now() > params.timeout) { | ||
throw new GoneException(); | ||
} | ||
|
||
const file = await this.fileUploadsRepository.findOne(params.id); | ||
|
||
if (!file) { | ||
throw new NotFoundException(); | ||
} | ||
|
||
const filePath = createHashedPath(file.contentHash); | ||
const fileExists = await this.blobStorageBackendService.fileExists(this.config.directory, filePath); | ||
|
||
if (!fileExists) { | ||
throw new NotFoundException(); | ||
} | ||
|
||
const headers = { | ||
"content-disposition": `attachment; filename="${file.name}"`, | ||
"content-type": file.mimetype, | ||
"last-modified": file.updatedAt?.toUTCString(), | ||
"content-length": file.size, | ||
}; | ||
|
||
// https://medium.com/@vishal1909/how-to-handle-partial-content-in-node-js-8b0a5aea216 | ||
let stream: NodeJS.ReadableStream; | ||
|
||
if (range) { | ||
const { start, end, contentLength } = calculatePartialRanges(file.size, range); | ||
|
||
if (start >= file.size || end >= file.size) { | ||
res.writeHead(416, { | ||
"content-range": `bytes */${file.size}`, | ||
}); | ||
res.end(); | ||
return; | ||
} | ||
|
||
stream = await this.blobStorageBackendService.getPartialFile( | ||
this.config.directory, | ||
createHashedPath(file.contentHash), | ||
start, | ||
contentLength, | ||
); | ||
|
||
res.writeHead(206, { | ||
...headers, | ||
"accept-ranges": "bytes", | ||
"content-range": `bytes ${start}-${end}/${file.size}`, | ||
"content-length": contentLength, | ||
}); | ||
} else { | ||
stream = await this.blobStorageBackendService.getFile(this.config.directory, createHashedPath(file.contentHash)); | ||
|
||
res.writeHead(200, headers); | ||
} | ||
|
||
stream.pipe(res); | ||
} | ||
|
||
private isValidHash(hash: string, params: DownloadParams): boolean { | ||
return hash === this.fileUploadsService.createHash(params); | ||
} | ||
} | ||
|
||
if (options.public) { | ||
@DisableCometGuards() | ||
class PublicFileUploadsDownloadController extends BaseFileUploadsDownloadController {} | ||
|
||
return PublicFileUploadsDownloadController; | ||
} | ||
|
||
@RequiredPermission("fileUploads", { skipScopeCheck: true }) | ||
class PrivateFileUploadsDownloadController extends BaseFileUploadsDownloadController {} | ||
|
||
return PrivateFileUploadsDownloadController; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters