|
| 1 | +import { Controller, Get, InternalServerErrorException, NotFoundException, Param, Req, Res } from "@nestjs/common"; |
| 2 | +import { ApiTags } from "@nestjs/swagger"; |
| 3 | +import { Request, Response } from "express"; |
| 4 | +import { MediaService } from "./media.service"; |
| 5 | +import { ApiService } from "@multiversx/sdk-nestjs-http"; |
| 6 | +import { OriginLogger } from "@multiversx/sdk-nestjs-common"; |
| 7 | +import https from 'https'; |
| 8 | + |
| 9 | +@Controller() |
| 10 | +@ApiTags('media') |
| 11 | +export class MediaController { |
| 12 | + private readonly logger = new OriginLogger(MediaController.name); |
| 13 | + |
| 14 | + constructor( |
| 15 | + private readonly mediaService: MediaService, |
| 16 | + private readonly apiService: ApiService, |
| 17 | + ) { } |
| 18 | + |
| 19 | + @Get("/media/:uri(*)") |
| 20 | + async redirectToMediaUri( |
| 21 | + @Param('uri') uri: string, |
| 22 | + @Req() req: Request, |
| 23 | + @Res() res: Response |
| 24 | + ) { |
| 25 | + const redirectUrl = await this.mediaService.getRedirectUrl(uri); |
| 26 | + if (!redirectUrl) { |
| 27 | + throw new NotFoundException('Not found'); |
| 28 | + } |
| 29 | + |
| 30 | + try { |
| 31 | + const response = await this.apiService.get(redirectUrl, { |
| 32 | + // @ts-ignore |
| 33 | + responseType: 'stream', |
| 34 | + timeout: 60_000, // 60 seconds timeout |
| 35 | + httpsAgent: new https.Agent({ rejectUnauthorized: false }), |
| 36 | + headers: { |
| 37 | + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36', |
| 38 | + }, |
| 39 | + }); |
| 40 | + |
| 41 | + res.setHeader('content-type', response.headers['content-type']); |
| 42 | + res.setHeader('content-length', response.headers['content-length']); |
| 43 | + res.setHeader('cache-control', 'max-age=60'); |
| 44 | + res.setHeader('Access-Control-Allow-Origin', '*'); |
| 45 | + |
| 46 | + response.data.pipe(res); |
| 47 | + |
| 48 | + response.data.on('error', (error: any) => { |
| 49 | + this.logger?.error(`Error streaming the resource: ${redirectUrl}`); |
| 50 | + this.logger?.error(error); |
| 51 | + |
| 52 | + throw new InternalServerErrorException('Failed to fetch URL'); |
| 53 | + }); |
| 54 | + |
| 55 | + req.on('close', () => { |
| 56 | + response.data?.destroy(); |
| 57 | + }); |
| 58 | + |
| 59 | + return; |
| 60 | + } catch (error) { |
| 61 | + this.logger.error(`Failed to fetch URL: ${redirectUrl}`); |
| 62 | + |
| 63 | + throw new InternalServerErrorException('Failed to fetch URL'); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments