2023-07-27 00:31:52 -05:00
|
|
|
/*
|
2024-02-11 20:37:45 -06:00
|
|
|
* SPDX-FileCopyrightText: syuilo and misskey-project
|
2023-07-27 00:31:52 -05:00
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-09-17 13:27:08 -05:00
|
|
|
import * as fs from 'node:fs';
|
|
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
import { dirname } from 'node:path';
|
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import rename from 'rename';
|
2023-07-18 21:27:50 -05:00
|
|
|
import sharp from 'sharp';
|
2023-12-30 18:45:35 -06:00
|
|
|
import { sharpBmp } from '@misskey-dev/sharp-read-bmp';
|
2022-09-20 15:33:11 -05:00
|
|
|
import type { Config } from '@/config.js';
|
2023-09-15 00:28:29 -05:00
|
|
|
import type { MiDriveFile, DriveFilesRepository } from '@/models/_.js';
|
2022-09-17 13:27:08 -05:00
|
|
|
import { DI } from '@/di-symbols.js';
|
|
|
|
import { createTemp } from '@/misc/create-temp.js';
|
|
|
|
import { FILE_TYPE_BROWSERSAFE } from '@/const.js';
|
|
|
|
import { StatusError } from '@/misc/status-error.js';
|
2022-09-18 09:07:41 -05:00
|
|
|
import type Logger from '@/logger.js';
|
2022-09-17 13:27:08 -05:00
|
|
|
import { DownloadService } from '@/core/DownloadService.js';
|
2023-01-26 01:06:29 -06:00
|
|
|
import { IImageStreamable, ImageProcessingService, webpDefault } from '@/core/ImageProcessingService.js';
|
2022-09-17 13:27:08 -05:00
|
|
|
import { VideoProcessingService } from '@/core/VideoProcessingService.js';
|
|
|
|
import { InternalStorageService } from '@/core/InternalStorageService.js';
|
|
|
|
import { contentDisposition } from '@/misc/content-disposition.js';
|
|
|
|
import { FileInfoService } from '@/core/FileInfoService.js';
|
2022-09-18 09:07:41 -05:00
|
|
|
import { LoggerService } from '@/core/LoggerService.js';
|
2022-12-04 00:03:09 -06:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2023-01-26 01:06:29 -06:00
|
|
|
import { isMimeImage } from '@/misc/is-mime-image.js';
|
2023-03-04 01:51:07 -06:00
|
|
|
import { correctFilename } from '@/misc/correct-filename.js';
|
2024-02-12 19:43:06 -06:00
|
|
|
import { handleRequestRedirectToOmitSearch } from '@/misc/fastify-hook-handlers.js';
|
2023-07-18 21:27:50 -05:00
|
|
|
import type { FastifyInstance, FastifyRequest, FastifyReply, FastifyPluginOptions } from 'fastify';
|
2022-09-17 13:27:08 -05:00
|
|
|
|
|
|
|
const _filename = fileURLToPath(import.meta.url);
|
|
|
|
const _dirname = dirname(_filename);
|
|
|
|
|
|
|
|
const assets = `${_dirname}/../../server/file/assets/`;
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class FileServerService {
|
2022-09-18 13:11:50 -05:00
|
|
|
private logger: Logger;
|
2022-09-18 09:07:41 -05:00
|
|
|
|
2022-09-17 13:27:08 -05:00
|
|
|
constructor(
|
|
|
|
@Inject(DI.config)
|
|
|
|
private config: Config,
|
|
|
|
|
|
|
|
@Inject(DI.driveFilesRepository)
|
|
|
|
private driveFilesRepository: DriveFilesRepository,
|
|
|
|
|
|
|
|
private fileInfoService: FileInfoService,
|
|
|
|
private downloadService: DownloadService,
|
|
|
|
private imageProcessingService: ImageProcessingService,
|
|
|
|
private videoProcessingService: VideoProcessingService,
|
|
|
|
private internalStorageService: InternalStorageService,
|
2022-09-18 09:07:41 -05:00
|
|
|
private loggerService: LoggerService,
|
2022-09-17 13:27:08 -05:00
|
|
|
) {
|
2022-09-18 13:11:50 -05:00
|
|
|
this.logger = this.loggerService.getLogger('server', 'gray', false);
|
2022-12-03 04:42:05 -06:00
|
|
|
|
2022-12-04 00:03:09 -06:00
|
|
|
//this.createServer = this.createServer.bind(this);
|
2022-09-17 13:27:08 -05:00
|
|
|
}
|
|
|
|
|
2022-12-04 00:03:09 -06:00
|
|
|
@bindThis
|
2022-12-03 04:42:05 -06: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\'');
|
2023-12-15 22:23:25 -06:00
|
|
|
if (process.env.NODE_ENV === 'development') {
|
|
|
|
reply.header('Access-Control-Allow-Origin', '*');
|
|
|
|
}
|
2022-12-03 04:42:05 -06:00
|
|
|
done();
|
2022-09-17 13:27:08 -05:00
|
|
|
});
|
|
|
|
|
2024-02-12 19:43:06 -06:00
|
|
|
fastify.register((fastify, options, done) => {
|
|
|
|
fastify.addHook('onRequest', handleRequestRedirectToOmitSearch);
|
|
|
|
fastify.get('/files/app-default.jpg', (request, reply) => {
|
|
|
|
const file = fs.createReadStream(`${_dirname}/assets/dummy.png`);
|
|
|
|
reply.header('Content-Type', 'image/jpeg');
|
|
|
|
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
|
|
|
return reply.send(file);
|
|
|
|
});
|
|
|
|
|
|
|
|
fastify.get<{ Params: { key: string; } }>('/files/:key', async (request, reply) => {
|
|
|
|
return await this.sendDriveFile(request, reply)
|
|
|
|
.catch(err => this.errorHandler(request, reply, err));
|
|
|
|
});
|
|
|
|
fastify.get<{ Params: { key: string; } }>('/files/:key/*', async (request, reply) => {
|
|
|
|
return await reply.redirect(301, `${this.config.url}/files/${request.params.key}`);
|
|
|
|
});
|
|
|
|
done();
|
2023-01-26 01:06:29 -06:00
|
|
|
});
|
|
|
|
|
|
|
|
fastify.get<{
|
|
|
|
Params: { url: string; };
|
|
|
|
Querystring: { url?: string; };
|
|
|
|
}>('/proxy/:url*', async (request, reply) => {
|
|
|
|
return await this.proxyHandler(request, reply)
|
|
|
|
.catch(err => this.errorHandler(request, reply, err));
|
|
|
|
});
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2022-12-03 04:42:05 -06:00
|
|
|
done();
|
2022-09-17 13:27:08 -05:00
|
|
|
}
|
|
|
|
|
2022-12-04 00:03:09 -06:00
|
|
|
@bindThis
|
2023-01-26 01:06:29 -06:00
|
|
|
private async errorHandler(request: FastifyRequest<{ Params?: { [x: string]: any }; Querystring?: { [x: string]: any }; }>, reply: FastifyReply, err?: any) {
|
|
|
|
this.logger.error(`${err}`);
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
reply.header('Cache-Control', 'max-age=300');
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
if (request.query && 'fallback' in request.query) {
|
2022-12-03 04:42:05 -06:00
|
|
|
return reply.sendFile('/dummy.png', assets);
|
2022-09-17 13:27:08 -05:00
|
|
|
}
|
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
if (err instanceof StatusError && (err.statusCode === 302 || err.isClientError)) {
|
|
|
|
reply.code(err.statusCode);
|
|
|
|
return;
|
|
|
|
}
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
reply.code(500);
|
|
|
|
return;
|
|
|
|
}
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
@bindThis
|
|
|
|
private async sendDriveFile(request: FastifyRequest<{ Params: { key: string; } }>, reply: FastifyReply) {
|
|
|
|
const key = request.params.key;
|
|
|
|
const file = await this.getFileFromKey(key).then();
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
if (file === '404') {
|
|
|
|
reply.code(404);
|
|
|
|
reply.header('Cache-Control', 'max-age=86400');
|
|
|
|
return reply.sendFile('/dummy.png', assets);
|
|
|
|
}
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
if (file === '204') {
|
|
|
|
reply.code(204);
|
|
|
|
reply.header('Cache-Control', 'max-age=86400');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
if (file.state === 'remote') {
|
2023-02-03 22:38:51 -06:00
|
|
|
let image: IImageStreamable | null = null;
|
|
|
|
|
|
|
|
if (file.fileRole === 'thumbnail') {
|
2023-03-04 04:23:11 -06:00
|
|
|
if (isMimeImage(file.mime, 'sharp-convertible-image-with-bmp')) {
|
2023-02-03 22:38:51 -06:00
|
|
|
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
|
|
|
|
2023-03-12 03:31:52 -05:00
|
|
|
const url = new URL(`${this.config.mediaProxy}/static.webp`);
|
2023-02-03 22:38:51 -06:00
|
|
|
url.searchParams.set('url', file.url);
|
|
|
|
url.searchParams.set('static', '1');
|
2023-02-04 07:46:19 -06:00
|
|
|
|
|
|
|
file.cleanup();
|
2023-02-03 22:38:51 -06:00
|
|
|
return await reply.redirect(301, url.toString());
|
|
|
|
} else if (file.mime.startsWith('video/')) {
|
2023-02-11 18:13:47 -06:00
|
|
|
const externalThumbnail = this.videoProcessingService.getExternalVideoThumbnailUrl(file.url);
|
|
|
|
if (externalThumbnail) {
|
|
|
|
file.cleanup();
|
|
|
|
return await reply.redirect(301, externalThumbnail);
|
|
|
|
}
|
|
|
|
|
2023-02-03 22:38:51 -06:00
|
|
|
image = await this.videoProcessingService.generateVideoThumbnail(file.path);
|
2023-01-26 01:06:29 -06:00
|
|
|
}
|
2023-02-03 22:38:51 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
if (file.fileRole === 'webpublic') {
|
|
|
|
if (['image/svg+xml'].includes(file.mime)) {
|
|
|
|
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-03-12 03:31:52 -05:00
|
|
|
const url = new URL(`${this.config.mediaProxy}/svg.webp`);
|
2023-02-03 22:38:51 -06:00
|
|
|
url.searchParams.set('url', file.url);
|
2023-02-04 07:46:19 -06:00
|
|
|
|
|
|
|
file.cleanup();
|
2023-02-03 22:38:51 -06:00
|
|
|
return await reply.redirect(301, url.toString());
|
2023-01-26 01:06:29 -06:00
|
|
|
}
|
2023-02-03 22:38:51 -06:00
|
|
|
}
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-02-03 22:38:51 -06:00
|
|
|
if (!image) {
|
2024-01-15 03:17:01 -06:00
|
|
|
if (request.headers.range && file.file.size > 0) {
|
|
|
|
const range = request.headers.range as string;
|
|
|
|
const parts = range.replace(/bytes=/, '').split('-');
|
|
|
|
const start = parseInt(parts[0], 10);
|
|
|
|
let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1;
|
|
|
|
if (end > file.file.size) {
|
|
|
|
end = file.file.size - 1;
|
|
|
|
}
|
|
|
|
const chunksize = end - start + 1;
|
|
|
|
|
|
|
|
image = {
|
|
|
|
data: fs.createReadStream(file.path, {
|
|
|
|
start,
|
|
|
|
end,
|
|
|
|
}),
|
|
|
|
ext: file.ext,
|
|
|
|
type: file.mime,
|
|
|
|
};
|
|
|
|
|
|
|
|
reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`);
|
|
|
|
reply.header('Accept-Ranges', 'bytes');
|
|
|
|
reply.header('Content-Length', chunksize);
|
|
|
|
} else {
|
|
|
|
image = {
|
|
|
|
data: fs.createReadStream(file.path),
|
|
|
|
ext: file.ext,
|
|
|
|
type: file.mime,
|
|
|
|
};
|
|
|
|
}
|
2023-02-03 22:38:51 -06:00
|
|
|
}
|
2023-01-26 01:06:29 -06:00
|
|
|
|
|
|
|
if ('pipe' in image.data && typeof image.data.pipe === 'function') {
|
|
|
|
// image.dataがstreamなら、stream終了後にcleanup
|
|
|
|
image.data.on('end', file.cleanup);
|
|
|
|
image.data.on('close', file.cleanup);
|
|
|
|
} else {
|
|
|
|
// image.dataがstreamでないなら直ちにcleanup
|
|
|
|
file.cleanup();
|
2022-09-17 13:27:08 -05:00
|
|
|
}
|
2023-01-26 01:06:29 -06:00
|
|
|
|
|
|
|
reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(image.type) ? image.type : 'application/octet-stream');
|
2023-03-04 01:51:07 -06:00
|
|
|
reply.header('Content-Disposition',
|
|
|
|
contentDisposition(
|
|
|
|
'inline',
|
2023-07-18 21:27:50 -05:00
|
|
|
correctFilename(file.filename, image.ext),
|
|
|
|
),
|
2023-03-04 01:51:07 -06:00
|
|
|
);
|
2023-01-26 01:06:29 -06:00
|
|
|
return image.data;
|
2022-09-17 13:27:08 -05:00
|
|
|
}
|
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
if (file.fileRole !== 'original') {
|
2023-03-04 01:51:07 -06:00
|
|
|
const filename = rename(file.filename, {
|
2023-01-26 01:06:29 -06:00
|
|
|
suffix: file.fileRole === 'thumbnail' ? '-thumb' : '-web',
|
2023-03-04 01:51:07 -06:00
|
|
|
extname: file.ext ? `.${file.ext}` : '.unknown',
|
2023-01-26 01:06:29 -06:00
|
|
|
}).toString();
|
|
|
|
|
|
|
|
reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(file.mime) ? file.mime : 'application/octet-stream');
|
|
|
|
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
|
|
|
reply.header('Content-Disposition', contentDisposition('inline', filename));
|
2024-01-15 03:17:01 -06:00
|
|
|
|
|
|
|
if (request.headers.range && file.file.size > 0) {
|
|
|
|
const range = request.headers.range as string;
|
|
|
|
const parts = range.replace(/bytes=/, '').split('-');
|
|
|
|
const start = parseInt(parts[0], 10);
|
|
|
|
let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1;
|
|
|
|
if (end > file.file.size) {
|
|
|
|
end = file.file.size - 1;
|
|
|
|
}
|
|
|
|
const chunksize = end - start + 1;
|
|
|
|
const fileStream = fs.createReadStream(file.path, {
|
|
|
|
start,
|
|
|
|
end,
|
|
|
|
});
|
|
|
|
reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`);
|
|
|
|
reply.header('Accept-Ranges', 'bytes');
|
|
|
|
reply.header('Content-Length', chunksize);
|
|
|
|
reply.code(206);
|
|
|
|
return fileStream;
|
|
|
|
}
|
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
return fs.createReadStream(file.path);
|
|
|
|
} else {
|
|
|
|
reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(file.file.type) ? file.file.type : 'application/octet-stream');
|
|
|
|
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
2023-03-04 01:51:07 -06:00
|
|
|
reply.header('Content-Disposition', contentDisposition('inline', file.filename));
|
2024-01-15 03:17:01 -06:00
|
|
|
|
|
|
|
if (request.headers.range && file.file.size > 0) {
|
|
|
|
const range = request.headers.range as string;
|
|
|
|
const parts = range.replace(/bytes=/, '').split('-');
|
|
|
|
const start = parseInt(parts[0], 10);
|
|
|
|
let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1;
|
|
|
|
console.log(end);
|
|
|
|
if (end > file.file.size) {
|
|
|
|
end = file.file.size - 1;
|
|
|
|
}
|
|
|
|
const chunksize = end - start + 1;
|
|
|
|
const fileStream = fs.createReadStream(file.path, {
|
|
|
|
start,
|
|
|
|
end,
|
|
|
|
});
|
|
|
|
reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`);
|
|
|
|
reply.header('Accept-Ranges', 'bytes');
|
|
|
|
reply.header('Content-Length', chunksize);
|
|
|
|
reply.code(206);
|
|
|
|
return fileStream;
|
|
|
|
}
|
|
|
|
|
2023-03-04 01:51:07 -06:00
|
|
|
return fs.createReadStream(file.path);
|
2023-01-26 01:06:29 -06:00
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
if ('cleanup' in file) file.cleanup();
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
private async proxyHandler(request: FastifyRequest<{ Params: { url: string; }; Querystring: { url?: string; }; }>, reply: FastifyReply) {
|
|
|
|
const url = 'url' in request.query ? request.query.url : 'https://' + request.params.url;
|
|
|
|
|
|
|
|
if (typeof url !== 'string') {
|
|
|
|
reply.code(400);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-02-28 02:14:23 -06:00
|
|
|
// アバタークロップなど、どうしてもオリジンである必要がある場合
|
|
|
|
const mustOrigin = 'origin' in request.query;
|
|
|
|
|
|
|
|
if (this.config.externalMediaProxyEnabled && !mustOrigin) {
|
2023-02-03 22:38:51 -06:00
|
|
|
// 外部のメディアプロキシが有効なら、そちらにリダイレクト
|
|
|
|
|
|
|
|
reply.header('Cache-Control', 'public, max-age=259200'); // 3 days
|
|
|
|
|
|
|
|
const url = new URL(`${this.config.mediaProxy}/${request.params.url || ''}`);
|
|
|
|
|
|
|
|
for (const [key, value] of Object.entries(request.query)) {
|
|
|
|
url.searchParams.append(key, value);
|
|
|
|
}
|
|
|
|
|
|
|
|
return await reply.redirect(
|
|
|
|
301,
|
|
|
|
url.toString(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
// Create temp file
|
|
|
|
const file = await this.getStreamAndTypeFromUrl(url);
|
|
|
|
if (file === '404') {
|
|
|
|
reply.code(404);
|
|
|
|
reply.header('Cache-Control', 'max-age=86400');
|
|
|
|
return reply.sendFile('/dummy.png', assets);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file === '204') {
|
2022-12-03 04:42:05 -06:00
|
|
|
reply.code(204);
|
|
|
|
reply.header('Cache-Control', 'max-age=86400');
|
2022-09-17 13:27:08 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
try {
|
2023-03-04 04:23:11 -06:00
|
|
|
const isConvertibleImage = isMimeImage(file.mime, 'sharp-convertible-image-with-bmp');
|
|
|
|
const isAnimationConvertibleImage = isMimeImage(file.mime, 'sharp-animation-convertible-image-with-bmp');
|
2022-09-17 13:27:08 -05:00
|
|
|
|
2023-02-09 06:39:24 -06:00
|
|
|
if (
|
|
|
|
'emoji' in request.query ||
|
|
|
|
'avatar' in request.query ||
|
|
|
|
'static' in request.query ||
|
|
|
|
'preview' in request.query ||
|
|
|
|
'badge' in request.query
|
|
|
|
) {
|
|
|
|
if (!isConvertibleImage) {
|
|
|
|
// 画像でないなら404でお茶を濁す
|
|
|
|
throw new StatusError('Unexpected mime', 404);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
let image: IImageStreamable | null = null;
|
2023-02-09 06:39:24 -06:00
|
|
|
if ('emoji' in request.query || 'avatar' in request.query) {
|
2023-01-26 01:06:29 -06:00
|
|
|
if (!isAnimationConvertibleImage && !('static' in request.query)) {
|
|
|
|
image = {
|
|
|
|
data: fs.createReadStream(file.path),
|
|
|
|
ext: file.ext,
|
|
|
|
type: file.mime,
|
|
|
|
};
|
|
|
|
} else {
|
2023-03-04 04:23:11 -06:00
|
|
|
const data = (await sharpBmp(file.path, file.mime, { animated: !('static' in request.query) }))
|
2023-07-18 21:27:50 -05:00
|
|
|
.resize({
|
|
|
|
height: 'emoji' in request.query ? 128 : 320,
|
|
|
|
withoutEnlargement: true,
|
|
|
|
})
|
|
|
|
.webp(webpDefault);
|
2023-01-26 01:06:29 -06:00
|
|
|
|
|
|
|
image = {
|
|
|
|
data,
|
|
|
|
ext: 'webp',
|
|
|
|
type: 'image/webp',
|
|
|
|
};
|
|
|
|
}
|
2023-02-09 06:39:24 -06:00
|
|
|
} else if ('static' in request.query) {
|
2023-03-12 03:31:52 -05:00
|
|
|
image = this.imageProcessingService.convertSharpToWebpStream(await sharpBmp(file.path, file.mime), 498, 422);
|
2023-02-09 06:39:24 -06:00
|
|
|
} else if ('preview' in request.query) {
|
2023-03-12 03:31:52 -05:00
|
|
|
image = this.imageProcessingService.convertSharpToWebpStream(await sharpBmp(file.path, file.mime), 200, 200);
|
2023-01-26 01:06:29 -06:00
|
|
|
} else if ('badge' in request.query) {
|
2023-03-04 04:23:11 -06:00
|
|
|
const mask = (await sharpBmp(file.path, file.mime))
|
2023-01-26 01:06:29 -06:00
|
|
|
.resize(96, 96, {
|
2023-04-19 09:30:48 -05:00
|
|
|
fit: 'contain',
|
|
|
|
position: 'centre',
|
2023-01-26 01:06:29 -06:00
|
|
|
withoutEnlargement: false,
|
|
|
|
})
|
|
|
|
.greyscale()
|
|
|
|
.normalise()
|
|
|
|
.linear(1.75, -(128 * 1.75) + 128) // 1.75x contrast
|
|
|
|
.flatten({ background: '#000' })
|
|
|
|
.toColorspace('b-w');
|
2023-03-09 11:37:44 -06:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
const stats = await mask.clone().stats();
|
2023-03-09 11:37:44 -06:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
if (stats.entropy < 0.1) {
|
|
|
|
// エントロピーがあまりない場合は404にする
|
|
|
|
throw new StatusError('Skip to provide badge', 404);
|
|
|
|
}
|
2023-03-09 11:37:44 -06:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
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');
|
2023-03-09 11:37:44 -06:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
image = {
|
|
|
|
data: await data.png().toBuffer(),
|
|
|
|
ext: 'png',
|
|
|
|
type: 'image/png',
|
|
|
|
};
|
|
|
|
} else if (file.mime === 'image/svg+xml') {
|
2023-03-12 03:31:52 -05:00
|
|
|
image = this.imageProcessingService.convertToWebpStream(file.path, 2048, 2048);
|
2023-01-26 01:06:29 -06:00
|
|
|
} else if (!file.mime.startsWith('image/') || !FILE_TYPE_BROWSERSAFE.includes(file.mime)) {
|
|
|
|
throw new StatusError('Rejected type', 403, 'Rejected type');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!image) {
|
2024-01-15 03:17:01 -06:00
|
|
|
if (request.headers.range && file.file && file.file.size > 0) {
|
|
|
|
const range = request.headers.range as string;
|
|
|
|
const parts = range.replace(/bytes=/, '').split('-');
|
|
|
|
const start = parseInt(parts[0], 10);
|
|
|
|
let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1;
|
|
|
|
if (end > file.file.size) {
|
|
|
|
end = file.file.size - 1;
|
|
|
|
}
|
|
|
|
const chunksize = end - start + 1;
|
|
|
|
|
|
|
|
image = {
|
|
|
|
data: fs.createReadStream(file.path, {
|
|
|
|
start,
|
|
|
|
end,
|
|
|
|
}),
|
|
|
|
ext: file.ext,
|
|
|
|
type: file.mime,
|
|
|
|
};
|
|
|
|
|
|
|
|
reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`);
|
|
|
|
reply.header('Accept-Ranges', 'bytes');
|
|
|
|
reply.header('Content-Length', chunksize);
|
|
|
|
} else {
|
|
|
|
image = {
|
|
|
|
data: fs.createReadStream(file.path),
|
|
|
|
ext: file.ext,
|
|
|
|
type: file.mime,
|
|
|
|
};
|
|
|
|
}
|
2023-01-26 01:06:29 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
if ('cleanup' in file) {
|
|
|
|
if ('pipe' in image.data && typeof image.data.pipe === 'function') {
|
|
|
|
// image.dataがstreamなら、stream終了後にcleanup
|
|
|
|
image.data.on('end', file.cleanup);
|
|
|
|
image.data.on('close', file.cleanup);
|
|
|
|
} else {
|
|
|
|
// image.dataがstreamでないなら直ちにcleanup
|
|
|
|
file.cleanup();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
reply.header('Content-Type', image.type);
|
2022-12-03 04:42:05 -06:00
|
|
|
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
2023-03-04 01:51:07 -06:00
|
|
|
reply.header('Content-Disposition',
|
|
|
|
contentDisposition(
|
|
|
|
'inline',
|
2023-07-18 21:27:50 -05:00
|
|
|
correctFilename(file.filename, image.ext),
|
|
|
|
),
|
2023-03-04 01:51:07 -06:00
|
|
|
);
|
2023-01-26 01:06:29 -06:00
|
|
|
return image.data;
|
|
|
|
} catch (e) {
|
|
|
|
if ('cleanup' in file) file.cleanup();
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
private async getStreamAndTypeFromUrl(url: string): Promise<
|
2023-08-16 03:51:28 -05:00
|
|
|
{ state: 'remote'; fileRole?: 'thumbnail' | 'webpublic' | 'original'; file?: MiDriveFile; mime: string; ext: string | null; path: string; cleanup: () => void; filename: string; }
|
|
|
|
| { state: 'stored_internal'; fileRole: 'thumbnail' | 'webpublic' | 'original'; file: MiDriveFile; filename: string; mime: string; ext: string | null; path: string; }
|
2023-01-26 01:06:29 -06:00
|
|
|
| '404'
|
|
|
|
| '204'
|
|
|
|
> {
|
|
|
|
if (url.startsWith(`${this.config.url}/files/`)) {
|
|
|
|
const key = url.replace(`${this.config.url}/files/`, '').split('/').shift();
|
|
|
|
if (!key) throw new StatusError('Invalid File Key', 400, 'Invalid File Key');
|
|
|
|
|
|
|
|
return await this.getFileFromKey(key);
|
|
|
|
}
|
|
|
|
|
|
|
|
return await this.downloadAndDetectTypeFromUrl(url);
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
private async downloadAndDetectTypeFromUrl(url: string): Promise<
|
2023-03-04 01:51:07 -06:00
|
|
|
{ state: 'remote' ; mime: string; ext: string | null; path: string; cleanup: () => void; filename: string; }
|
2023-01-26 01:06:29 -06:00
|
|
|
> {
|
|
|
|
const [path, cleanup] = await createTemp();
|
|
|
|
try {
|
2023-03-04 01:51:07 -06:00
|
|
|
const { filename } = await this.downloadService.downloadUrl(url, path);
|
2023-01-26 01:06:29 -06:00
|
|
|
|
|
|
|
const { mime, ext } = await this.fileInfoService.detectType(path);
|
2023-03-09 11:37:44 -06:00
|
|
|
|
2023-01-26 01:06:29 -06:00
|
|
|
return {
|
|
|
|
state: 'remote',
|
|
|
|
mime, ext,
|
|
|
|
path, cleanup,
|
2023-03-04 01:51:07 -06:00
|
|
|
filename,
|
2023-02-16 19:56:59 -06:00
|
|
|
};
|
2023-01-26 01:06:29 -06:00
|
|
|
} catch (e) {
|
|
|
|
cleanup();
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
private async getFileFromKey(key: string): Promise<
|
2023-08-16 03:51:28 -05:00
|
|
|
{ state: 'remote'; fileRole: 'thumbnail' | 'webpublic' | 'original'; file: MiDriveFile; filename: string; url: string; mime: string; ext: string | null; path: string; cleanup: () => void; }
|
|
|
|
| { state: 'stored_internal'; fileRole: 'thumbnail' | 'webpublic' | 'original'; file: MiDriveFile; filename: string; mime: string; ext: string | null; path: string; }
|
2023-01-26 01:06:29 -06:00
|
|
|
| '404'
|
|
|
|
| '204'
|
|
|
|
> {
|
|
|
|
// Fetch drive file
|
|
|
|
const file = await this.driveFilesRepository.createQueryBuilder('file')
|
|
|
|
.where('file.accessKey = :accessKey', { accessKey: key })
|
|
|
|
.orWhere('file.thumbnailAccessKey = :thumbnailAccessKey', { thumbnailAccessKey: key })
|
|
|
|
.orWhere('file.webpublicAccessKey = :webpublicAccessKey', { webpublicAccessKey: key })
|
|
|
|
.getOne();
|
|
|
|
|
|
|
|
if (file == null) return '404';
|
|
|
|
|
|
|
|
const isThumbnail = file.thumbnailAccessKey === key;
|
|
|
|
const isWebpublic = file.webpublicAccessKey === key;
|
|
|
|
|
|
|
|
if (!file.storedInternal) {
|
|
|
|
if (!(file.isLink && file.uri)) return '204';
|
|
|
|
const result = await this.downloadAndDetectTypeFromUrl(file.uri);
|
|
|
|
return {
|
|
|
|
...result,
|
2023-02-03 22:38:51 -06:00
|
|
|
url: file.uri,
|
2023-01-26 01:06:29 -06:00
|
|
|
fileRole: isThumbnail ? 'thumbnail' : isWebpublic ? 'webpublic' : 'original',
|
|
|
|
file,
|
2023-03-04 01:51:07 -06:00
|
|
|
filename: file.name,
|
2023-02-16 19:56:59 -06:00
|
|
|
};
|
2023-01-26 01:06:29 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
const path = this.internalStorageService.resolvePath(key);
|
|
|
|
|
|
|
|
if (isThumbnail || isWebpublic) {
|
|
|
|
const { mime, ext } = await this.fileInfoService.detectType(path);
|
|
|
|
return {
|
|
|
|
state: 'stored_internal',
|
|
|
|
fileRole: isThumbnail ? 'thumbnail' : 'webpublic',
|
|
|
|
file,
|
2023-03-04 01:51:07 -06:00
|
|
|
filename: file.name,
|
2023-01-26 01:06:29 -06:00
|
|
|
mime, ext,
|
|
|
|
path,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
state: 'stored_internal',
|
|
|
|
fileRole: 'original',
|
|
|
|
file,
|
2023-03-04 01:51:07 -06:00
|
|
|
filename: file.name,
|
2023-04-25 12:17:58 -05:00
|
|
|
// 古いファイルは修正前のmimeを持っているのでできるだけ修正してあげる
|
|
|
|
mime: this.fileInfoService.fixMime(file.type),
|
2023-01-26 01:06:29 -06:00
|
|
|
ext: null,
|
|
|
|
path,
|
2023-02-16 19:56:59 -06:00
|
|
|
};
|
2022-09-17 13:27:08 -05:00
|
|
|
}
|
|
|
|
}
|