From 6d46e5cf7759e29abcfc63dea81e325c2870acea Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 8 Dec 2022 17:16:50 +0900 Subject: [PATCH] enhance: fallback option for media proxy --- .../src/server/MediaProxyServerService.ts | 17 +++++++++++++++++ packages/client/src/scripts/media-proxy.ts | 3 ++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/backend/src/server/MediaProxyServerService.ts b/packages/backend/src/server/MediaProxyServerService.ts index 733a7feeb5..8ffcbe6bad 100644 --- a/packages/backend/src/server/MediaProxyServerService.ts +++ b/packages/backend/src/server/MediaProxyServerService.ts @@ -1,7 +1,10 @@ import * as fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname } from 'node:path'; import { Inject, Injectable } from '@nestjs/common'; import { FastifyInstance, FastifyPluginOptions, FastifyReply, FastifyRequest } from 'fastify'; import sharp from 'sharp'; +import fastifyStatic from '@fastify/static'; import { DI } from '@/di-symbols.js'; import type { Config } from '@/config.js'; import { isMimeImage } from '@/misc/is-mime-image.js'; @@ -16,6 +19,11 @@ import { FileInfoService } from '@/core/FileInfoService.js'; import { LoggerService } from '@/core/LoggerService.js'; import { bindThis } from '@/decorators.js'; +const _filename = fileURLToPath(import.meta.url); +const _dirname = dirname(_filename); + +const assets = `${_dirname}/../../server/file/assets/`; + @Injectable() export class MediaProxyServerService { private logger: Logger; @@ -41,6 +49,11 @@ export class MediaProxyServerService { done(); }); + fastify.register(fastifyStatic, { + root: _dirname, + serve: false, + }); + fastify.get<{ Params: { url: string; }; Querystring: { url?: string; }; @@ -125,6 +138,10 @@ export class MediaProxyServerService { return image.data; } catch (err) { this.logger.error(`${err}`); + + if ('fallback' in request.query) { + return reply.sendFile('/dummy.png', assets); + } if (err instanceof StatusError && (err.statusCode === 302 || err.isClientError)) { reply.code(err.statusCode); diff --git a/packages/client/src/scripts/media-proxy.ts b/packages/client/src/scripts/media-proxy.ts index 506cb78291..aaf7f9e610 100644 --- a/packages/client/src/scripts/media-proxy.ts +++ b/packages/client/src/scripts/media-proxy.ts @@ -4,7 +4,8 @@ import { url } from '@/config'; export function getProxiedImageUrl(imageUrl: string, type?: 'preview'): string { return `${url}/proxy/image.webp?${query({ url: imageUrl, - ...(type ? { [type]: "1" } : {}), + fallback: '1', + ...(type ? { [type]: '1' } : {}), })}`; }