2022-09-18 03:27:08 +09:00
|
|
|
import * as fs from 'node:fs';
|
2022-12-08 17:16:50 +09:00
|
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
import { dirname } from 'node:path';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import sharp from 'sharp';
|
2022-12-08 17:16:50 +09:00
|
|
|
import fastifyStatic from '@fastify/static';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { DI } from '@/di-symbols.js';
|
2022-09-21 05:33:11 +09:00
|
|
|
import type { Config } from '@/config.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { isMimeImage } from '@/misc/is-mime-image.js';
|
|
|
|
import { createTemp } from '@/misc/create-temp.js';
|
|
|
|
import { DownloadService } from '@/core/DownloadService.js';
|
2022-12-30 12:00:50 +09:00
|
|
|
import { ImageProcessingService, webpDefault } from '@/core/ImageProcessingService.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import type { IImage } from '@/core/ImageProcessingService.js';
|
|
|
|
import { FILE_TYPE_BROWSERSAFE } from '@/const.js';
|
|
|
|
import { StatusError } from '@/misc/status-error.js';
|
2022-09-18 23:07:41 +09:00
|
|
|
import type Logger from '@/logger.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { FileInfoService } from '@/core/FileInfoService.js';
|
2022-09-18 23:07:41 +09:00
|
|
|
import { LoggerService } from '@/core/LoggerService.js';
|
2022-12-04 15:03:09 +09:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2022-12-14 00:01:45 +09:00
|
|
|
import type { FastifyInstance, FastifyPluginOptions, FastifyReply, FastifyRequest } from 'fastify';
|
2022-09-18 03:27:08 +09:00
|
|
|
|
2022-12-08 17:16:50 +09:00
|
|
|
const _filename = fileURLToPath(import.meta.url);
|
|
|
|
const _dirname = dirname(_filename);
|
|
|
|
|
2022-12-23 16:57:20 +09:00
|
|
|
const assets = `${_dirname}/../../src/server/assets/`;
|
2022-12-08 17:16:50 +09:00
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
@Injectable()
|
|
|
|
export class MediaProxyServerService {
|
2022-09-19 03:11:50 +09:00
|
|
|
private logger: Logger;
|
2022-09-18 23:07:41 +09:00
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
constructor(
|
|
|
|
@Inject(DI.config)
|
|
|
|
private config: Config,
|
|
|
|
|
|
|
|
private fileInfoService: FileInfoService,
|
|
|
|
private downloadService: DownloadService,
|
|
|
|
private imageProcessingService: ImageProcessingService,
|
2022-09-18 23:07:41 +09:00
|
|
|
private loggerService: LoggerService,
|
2022-09-18 03:27:08 +09:00
|
|
|
) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.logger = this.loggerService.getLogger('server', 'gray', false);
|
2022-12-03 19:42:05 +09:00
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
//this.createServer = this.createServer.bind(this);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-12-03 19:42:05 +09:00
|
|
|
public createServer(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) {
|
|
|
|
fastify.addHook('onRequest', (request, reply, done) => {
|
|
|
|
reply.header('Content-Security-Policy', 'default-src \'none\'; img-src \'self\'; media-src \'self\'; style-src \'unsafe-inline\'');
|
|
|
|
done();
|
2022-09-18 03:27:08 +09:00
|
|
|
});
|
|
|
|
|
2022-12-08 17:16:50 +09:00
|
|
|
fastify.register(fastifyStatic, {
|
|
|
|
root: _dirname,
|
|
|
|
serve: false,
|
|
|
|
});
|
|
|
|
|
2022-12-03 19:42:05 +09:00
|
|
|
fastify.get<{
|
|
|
|
Params: { url: string; };
|
|
|
|
Querystring: { url?: string; };
|
|
|
|
}>('/:url*', async (request, reply) => await this.handler(request, reply));
|
2022-09-18 03:27:08 +09:00
|
|
|
|
2022-12-03 19:42:05 +09:00
|
|
|
done();
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-12-03 19:42:05 +09:00
|
|
|
private async handler(request: FastifyRequest<{ Params: { url: string; }; Querystring: { url?: string; }; }>, reply: FastifyReply) {
|
|
|
|
const url = 'url' in request.query ? request.query.url : 'https://' + request.params.url;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
if (typeof url !== 'string') {
|
2022-12-03 19:42:05 +09:00
|
|
|
reply.code(400);
|
2022-09-18 03:27:08 +09:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create temp file
|
|
|
|
const [path, cleanup] = await createTemp();
|
|
|
|
|
|
|
|
try {
|
|
|
|
await this.downloadService.downloadUrl(url, path);
|
|
|
|
|
|
|
|
const { mime, ext } = await this.fileInfoService.detectType(path);
|
|
|
|
const isConvertibleImage = isMimeImage(mime, 'sharp-convertible-image');
|
2023-01-06 22:34:50 +09:00
|
|
|
const isAnimationConvertibleImage = isMimeImage(mime, 'sharp-animation-convertible-image');
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
let image: IImage;
|
2022-12-30 12:00:50 +09:00
|
|
|
if ('emoji' in request.query && isConvertibleImage) {
|
2023-01-06 22:34:50 +09:00
|
|
|
if (!isAnimationConvertibleImage && !('static' in request.query)) {
|
|
|
|
image = {
|
|
|
|
data: fs.readFileSync(path),
|
|
|
|
ext,
|
|
|
|
type: mime,
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
const data = await sharp(path, { animated: !('static' in request.query) })
|
2022-12-30 12:00:50 +09:00
|
|
|
.resize({
|
|
|
|
height: 128,
|
|
|
|
withoutEnlargement: true,
|
|
|
|
})
|
|
|
|
.webp(webpDefault)
|
|
|
|
.toBuffer();
|
|
|
|
|
2023-01-06 22:34:50 +09:00
|
|
|
image = {
|
|
|
|
data,
|
|
|
|
ext: 'webp',
|
|
|
|
type: 'image/webp',
|
|
|
|
};
|
|
|
|
}
|
2022-12-30 12:00:50 +09:00
|
|
|
} else if ('static' in request.query && isConvertibleImage) {
|
2022-09-18 03:27:08 +09:00
|
|
|
image = await this.imageProcessingService.convertToWebp(path, 498, 280);
|
2022-12-03 19:42:05 +09:00
|
|
|
} else if ('preview' in request.query && isConvertibleImage) {
|
2022-09-18 03:27:08 +09:00
|
|
|
image = await this.imageProcessingService.convertToWebp(path, 200, 200);
|
2022-12-03 19:42:05 +09:00
|
|
|
} else if ('badge' in request.query) {
|
2022-09-18 03:27:08 +09:00
|
|
|
if (!isConvertibleImage) {
|
|
|
|
// 画像でないなら404でお茶を濁す
|
|
|
|
throw new StatusError('Unexpected mime', 404);
|
|
|
|
}
|
2022-12-30 12:00:50 +09:00
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
const mask = sharp(path)
|
|
|
|
.resize(96, 96, {
|
|
|
|
fit: 'inside',
|
|
|
|
withoutEnlargement: false,
|
|
|
|
})
|
|
|
|
.greyscale()
|
|
|
|
.normalise()
|
|
|
|
.linear(1.75, -(128 * 1.75) + 128) // 1.75x contrast
|
|
|
|
.flatten({ background: '#000' })
|
|
|
|
.toColorspace('b-w');
|
|
|
|
|
|
|
|
const stats = await mask.clone().stats();
|
|
|
|
|
|
|
|
if (stats.entropy < 0.1) {
|
|
|
|
// エントロピーがあまりない場合は404にする
|
|
|
|
throw new StatusError('Skip to provide badge', 404);
|
|
|
|
}
|
|
|
|
|
|
|
|
const data = sharp({
|
|
|
|
create: { width: 96, height: 96, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
|
|
|
|
})
|
|
|
|
.pipelineColorspace('b-w')
|
|
|
|
.boolean(await mask.png().toBuffer(), 'eor');
|
|
|
|
|
|
|
|
image = {
|
|
|
|
data: await data.png().toBuffer(),
|
|
|
|
ext: 'png',
|
|
|
|
type: 'image/png',
|
|
|
|
};
|
2022-12-30 12:00:50 +09:00
|
|
|
} else if (mime === 'image/svg+xml') {
|
|
|
|
image = await this.imageProcessingService.convertToWebp(path, 2048, 2048, webpDefault);
|
2022-09-18 03:27:08 +09:00
|
|
|
} else if (!mime.startsWith('image/') || !FILE_TYPE_BROWSERSAFE.includes(mime)) {
|
|
|
|
throw new StatusError('Rejected type', 403, 'Rejected type');
|
|
|
|
} else {
|
|
|
|
image = {
|
|
|
|
data: fs.readFileSync(path),
|
|
|
|
ext,
|
|
|
|
type: mime,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-12-03 19:42:05 +09:00
|
|
|
reply.header('Content-Type', image.type);
|
|
|
|
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
|
|
|
return image.data;
|
2022-09-18 03:27:08 +09:00
|
|
|
} catch (err) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.logger.error(`${err}`);
|
2022-12-08 17:16:50 +09:00
|
|
|
|
|
|
|
if ('fallback' in request.query) {
|
|
|
|
return reply.sendFile('/dummy.png', assets);
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
if (err instanceof StatusError && (err.statusCode === 302 || err.isClientError)) {
|
2022-12-03 19:42:05 +09:00
|
|
|
reply.code(err.statusCode);
|
2022-09-18 03:27:08 +09:00
|
|
|
} else {
|
2022-12-03 19:42:05 +09:00
|
|
|
reply.code(500);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
} finally {
|
|
|
|
cleanup();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|