enhance: fallback option for media proxy

This commit is contained in:
syuilo 2022-12-08 17:16:50 +09:00
parent 2a86942f07
commit 6d46e5cf77
2 changed files with 19 additions and 1 deletions

View file

@ -1,7 +1,10 @@
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { FastifyInstance, FastifyPluginOptions, FastifyReply, FastifyRequest } from 'fastify'; import { FastifyInstance, FastifyPluginOptions, FastifyReply, FastifyRequest } from 'fastify';
import sharp from 'sharp'; import sharp from 'sharp';
import fastifyStatic from '@fastify/static';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';
import type { Config } from '@/config.js'; import type { Config } from '@/config.js';
import { isMimeImage } from '@/misc/is-mime-image.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 { LoggerService } from '@/core/LoggerService.js';
import { bindThis } from '@/decorators.js'; import { bindThis } from '@/decorators.js';
const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename);
const assets = `${_dirname}/../../server/file/assets/`;
@Injectable() @Injectable()
export class MediaProxyServerService { export class MediaProxyServerService {
private logger: Logger; private logger: Logger;
@ -41,6 +49,11 @@ export class MediaProxyServerService {
done(); done();
}); });
fastify.register(fastifyStatic, {
root: _dirname,
serve: false,
});
fastify.get<{ fastify.get<{
Params: { url: string; }; Params: { url: string; };
Querystring: { url?: string; }; Querystring: { url?: string; };
@ -126,6 +139,10 @@ export class MediaProxyServerService {
} catch (err) { } catch (err) {
this.logger.error(`${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)) { if (err instanceof StatusError && (err.statusCode === 302 || err.isClientError)) {
reply.code(err.statusCode); reply.code(err.statusCode);
} else { } else {

View file

@ -4,7 +4,8 @@ import { url } from '@/config';
export function getProxiedImageUrl(imageUrl: string, type?: 'preview'): string { export function getProxiedImageUrl(imageUrl: string, type?: 'preview'): string {
return `${url}/proxy/image.webp?${query({ return `${url}/proxy/image.webp?${query({
url: imageUrl, url: imageUrl,
...(type ? { [type]: "1" } : {}), fallback: '1',
...(type ? { [type]: '1' } : {}),
})}`; })}`;
} }