egirlskey/packages/backend/src/server/FileServerService.ts

183 lines
6.5 KiB
TypeScript
Raw Normal View History

2022-09-17 18:27:08 +00:00
import * as fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
import { Inject, Injectable } from '@nestjs/common';
import fastifyStatic from '@fastify/static';
2022-09-17 18:27:08 +00:00
import rename from 'rename';
2022-09-20 20:33:11 +00:00
import type { Config } from '@/config.js';
import type { DriveFilesRepository } from '@/models/index.js';
2022-09-17 18:27:08 +00: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 14:07:41 +00:00
import type Logger from '@/logger.js';
2022-09-17 18:27:08 +00:00
import { DownloadService } from '@/core/DownloadService.js';
import { ImageProcessingService } from '@/core/ImageProcessingService.js';
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 14:07:41 +00:00
import { LoggerService } from '@/core/LoggerService.js';
import { bindThis } from '@/decorators.js';
import type { FastifyInstance, FastifyRequest, FastifyReply, FastifyPluginOptions } from 'fastify';
2022-09-17 18:27:08 +00:00
const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename);
const assets = `${_dirname}/../../server/file/assets/`;
@Injectable()
export class FileServerService {
2022-09-18 18:11:50 +00:00
private logger: Logger;
2022-09-18 14:07:41 +00:00
2022-09-17 18:27:08 +00: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 14:07:41 +00:00
private loggerService: LoggerService,
2022-09-17 18:27:08 +00:00
) {
2022-09-18 18:11:50 +00:00
this.logger = this.loggerService.getLogger('server', 'gray', false);
//this.createServer = this.createServer.bind(this);
2022-09-17 18:27:08 +00:00
}
@bindThis
public commonReadableHandlerGenerator(reply: FastifyReply) {
return (err: Error): void => {
this.logger.error(err);
reply.code(500);
reply.header('Cache-Control', 'max-age=300');
2022-09-18 14:07:41 +00:00
};
}
@bindThis
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-17 18:27:08 +00:00
});
fastify.register(fastifyStatic, {
root: _dirname,
serve: false,
});
2022-09-17 18:27:08 +00:00
fastify.get('/app-default.jpg', (request, reply) => {
2022-09-17 18:27:08 +00:00
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);
2022-09-17 18:27:08 +00:00
});
fastify.get<{ Params: { key: string; } }>('/:key', async (request, reply) => await this.sendDriveFile(request, reply));
fastify.get<{ Params: { key: string; } }>('/:key/*', async (request, reply) => await this.sendDriveFile(request, reply));
2022-09-17 18:27:08 +00:00
done();
2022-09-17 18:27:08 +00:00
}
@bindThis
private async sendDriveFile(request: FastifyRequest<{ Params: { key: string; } }>, reply: FastifyReply) {
const key = request.params.key;
2022-09-17 18:27:08 +00:00
// 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) {
reply.code(404);
reply.header('Cache-Control', 'max-age=86400');
return reply.sendFile('/dummy.png', assets);
2022-09-17 18:27:08 +00:00
}
const isThumbnail = file.thumbnailAccessKey === key;
const isWebpublic = file.webpublicAccessKey === key;
if (!file.storedInternal) {
if (file.isLink && file.uri) { // 期限切れリモートファイル
const [path, cleanup] = await createTemp();
try {
await this.downloadService.downloadUrl(file.uri, path);
const { mime, ext } = await this.fileInfoService.detectType(path);
const convertFile = async () => {
if (isThumbnail) {
if (['image/jpeg', 'image/webp', 'image/avif', 'image/png', 'image/svg+xml'].includes(mime)) {
2022-09-17 18:27:08 +00:00
return await this.imageProcessingService.convertToWebp(path, 498, 280);
} else if (mime.startsWith('video/')) {
return await this.videoProcessingService.generateVideoThumbnail(path);
}
}
if (isWebpublic) {
if (['image/svg+xml'].includes(mime)) {
return await this.imageProcessingService.convertToPng(path, 2048, 2048);
}
}
return {
data: fs.readFileSync(path),
ext,
type: mime,
};
};
const image = await convertFile();
reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(image.type) ? image.type : 'application/octet-stream');
reply.header('Cache-Control', 'max-age=31536000, immutable');
return image.data;
2022-09-17 18:27:08 +00:00
} catch (err) {
2022-09-18 18:11:50 +00:00
this.logger.error(`${err}`);
2022-09-17 18:27:08 +00:00
if (err instanceof StatusError && err.isClientError) {
reply.code(err.statusCode);
reply.header('Cache-Control', 'max-age=86400');
2022-09-17 18:27:08 +00:00
} else {
reply.code(500);
reply.header('Cache-Control', 'max-age=300');
2022-09-17 18:27:08 +00:00
}
} finally {
cleanup();
}
return;
}
reply.code(204);
reply.header('Cache-Control', 'max-age=86400');
2022-09-17 18:27:08 +00:00
return;
}
if (isThumbnail || isWebpublic) {
const { mime, ext } = await this.fileInfoService.detectType(this.internalStorageService.resolvePath(key));
const filename = rename(file.name, {
suffix: isThumbnail ? '-thumb' : '-web',
extname: ext ? `.${ext}` : undefined,
}).toString();
reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(mime) ? mime : 'application/octet-stream');
reply.header('Cache-Control', 'max-age=31536000, immutable');
reply.header('Content-Disposition', contentDisposition('inline', filename));
return this.internalStorageService.read(key);
2022-09-17 18:27:08 +00:00
} else {
const readable = this.internalStorageService.read(file.accessKey!);
readable.on('error', this.commonReadableHandlerGenerator(reply));
reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(file.type) ? file.type : 'application/octet-stream');
reply.header('Cache-Control', 'max-age=31536000, immutable');
reply.header('Content-Disposition', contentDisposition('inline', file.name));
return readable;
2022-09-17 18:27:08 +00:00
}
}
}