2023-07-27 14:31:52 +09:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: syuilo and other misskey contributors
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2023-07-15 18:39:38 +09:00
|
|
|
import { randomUUID } from 'node:crypto';
|
2022-09-18 03:27:08 +09:00
|
|
|
import * as fs from 'node:fs';
|
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import sharp from 'sharp';
|
2023-03-11 14:11:40 +09:00
|
|
|
import { sharpBmp } from 'sharp-read-bmp';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { IsNull } from 'typeorm';
|
2023-03-23 13:48:14 +09:00
|
|
|
import { DeleteObjectCommandInput, PutObjectCommandInput, NoSuchKey } from '@aws-sdk/client-s3';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { DI } from '@/di-symbols.js';
|
2023-09-15 14:28:29 +09:00
|
|
|
import type { DriveFilesRepository, UsersRepository, DriveFoldersRepository, UserProfilesRepository } from '@/models/_.js';
|
2022-09-21 05:33:11 +09:00
|
|
|
import type { Config } from '@/config.js';
|
2022-09-18 23:30:08 +09:00
|
|
|
import Logger from '@/logger.js';
|
2023-09-20 11:33:36 +09:00
|
|
|
import type { MiRemoteUser, MiUser } from '@/models/User.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { MetaService } from '@/core/MetaService.js';
|
2023-09-20 11:33:36 +09:00
|
|
|
import { MiDriveFile } from '@/models/DriveFile.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { IdService } from '@/core/IdService.js';
|
|
|
|
import { isDuplicateKeyValueError } from '@/misc/is-duplicate-key-value-error.js';
|
|
|
|
import { FILE_TYPE_BROWSERSAFE } from '@/const.js';
|
|
|
|
import { IdentifiableError } from '@/misc/identifiable-error.js';
|
|
|
|
import { contentDisposition } from '@/misc/content-disposition.js';
|
|
|
|
import { GlobalEventService } from '@/core/GlobalEventService.js';
|
|
|
|
import { VideoProcessingService } from '@/core/VideoProcessingService.js';
|
|
|
|
import { ImageProcessingService } from '@/core/ImageProcessingService.js';
|
|
|
|
import type { IImage } from '@/core/ImageProcessingService.js';
|
|
|
|
import { QueueService } from '@/core/QueueService.js';
|
2023-09-20 11:33:36 +09:00
|
|
|
import type { MiDriveFolder } from '@/models/DriveFolder.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { createTemp } from '@/misc/create-temp.js';
|
|
|
|
import DriveChart from '@/core/chart/charts/drive.js';
|
|
|
|
import PerUserDriveChart from '@/core/chart/charts/per-user-drive.js';
|
|
|
|
import InstanceChart from '@/core/chart/charts/instance.js';
|
|
|
|
import { DownloadService } from '@/core/DownloadService.js';
|
|
|
|
import { S3Service } from '@/core/S3Service.js';
|
|
|
|
import { InternalStorageService } from '@/core/InternalStorageService.js';
|
2022-12-04 10:16:03 +09:00
|
|
|
import { DriveFileEntityService } from '@/core/entities/DriveFileEntityService.js';
|
|
|
|
import { UserEntityService } from '@/core/entities/UserEntityService.js';
|
|
|
|
import { FileInfoService } from '@/core/FileInfoService.js';
|
2022-12-04 17:05:32 +09:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2023-01-12 21:02:26 +09:00
|
|
|
import { RoleService } from '@/core/RoleService.js';
|
2023-03-04 16:51:07 +09:00
|
|
|
import { correctFilename } from '@/misc/correct-filename.js';
|
2023-03-11 14:11:40 +09:00
|
|
|
import { isMimeImage } from '@/misc/is-mime-image.js';
|
2023-09-23 18:28:16 +09:00
|
|
|
import { ModerationLogService } from '@/core/ModerationLogService.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
type AddFileArgs = {
|
|
|
|
/** User who wish to add file */
|
2023-08-16 17:51:28 +09:00
|
|
|
user: { id: MiUser['id']; host: MiUser['host'] } | null;
|
2022-09-18 03:27:08 +09:00
|
|
|
/** File path */
|
|
|
|
path: string;
|
|
|
|
/** Name */
|
|
|
|
name?: string | null;
|
|
|
|
/** Comment */
|
|
|
|
comment?: string | null;
|
|
|
|
/** Folder ID */
|
|
|
|
folderId?: any;
|
|
|
|
/** If set to true, forcibly upload the file even if there is a file with the same hash. */
|
|
|
|
force?: boolean;
|
|
|
|
/** Do not save file to local */
|
|
|
|
isLink?: boolean;
|
|
|
|
/** URL of source (URLからアップロードされた場合(ローカル/リモート)の元URL) */
|
|
|
|
url?: string | null;
|
|
|
|
/** URL of source (リモートインスタンスのURLからアップロードされた場合の元URL) */
|
|
|
|
uri?: string | null;
|
|
|
|
/** Mark file as sensitive */
|
|
|
|
sensitive?: boolean | null;
|
2023-04-14 14:35:38 +09:00
|
|
|
/** Extension to force */
|
|
|
|
ext?: string | null;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
requestIp?: string | null;
|
|
|
|
requestHeaders?: Record<string, string> | null;
|
|
|
|
};
|
|
|
|
|
|
|
|
type UploadFromUrlArgs = {
|
|
|
|
url: string;
|
2023-08-16 17:51:28 +09:00
|
|
|
user: { id: MiUser['id']; host: MiUser['host'] } | null;
|
|
|
|
folderId?: MiDriveFolder['id'] | null;
|
2022-09-18 03:27:08 +09:00
|
|
|
uri?: string | null;
|
|
|
|
sensitive?: boolean;
|
|
|
|
force?: boolean;
|
|
|
|
isLink?: boolean;
|
|
|
|
comment?: string | null;
|
|
|
|
requestIp?: string | null;
|
|
|
|
requestHeaders?: Record<string, string> | null;
|
|
|
|
};
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class DriveService {
|
2023-09-24 16:24:13 +09:00
|
|
|
public static NoSuchFolderError = class extends Error {};
|
|
|
|
public static InvalidFileNameError = class extends Error {};
|
|
|
|
public static CannotUnmarkSensitiveError = class extends Error {};
|
2022-09-19 03:11:50 +09:00
|
|
|
private registerLogger: Logger;
|
|
|
|
private downloaderLogger: Logger;
|
2023-03-23 13:48:14 +09:00
|
|
|
private deleteLogger: Logger;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.config)
|
|
|
|
private config: Config,
|
|
|
|
|
|
|
|
@Inject(DI.usersRepository)
|
|
|
|
private usersRepository: UsersRepository,
|
|
|
|
|
|
|
|
@Inject(DI.userProfilesRepository)
|
|
|
|
private userProfilesRepository: UserProfilesRepository,
|
|
|
|
|
|
|
|
@Inject(DI.driveFilesRepository)
|
|
|
|
private driveFilesRepository: DriveFilesRepository,
|
|
|
|
|
|
|
|
@Inject(DI.driveFoldersRepository)
|
|
|
|
private driveFoldersRepository: DriveFoldersRepository,
|
|
|
|
|
|
|
|
private fileInfoService: FileInfoService,
|
|
|
|
private userEntityService: UserEntityService,
|
|
|
|
private driveFileEntityService: DriveFileEntityService,
|
|
|
|
private idService: IdService,
|
|
|
|
private metaService: MetaService,
|
|
|
|
private downloadService: DownloadService,
|
|
|
|
private internalStorageService: InternalStorageService,
|
|
|
|
private s3Service: S3Service,
|
|
|
|
private imageProcessingService: ImageProcessingService,
|
|
|
|
private videoProcessingService: VideoProcessingService,
|
|
|
|
private globalEventService: GlobalEventService,
|
|
|
|
private queueService: QueueService,
|
2023-01-12 21:02:26 +09:00
|
|
|
private roleService: RoleService,
|
2023-09-23 18:28:16 +09:00
|
|
|
private moderationLogService: ModerationLogService,
|
2022-09-18 03:27:08 +09:00
|
|
|
private driveChart: DriveChart,
|
|
|
|
private perUserDriveChart: PerUserDriveChart,
|
|
|
|
private instanceChart: InstanceChart,
|
|
|
|
) {
|
|
|
|
const logger = new Logger('drive', 'blue');
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger = logger.createSubLogger('register', 'yellow');
|
|
|
|
this.downloaderLogger = logger.createSubLogger('downloader');
|
2023-03-23 13:48:14 +09:00
|
|
|
this.deleteLogger = logger.createSubLogger('delete');
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
/***
|
|
|
|
* Save file
|
|
|
|
* @param path Path for original
|
2023-04-14 14:35:38 +09:00
|
|
|
* @param name Name for original (should be extention corrected)
|
2022-09-18 03:27:08 +09:00
|
|
|
* @param type Content-Type for original
|
|
|
|
* @param hash Hash for original
|
|
|
|
* @param size Size for original
|
|
|
|
*/
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2023-08-16 17:51:28 +09:00
|
|
|
private async save(file: MiDriveFile, path: string, name: string, type: string, hash: string, size: number): Promise<MiDriveFile> {
|
2022-09-18 03:27:08 +09:00
|
|
|
// thunbnail, webpublic を必要なら生成
|
|
|
|
const alts = await this.generateAlts(path, type, !file.uri);
|
|
|
|
|
|
|
|
const meta = await this.metaService.fetch();
|
|
|
|
|
|
|
|
if (meta.useObjectStorage) {
|
|
|
|
//#region ObjectStorage params
|
|
|
|
let [ext] = (name.match(/\.([a-zA-Z0-9_-]+)$/) ?? ['']);
|
|
|
|
|
|
|
|
if (ext === '') {
|
|
|
|
if (type === 'image/jpeg') ext = '.jpg';
|
|
|
|
if (type === 'image/png') ext = '.png';
|
|
|
|
if (type === 'image/webp') ext = '.webp';
|
2022-12-08 14:49:49 +09:00
|
|
|
if (type === 'image/avif') ext = '.avif';
|
2022-09-18 03:27:08 +09:00
|
|
|
if (type === 'image/apng') ext = '.apng';
|
|
|
|
if (type === 'image/vnd.mozilla.apng') ext = '.apng';
|
|
|
|
}
|
|
|
|
|
|
|
|
// 拡張子からContent-Typeを設定してそうな挙動を示すオブジェクトストレージ (upcloud?) も存在するので、
|
2023-04-14 14:35:38 +09:00
|
|
|
// 許可されているファイル形式でしかURLに拡張子をつけない
|
2022-09-18 03:27:08 +09:00
|
|
|
if (!FILE_TYPE_BROWSERSAFE.includes(type)) {
|
|
|
|
ext = '';
|
|
|
|
}
|
|
|
|
|
|
|
|
const baseUrl = meta.objectStorageBaseUrl
|
2022-09-20 05:32:18 +09:00
|
|
|
?? `${ meta.objectStorageUseSSL ? 'https' : 'http' }://${ meta.objectStorageEndpoint }${ meta.objectStoragePort ? `:${meta.objectStoragePort}` : '' }/${ meta.objectStorageBucket }`;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
// for original
|
2023-07-15 18:39:38 +09:00
|
|
|
const key = `${meta.objectStoragePrefix}/${randomUUID()}${ext}`;
|
2022-09-18 03:27:08 +09:00
|
|
|
const url = `${ baseUrl }/${ key }`;
|
|
|
|
|
|
|
|
// for alts
|
|
|
|
let webpublicKey: string | null = null;
|
|
|
|
let webpublicUrl: string | null = null;
|
|
|
|
let thumbnailKey: string | null = null;
|
|
|
|
let thumbnailUrl: string | null = null;
|
|
|
|
//#endregion
|
|
|
|
|
|
|
|
//#region Uploads
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info(`uploading original: ${key}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
const uploads = [
|
2023-04-14 14:35:38 +09:00
|
|
|
this.upload(key, fs.createReadStream(path), type, null, name),
|
2022-09-18 03:27:08 +09:00
|
|
|
];
|
|
|
|
|
|
|
|
if (alts.webpublic) {
|
2023-07-15 18:39:38 +09:00
|
|
|
webpublicKey = `${meta.objectStoragePrefix}/webpublic-${randomUUID()}.${alts.webpublic.ext}`;
|
2022-09-18 03:27:08 +09:00
|
|
|
webpublicUrl = `${ baseUrl }/${ webpublicKey }`;
|
|
|
|
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info(`uploading webpublic: ${webpublicKey}`);
|
2023-03-04 16:51:07 +09:00
|
|
|
uploads.push(this.upload(webpublicKey, alts.webpublic.data, alts.webpublic.type, alts.webpublic.ext, name));
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
if (alts.thumbnail) {
|
2023-07-15 18:39:38 +09:00
|
|
|
thumbnailKey = `${meta.objectStoragePrefix}/thumbnail-${randomUUID()}.${alts.thumbnail.ext}`;
|
2022-09-18 03:27:08 +09:00
|
|
|
thumbnailUrl = `${ baseUrl }/${ thumbnailKey }`;
|
|
|
|
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info(`uploading thumbnail: ${thumbnailKey}`);
|
2023-04-14 14:35:38 +09:00
|
|
|
uploads.push(this.upload(thumbnailKey, alts.thumbnail.data, alts.thumbnail.type, alts.thumbnail.ext, `${name}.thumbnail`));
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
await Promise.all(uploads);
|
|
|
|
//#endregion
|
|
|
|
|
|
|
|
file.url = url;
|
|
|
|
file.thumbnailUrl = thumbnailUrl;
|
|
|
|
file.webpublicUrl = webpublicUrl;
|
|
|
|
file.accessKey = key;
|
|
|
|
file.thumbnailAccessKey = thumbnailKey;
|
|
|
|
file.webpublicAccessKey = webpublicKey;
|
|
|
|
file.webpublicType = alts.webpublic?.type ?? null;
|
|
|
|
file.name = name;
|
|
|
|
file.type = type;
|
|
|
|
file.md5 = hash;
|
|
|
|
file.size = size;
|
|
|
|
file.storedInternal = false;
|
|
|
|
|
|
|
|
return await this.driveFilesRepository.insert(file).then(x => this.driveFilesRepository.findOneByOrFail(x.identifiers[0]));
|
|
|
|
} else { // use internal storage
|
2023-07-15 18:39:38 +09:00
|
|
|
const accessKey = randomUUID();
|
|
|
|
const thumbnailAccessKey = 'thumbnail-' + randomUUID();
|
|
|
|
const webpublicAccessKey = 'webpublic-' + randomUUID();
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
const url = this.internalStorageService.saveFromPath(accessKey, path);
|
|
|
|
|
|
|
|
let thumbnailUrl: string | null = null;
|
|
|
|
let webpublicUrl: string | null = null;
|
|
|
|
|
|
|
|
if (alts.thumbnail) {
|
|
|
|
thumbnailUrl = this.internalStorageService.saveFromBuffer(thumbnailAccessKey, alts.thumbnail.data);
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info(`thumbnail stored: ${thumbnailAccessKey}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
if (alts.webpublic) {
|
|
|
|
webpublicUrl = this.internalStorageService.saveFromBuffer(webpublicAccessKey, alts.webpublic.data);
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info(`web stored: ${webpublicAccessKey}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
file.storedInternal = true;
|
|
|
|
file.url = url;
|
|
|
|
file.thumbnailUrl = thumbnailUrl;
|
|
|
|
file.webpublicUrl = webpublicUrl;
|
|
|
|
file.accessKey = accessKey;
|
|
|
|
file.thumbnailAccessKey = thumbnailAccessKey;
|
|
|
|
file.webpublicAccessKey = webpublicAccessKey;
|
|
|
|
file.webpublicType = alts.webpublic?.type ?? null;
|
|
|
|
file.name = name;
|
|
|
|
file.type = type;
|
|
|
|
file.md5 = hash;
|
|
|
|
file.size = size;
|
|
|
|
|
|
|
|
return await this.driveFilesRepository.insert(file).then(x => this.driveFilesRepository.findOneByOrFail(x.identifiers[0]));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate webpublic, thumbnail, etc
|
|
|
|
* @param path Path for original
|
|
|
|
* @param type Content-Type for original
|
|
|
|
* @param generateWeb Generate webpublic or not
|
|
|
|
*/
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-09-18 03:27:08 +09:00
|
|
|
public async generateAlts(path: string, type: string, generateWeb: boolean) {
|
|
|
|
if (type.startsWith('video/')) {
|
2023-02-12 09:13:47 +09:00
|
|
|
if (this.config.videoThumbnailGenerator != null) {
|
|
|
|
// videoThumbnailGeneratorが指定されていたら動画サムネイル生成はスキップ
|
|
|
|
return {
|
|
|
|
webpublic: null,
|
|
|
|
thumbnail: null,
|
2023-02-13 15:50:22 +09:00
|
|
|
};
|
2023-02-12 09:13:47 +09:00
|
|
|
}
|
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
try {
|
|
|
|
const thumbnail = await this.videoProcessingService.generateVideoThumbnail(path);
|
|
|
|
return {
|
|
|
|
webpublic: null,
|
|
|
|
thumbnail,
|
|
|
|
};
|
|
|
|
} catch (err) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.warn(`GenerateVideoThumbnail failed: ${err}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
return {
|
|
|
|
webpublic: null,
|
|
|
|
thumbnail: null,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-11 14:11:40 +09:00
|
|
|
if (!isMimeImage(type, 'sharp-convertible-image-with-bmp')) {
|
|
|
|
this.registerLogger.debug('web image and thumbnail not created (cannot convert by sharp)');
|
2022-09-18 03:27:08 +09:00
|
|
|
return {
|
|
|
|
webpublic: null,
|
|
|
|
thumbnail: null,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
let img: sharp.Sharp | null = null;
|
|
|
|
let satisfyWebpublic: boolean;
|
2023-03-11 14:11:40 +09:00
|
|
|
let isAnimated: boolean;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
try {
|
2023-03-11 14:11:40 +09:00
|
|
|
img = await sharpBmp(path, type);
|
2022-09-18 03:27:08 +09:00
|
|
|
const metadata = await img.metadata();
|
2023-03-11 14:11:40 +09:00
|
|
|
isAnimated = !!(metadata.pages && metadata.pages > 1);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
satisfyWebpublic = !!(
|
2023-03-11 14:11:40 +09:00
|
|
|
type !== 'image/svg+xml' && // security reason
|
2023-03-12 17:31:52 +09:00
|
|
|
type !== 'image/avif' && // not supported by Mastodon and MS Edge
|
2022-09-20 05:32:18 +09:00
|
|
|
!(metadata.exif ?? metadata.iptc ?? metadata.xmp ?? metadata.tifftagPhotoshop) &&
|
2022-09-18 03:27:08 +09:00
|
|
|
metadata.width && metadata.width <= 2048 &&
|
|
|
|
metadata.height && metadata.height <= 2048
|
|
|
|
);
|
|
|
|
} catch (err) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.warn(`sharp failed: ${err}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
return {
|
|
|
|
webpublic: null,
|
|
|
|
thumbnail: null,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
// #region webpublic
|
|
|
|
let webpublic: IImage | null = null;
|
|
|
|
|
2023-03-11 14:11:40 +09:00
|
|
|
if (generateWeb && !satisfyWebpublic && !isAnimated) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info('creating web image');
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
try {
|
2023-03-11 14:11:40 +09:00
|
|
|
if (['image/jpeg', 'image/webp', 'image/avif'].includes(type)) {
|
2023-03-10 09:37:22 +09:00
|
|
|
webpublic = await this.imageProcessingService.convertSharpToWebp(img, 2048, 2048);
|
2023-03-11 14:11:40 +09:00
|
|
|
} else if (['image/png', 'image/bmp', 'image/svg+xml'].includes(type)) {
|
2022-09-18 03:27:08 +09:00
|
|
|
webpublic = await this.imageProcessingService.convertSharpToPng(img, 2048, 2048);
|
|
|
|
} else {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.debug('web image not created (not an required image)');
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
} catch (err) {
|
2023-08-05 13:56:33 +09:00
|
|
|
this.registerLogger.warn('web image not created (an error occurred)', err as Error);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
} else {
|
2022-09-19 03:11:50 +09:00
|
|
|
if (satisfyWebpublic) this.registerLogger.info('web image not created (original satisfies webpublic)');
|
2023-03-11 14:11:40 +09:00
|
|
|
else if (isAnimated) this.registerLogger.info('web image not created (animated image)');
|
2022-09-19 03:11:50 +09:00
|
|
|
else this.registerLogger.info('web image not created (from remote)');
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
// #endregion webpublic
|
|
|
|
|
|
|
|
// #region thumbnail
|
|
|
|
let thumbnail: IImage | null = null;
|
|
|
|
|
|
|
|
try {
|
2023-03-11 14:11:40 +09:00
|
|
|
if (isAnimated) {
|
|
|
|
thumbnail = await this.imageProcessingService.convertSharpToWebp(sharp(path, { animated: true }), 374, 317, { alphaQuality: 70 });
|
2022-09-18 03:27:08 +09:00
|
|
|
} else {
|
2023-03-12 17:31:52 +09:00
|
|
|
thumbnail = await this.imageProcessingService.convertSharpToWebp(img, 498, 422);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
} catch (err) {
|
2023-08-05 13:56:33 +09:00
|
|
|
this.registerLogger.warn('thumbnail not created (an error occurred)', err as Error);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
// #endregion thumbnail
|
|
|
|
|
|
|
|
return {
|
|
|
|
webpublic,
|
|
|
|
thumbnail,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Upload to ObjectStorage
|
|
|
|
*/
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2023-03-04 16:51:07 +09:00
|
|
|
private async upload(key: string, stream: fs.ReadStream | Buffer, type: string, ext?: string | null, filename?: string) {
|
2022-09-18 03:27:08 +09:00
|
|
|
if (type === 'image/apng') type = 'image/png';
|
|
|
|
if (!FILE_TYPE_BROWSERSAFE.includes(type)) type = 'application/octet-stream';
|
|
|
|
|
|
|
|
const meta = await this.metaService.fetch();
|
|
|
|
|
|
|
|
const params = {
|
|
|
|
Bucket: meta.objectStorageBucket,
|
|
|
|
Key: key,
|
|
|
|
Body: stream,
|
|
|
|
ContentType: type,
|
|
|
|
CacheControl: 'max-age=31536000, immutable',
|
2023-03-23 13:48:14 +09:00
|
|
|
} as PutObjectCommandInput;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
2023-03-04 16:51:07 +09:00
|
|
|
if (filename) params.ContentDisposition = contentDisposition(
|
|
|
|
'inline',
|
|
|
|
// 拡張子からContent-Typeを設定してそうな挙動を示すオブジェクトストレージ (upcloud?) も存在するので、
|
|
|
|
// 許可されているファイル形式でしか拡張子をつけない
|
|
|
|
ext ? correctFilename(filename, ext) : filename,
|
|
|
|
);
|
2022-09-18 03:27:08 +09:00
|
|
|
if (meta.objectStorageSetPublicRead) params.ACL = 'public-read';
|
|
|
|
|
2023-03-23 13:48:14 +09:00
|
|
|
await this.s3Service.upload(meta, params)
|
2023-01-12 21:03:02 +09:00
|
|
|
.then(
|
|
|
|
result => {
|
2023-03-23 13:48:14 +09:00
|
|
|
if ('Bucket' in result) { // CompleteMultipartUploadCommandOutput
|
2023-01-12 21:03:02 +09:00
|
|
|
this.registerLogger.debug(`Uploaded: ${result.Bucket}/${result.Key} => ${result.Location}`);
|
2023-03-23 13:48:14 +09:00
|
|
|
} else { // AbortMultipartUploadCommandOutput
|
|
|
|
this.registerLogger.error(`Upload Result Aborted: key = ${key}, filename = ${filename}`);
|
2023-01-12 21:03:02 +09:00
|
|
|
}
|
2023-03-23 13:48:14 +09:00
|
|
|
})
|
|
|
|
.catch(
|
2023-01-12 21:03:02 +09:00
|
|
|
err => {
|
|
|
|
this.registerLogger.error(`Upload Failed: key = ${key}, filename = ${filename}`, err);
|
2023-01-13 11:14:07 +09:00
|
|
|
},
|
2023-01-12 21:03:02 +09:00
|
|
|
);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2023-04-13 18:48:38 +09:00
|
|
|
// Expire oldest file (without avatar or banner) of remote user
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2023-08-16 17:51:28 +09:00
|
|
|
private async expireOldFile(user: MiRemoteUser, driveCapacity: number) {
|
2022-09-18 03:27:08 +09:00
|
|
|
const q = this.driveFilesRepository.createQueryBuilder('file')
|
|
|
|
.where('file.userId = :userId', { userId: user.id })
|
|
|
|
.andWhere('file.isLink = FALSE');
|
|
|
|
|
|
|
|
if (user.avatarId) {
|
|
|
|
q.andWhere('file.id != :avatarId', { avatarId: user.avatarId });
|
|
|
|
}
|
|
|
|
|
|
|
|
if (user.bannerId) {
|
|
|
|
q.andWhere('file.id != :bannerId', { bannerId: user.bannerId });
|
|
|
|
}
|
|
|
|
|
2023-10-06 09:32:09 +09:00
|
|
|
if (user.backgroundId) {
|
|
|
|
q.andWhere('file.id != :backgroundId', { backgroundId: user.backgroundId });
|
|
|
|
}
|
|
|
|
|
2023-04-13 18:48:38 +09:00
|
|
|
//This selete is hard coded, be careful if change database schema
|
|
|
|
q.addSelect('SUM("file"."size") OVER (ORDER BY "file"."id" DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)', 'acc_usage');
|
2022-09-18 03:27:08 +09:00
|
|
|
q.orderBy('file.id', 'ASC');
|
|
|
|
|
2023-04-13 18:48:38 +09:00
|
|
|
const fileList = await q.getRawMany();
|
|
|
|
const exceedFileIds = fileList.filter((x: any) => x.acc_usage > driveCapacity).map((x: any) => x.file_id);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
2023-04-13 18:48:38 +09:00
|
|
|
for (const fileId of exceedFileIds) {
|
|
|
|
const file = await this.driveFilesRepository.findOneBy({ id: fileId });
|
2023-04-13 20:27:05 +09:00
|
|
|
if (file == null) continue;
|
2023-04-13 18:48:38 +09:00
|
|
|
this.deleteFile(file, true);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add file to drive
|
|
|
|
*
|
|
|
|
*/
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-09-18 03:27:08 +09:00
|
|
|
public async addFile({
|
|
|
|
user,
|
|
|
|
path,
|
|
|
|
name = null,
|
|
|
|
comment = null,
|
|
|
|
folderId = null,
|
|
|
|
force = false,
|
|
|
|
isLink = false,
|
|
|
|
url = null,
|
|
|
|
uri = null,
|
|
|
|
sensitive = null,
|
|
|
|
requestIp = null,
|
|
|
|
requestHeaders = null,
|
2023-04-14 14:35:38 +09:00
|
|
|
ext = null,
|
2023-08-16 17:51:28 +09:00
|
|
|
}: AddFileArgs): Promise<MiDriveFile> {
|
2022-09-18 03:27:08 +09:00
|
|
|
let skipNsfwCheck = false;
|
|
|
|
const instance = await this.metaService.fetch();
|
2023-05-05 14:18:06 +09:00
|
|
|
const userRoleNSFW = user && (await this.roleService.getUserPolicies(user.id)).alwaysMarkNsfw;
|
|
|
|
if (user == null) {
|
|
|
|
skipNsfwCheck = true;
|
|
|
|
} else if (userRoleNSFW) {
|
|
|
|
skipNsfwCheck = true;
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
if (instance.sensitiveMediaDetection === 'none') skipNsfwCheck = true;
|
|
|
|
if (user && instance.sensitiveMediaDetection === 'local' && this.userEntityService.isRemoteUser(user)) skipNsfwCheck = true;
|
|
|
|
if (user && instance.sensitiveMediaDetection === 'remote' && this.userEntityService.isLocalUser(user)) skipNsfwCheck = true;
|
|
|
|
|
|
|
|
const info = await this.fileInfoService.getFileInfo(path, {
|
|
|
|
skipSensitiveDetection: skipNsfwCheck,
|
|
|
|
sensitiveThreshold: // 感度が高いほどしきい値は低くすることになる
|
|
|
|
instance.sensitiveMediaDetectionSensitivity === 'veryHigh' ? 0.1 :
|
|
|
|
instance.sensitiveMediaDetectionSensitivity === 'high' ? 0.3 :
|
|
|
|
instance.sensitiveMediaDetectionSensitivity === 'low' ? 0.7 :
|
|
|
|
instance.sensitiveMediaDetectionSensitivity === 'veryLow' ? 0.9 :
|
|
|
|
0.5,
|
|
|
|
sensitiveThresholdForPorn: 0.75,
|
|
|
|
enableSensitiveMediaDetectionForVideos: instance.enableSensitiveMediaDetectionForVideos,
|
|
|
|
});
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info(`${JSON.stringify(info)}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
// 現状 false positive が多すぎて実用に耐えない
|
|
|
|
//if (info.porn && instance.disallowUploadWhenPredictedAsPorn) {
|
|
|
|
// throw new IdentifiableError('282f77bf-5816-4f72-9264-aa14d8261a21', 'Detected as porn.');
|
|
|
|
//}
|
|
|
|
|
|
|
|
// detect name
|
2023-03-04 16:51:07 +09:00
|
|
|
const detectedName = correctFilename(
|
|
|
|
// DriveFile.nameは256文字, validateFileNameは200文字制限であるため、
|
|
|
|
// extを付加してデータベースの文字数制限に当たることはまずない
|
|
|
|
(name && this.driveFileEntityService.validateFileName(name)) ? name : 'untitled',
|
2023-04-14 14:35:38 +09:00
|
|
|
ext ?? info.type.ext,
|
2023-03-04 16:51:07 +09:00
|
|
|
);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
if (user && !force) {
|
|
|
|
// Check if there is a file with the same hash
|
|
|
|
const much = await this.driveFilesRepository.findOneBy({
|
|
|
|
md5: info.md5,
|
|
|
|
userId: user.id,
|
|
|
|
});
|
|
|
|
|
|
|
|
if (much) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info(`file with same hash is found: ${much.id}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
return much;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-12 21:03:02 +09:00
|
|
|
this.registerLogger.debug(`ADD DRIVE FILE: user ${user?.id ?? 'not set'}, name ${detectedName}, tmp ${path}`);
|
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
//#region Check drive usage
|
|
|
|
if (user && !isLink) {
|
|
|
|
const usage = await this.driveFileEntityService.calcDriveUsageOf(user);
|
2023-04-13 18:48:38 +09:00
|
|
|
const isLocalUser = this.userEntityService.isLocalUser(user);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
2023-01-15 20:52:53 +09:00
|
|
|
const policies = await this.roleService.getUserPolicies(user.id);
|
|
|
|
const driveCapacity = 1024 * 1024 * policies.driveCapacityMb;
|
2023-01-13 11:14:07 +09:00
|
|
|
this.registerLogger.debug('drive capacity override applied');
|
|
|
|
this.registerLogger.debug(`overrideCap: ${driveCapacity}bytes, usage: ${usage}bytes, u+s: ${usage + info.size}bytes`);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
// If usage limit exceeded
|
2023-04-13 18:48:38 +09:00
|
|
|
if (driveCapacity < usage + info.size) {
|
|
|
|
if (isLocalUser) {
|
2022-09-18 03:27:08 +09:00
|
|
|
throw new IdentifiableError('c6244ed2-a39a-4e1c-bf93-f0fbd7764fa6', 'No free space.');
|
|
|
|
}
|
2023-08-16 17:51:28 +09:00
|
|
|
await this.expireOldFile(await this.usersRepository.findOneByOrFail({ id: user.id }) as MiRemoteUser, driveCapacity - info.size);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
//#endregion
|
|
|
|
|
|
|
|
const fetchFolder = async () => {
|
|
|
|
if (!folderId) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const driveFolder = await this.driveFoldersRepository.findOneBy({
|
|
|
|
id: folderId,
|
|
|
|
userId: user ? user.id : IsNull(),
|
|
|
|
});
|
|
|
|
|
|
|
|
if (driveFolder == null) throw new Error('folder-not-found');
|
|
|
|
|
|
|
|
return driveFolder;
|
|
|
|
};
|
|
|
|
|
|
|
|
const properties: {
|
2023-03-23 13:48:14 +09:00
|
|
|
width?: number;
|
|
|
|
height?: number;
|
|
|
|
orientation?: number;
|
|
|
|
} = {};
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
if (info.width) {
|
|
|
|
properties['width'] = info.width;
|
|
|
|
properties['height'] = info.height;
|
|
|
|
}
|
|
|
|
if (info.orientation != null) {
|
|
|
|
properties['orientation'] = info.orientation;
|
|
|
|
}
|
|
|
|
|
|
|
|
const profile = user ? await this.userProfilesRepository.findOneBy({ userId: user.id }) : null;
|
|
|
|
|
|
|
|
const folder = await fetchFolder();
|
|
|
|
|
2023-08-16 17:51:28 +09:00
|
|
|
let file = new MiDriveFile();
|
2023-10-16 10:45:22 +09:00
|
|
|
file.id = this.idService.gen();
|
2022-09-18 03:27:08 +09:00
|
|
|
file.userId = user ? user.id : null;
|
|
|
|
file.userHost = user ? user.host : null;
|
|
|
|
file.folderId = folder !== null ? folder.id : null;
|
|
|
|
file.comment = comment;
|
|
|
|
file.properties = properties;
|
|
|
|
file.blurhash = info.blurhash ?? null;
|
|
|
|
file.isLink = isLink;
|
|
|
|
file.requestIp = requestIp;
|
|
|
|
file.requestHeaders = requestHeaders;
|
|
|
|
file.maybeSensitive = info.sensitive;
|
|
|
|
file.maybePorn = info.porn;
|
|
|
|
file.isSensitive = user
|
|
|
|
? this.userEntityService.isLocalUser(user) && profile!.alwaysMarkNsfw ? true :
|
2023-07-31 19:14:20 +09:00
|
|
|
sensitive ?? false
|
2022-09-18 03:27:08 +09:00
|
|
|
: false;
|
|
|
|
|
|
|
|
if (info.sensitive && profile!.autoSensitive) file.isSensitive = true;
|
|
|
|
if (info.sensitive && instance.setSensitiveFlagAutomatically) file.isSensitive = true;
|
2023-05-05 14:18:06 +09:00
|
|
|
if (userRoleNSFW) file.isSensitive = true;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
if (url !== null) {
|
|
|
|
file.src = url;
|
|
|
|
|
|
|
|
if (isLink) {
|
|
|
|
file.url = url;
|
|
|
|
// ローカルプロキシ用
|
2023-07-15 18:39:38 +09:00
|
|
|
file.accessKey = randomUUID();
|
|
|
|
file.thumbnailAccessKey = 'thumbnail-' + randomUUID();
|
|
|
|
file.webpublicAccessKey = 'webpublic-' + randomUUID();
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (uri !== null) {
|
|
|
|
file.uri = uri;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isLink) {
|
|
|
|
try {
|
|
|
|
file.size = 0;
|
|
|
|
file.md5 = info.md5;
|
|
|
|
file.name = detectedName;
|
|
|
|
file.type = info.type.mime;
|
|
|
|
file.storedInternal = false;
|
|
|
|
|
|
|
|
file = await this.driveFilesRepository.insert(file).then(x => this.driveFilesRepository.findOneByOrFail(x.identifiers[0]));
|
|
|
|
} catch (err) {
|
|
|
|
// duplicate key error (when already registered)
|
|
|
|
if (isDuplicateKeyValueError(err)) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.info(`already registered ${file.uri}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
file = await this.driveFilesRepository.findOneBy({
|
|
|
|
uri: file.uri!,
|
|
|
|
userId: user ? user.id : IsNull(),
|
2023-08-16 17:51:28 +09:00
|
|
|
}) as MiDriveFile;
|
2022-09-18 03:27:08 +09:00
|
|
|
} else {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.error(err as Error);
|
2022-09-18 03:27:08 +09:00
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2022-09-19 03:11:50 +09:00
|
|
|
file = await (this.save(file, path, detectedName, info.type.mime, info.md5, info.size));
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2022-09-19 03:11:50 +09:00
|
|
|
this.registerLogger.succ(`drive file has been created ${file.id}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
if (user) {
|
|
|
|
this.driveFileEntityService.pack(file, { self: true }).then(packedFile => {
|
2023-03-24 18:37:08 +09:00
|
|
|
// Publish driveFileCreated event
|
2022-09-18 03:27:08 +09:00
|
|
|
this.globalEventService.publishMainStream(user.id, 'driveFileCreated', packedFile);
|
|
|
|
this.globalEventService.publishDriveStream(user.id, 'fileCreated', packedFile);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
this.driveChart.update(file, true);
|
2023-03-24 18:37:08 +09:00
|
|
|
if (file.userHost == null) {
|
|
|
|
// ローカルユーザーのみ
|
|
|
|
this.perUserDriveChart.update(file, true);
|
|
|
|
} else {
|
2023-03-24 19:08:08 +09:00
|
|
|
if ((await this.metaService.fetch()).enableChartsForFederatedInstances) {
|
|
|
|
this.instanceChart.updateDrive(file, true);
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
return file;
|
|
|
|
}
|
|
|
|
|
2023-09-24 15:40:38 +09:00
|
|
|
@bindThis
|
2023-09-24 16:24:13 +09:00
|
|
|
public async updateFile(file: MiDriveFile, values: Partial<MiDriveFile>, updater: MiUser) {
|
2023-09-24 15:40:38 +09:00
|
|
|
const alwaysMarkNsfw = (await this.roleService.getUserPolicies(file.userId)).alwaysMarkNsfw;
|
|
|
|
|
|
|
|
if (values.name && !this.driveFileEntityService.validateFileName(file.name)) {
|
2023-09-24 16:24:13 +09:00
|
|
|
throw new DriveService.InvalidFileNameError();
|
2023-09-24 15:40:38 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
if (values.isSensitive !== undefined && values.isSensitive !== file.isSensitive && alwaysMarkNsfw && !values.isSensitive) {
|
2023-09-24 16:24:13 +09:00
|
|
|
throw new DriveService.CannotUnmarkSensitiveError();
|
2023-09-24 15:40:38 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
if (values.folderId != null) {
|
|
|
|
const folder = await this.driveFoldersRepository.findOneBy({
|
|
|
|
id: values.folderId,
|
|
|
|
userId: file.userId!,
|
|
|
|
});
|
|
|
|
|
|
|
|
if (folder == null) {
|
2023-09-24 16:24:13 +09:00
|
|
|
throw new DriveService.NoSuchFolderError();
|
2023-09-24 15:40:38 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
await this.driveFilesRepository.update(file.id, values);
|
|
|
|
|
2023-09-24 16:45:36 +09:00
|
|
|
const fileObj = await this.driveFileEntityService.pack(file.id, { self: true });
|
2023-09-24 15:40:38 +09:00
|
|
|
|
|
|
|
// Publish fileUpdated event
|
|
|
|
if (file.userId) {
|
|
|
|
this.globalEventService.publishDriveStream(file.userId, 'fileUpdated', fileObj);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (await this.roleService.isModerator(updater) && (file.userId !== updater.id)) {
|
|
|
|
if (values.isSensitive !== undefined && values.isSensitive !== file.isSensitive) {
|
2023-09-25 10:29:12 +09:00
|
|
|
const user = file.userId ? await this.usersRepository.findOneByOrFail({ id: file.userId }) : null;
|
2023-09-24 15:40:38 +09:00
|
|
|
if (values.isSensitive) {
|
|
|
|
this.moderationLogService.log(updater, 'markSensitiveDriveFile', {
|
|
|
|
fileId: file.id,
|
|
|
|
fileUserId: file.userId,
|
2023-09-25 10:29:12 +09:00
|
|
|
fileUserUsername: user?.username ?? null,
|
|
|
|
fileUserHost: user?.host ?? null,
|
2023-09-24 15:40:38 +09:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
this.moderationLogService.log(updater, 'unmarkSensitiveDriveFile', {
|
|
|
|
fileId: file.id,
|
|
|
|
fileUserId: file.userId,
|
2023-09-25 10:29:12 +09:00
|
|
|
fileUserUsername: user?.username ?? null,
|
|
|
|
fileUserHost: user?.host ?? null,
|
2023-09-24 15:40:38 +09:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return fileObj;
|
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2023-09-23 18:28:16 +09:00
|
|
|
public async deleteFile(file: MiDriveFile, isExpired = false, deleter?: MiUser) {
|
2022-09-18 03:27:08 +09:00
|
|
|
if (file.storedInternal) {
|
|
|
|
this.internalStorageService.del(file.accessKey!);
|
|
|
|
|
|
|
|
if (file.thumbnailUrl) {
|
|
|
|
this.internalStorageService.del(file.thumbnailAccessKey!);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file.webpublicUrl) {
|
|
|
|
this.internalStorageService.del(file.webpublicAccessKey!);
|
|
|
|
}
|
|
|
|
} else if (!file.isLink) {
|
|
|
|
this.queueService.createDeleteObjectStorageFileJob(file.accessKey!);
|
|
|
|
|
|
|
|
if (file.thumbnailUrl) {
|
|
|
|
this.queueService.createDeleteObjectStorageFileJob(file.thumbnailAccessKey!);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file.webpublicUrl) {
|
|
|
|
this.queueService.createDeleteObjectStorageFileJob(file.webpublicAccessKey!);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-23 18:28:16 +09:00
|
|
|
this.deletePostProcess(file, isExpired, deleter);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2023-09-23 18:28:16 +09:00
|
|
|
public async deleteFileSync(file: MiDriveFile, isExpired = false, deleter?: MiUser) {
|
2022-09-18 03:27:08 +09:00
|
|
|
if (file.storedInternal) {
|
|
|
|
this.internalStorageService.del(file.accessKey!);
|
|
|
|
|
|
|
|
if (file.thumbnailUrl) {
|
|
|
|
this.internalStorageService.del(file.thumbnailAccessKey!);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file.webpublicUrl) {
|
|
|
|
this.internalStorageService.del(file.webpublicAccessKey!);
|
|
|
|
}
|
|
|
|
} else if (!file.isLink) {
|
|
|
|
const promises = [];
|
|
|
|
|
|
|
|
promises.push(this.deleteObjectStorageFile(file.accessKey!));
|
|
|
|
|
|
|
|
if (file.thumbnailUrl) {
|
|
|
|
promises.push(this.deleteObjectStorageFile(file.thumbnailAccessKey!));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file.webpublicUrl) {
|
|
|
|
promises.push(this.deleteObjectStorageFile(file.webpublicAccessKey!));
|
|
|
|
}
|
|
|
|
|
|
|
|
await Promise.all(promises);
|
|
|
|
}
|
|
|
|
|
2023-09-23 18:28:16 +09:00
|
|
|
this.deletePostProcess(file, isExpired, deleter);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2023-09-23 18:28:16 +09:00
|
|
|
private async deletePostProcess(file: MiDriveFile, isExpired = false, deleter?: MiUser) {
|
2023-03-24 18:37:08 +09:00
|
|
|
// リモートファイル期限切れ削除後は直リンクにする
|
2022-09-18 03:27:08 +09:00
|
|
|
if (isExpired && file.userHost !== null && file.uri != null) {
|
|
|
|
this.driveFilesRepository.update(file.id, {
|
|
|
|
isLink: true,
|
|
|
|
url: file.uri,
|
|
|
|
thumbnailUrl: null,
|
|
|
|
webpublicUrl: null,
|
|
|
|
storedInternal: false,
|
|
|
|
// ローカルプロキシ用
|
2023-07-15 18:39:38 +09:00
|
|
|
accessKey: randomUUID(),
|
|
|
|
thumbnailAccessKey: 'thumbnail-' + randomUUID(),
|
|
|
|
webpublicAccessKey: 'webpublic-' + randomUUID(),
|
2022-09-18 03:27:08 +09:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
this.driveFilesRepository.delete(file.id);
|
|
|
|
}
|
|
|
|
|
|
|
|
this.driveChart.update(file, false);
|
2023-03-24 18:37:08 +09:00
|
|
|
if (file.userHost == null) {
|
|
|
|
// ローカルユーザーのみ
|
|
|
|
this.perUserDriveChart.update(file, false);
|
|
|
|
} else {
|
2023-03-24 19:08:08 +09:00
|
|
|
if ((await this.metaService.fetch()).enableChartsForFederatedInstances) {
|
|
|
|
this.instanceChart.updateDrive(file, false);
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
2023-09-23 18:28:16 +09:00
|
|
|
|
|
|
|
if (file.userId) {
|
|
|
|
this.globalEventService.publishDriveStream(file.userId, 'fileDeleted', file.id);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (deleter && await this.roleService.isModerator(deleter) && (file.userId !== deleter.id)) {
|
2023-09-25 10:29:12 +09:00
|
|
|
const user = file.userId ? await this.usersRepository.findOneByOrFail({ id: file.userId }) : null;
|
2023-09-23 18:28:16 +09:00
|
|
|
this.moderationLogService.log(deleter, 'deleteDriveFile', {
|
|
|
|
fileId: file.id,
|
|
|
|
fileUserId: file.userId,
|
2023-09-25 10:29:12 +09:00
|
|
|
fileUserUsername: user?.username ?? null,
|
|
|
|
fileUserHost: user?.host ?? null,
|
2023-09-23 18:28:16 +09:00
|
|
|
});
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-09-18 03:27:08 +09:00
|
|
|
public async deleteObjectStorageFile(key: string) {
|
|
|
|
const meta = await this.metaService.fetch();
|
2023-03-11 13:35:51 +09:00
|
|
|
try {
|
2023-03-23 13:48:14 +09:00
|
|
|
const param = {
|
|
|
|
Bucket: meta.objectStorageBucket,
|
2023-03-11 13:35:51 +09:00
|
|
|
Key: key,
|
2023-03-23 13:48:14 +09:00
|
|
|
} as DeleteObjectCommandInput;
|
|
|
|
|
|
|
|
await this.s3Service.delete(meta, param);
|
2023-03-11 13:35:51 +09:00
|
|
|
} catch (err: any) {
|
2023-03-23 13:48:14 +09:00
|
|
|
if (err.name === 'NoSuchKey') {
|
|
|
|
this.deleteLogger.warn(`The object storage had no such key to delete: ${key}. Skipping this.`, err as Error);
|
2023-03-11 13:35:51 +09:00
|
|
|
return;
|
2023-03-23 13:48:14 +09:00
|
|
|
} else {
|
|
|
|
throw new Error(`Failed to delete the file from the object storage with the given key: ${key}`, {
|
|
|
|
cause: err,
|
|
|
|
});
|
2023-03-11 13:35:51 +09:00
|
|
|
}
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-09-18 03:27:08 +09:00
|
|
|
public async uploadFromUrl({
|
|
|
|
url,
|
|
|
|
user,
|
|
|
|
folderId = null,
|
|
|
|
uri = null,
|
|
|
|
sensitive = false,
|
|
|
|
force = false,
|
|
|
|
isLink = false,
|
|
|
|
comment = null,
|
|
|
|
requestIp = null,
|
|
|
|
requestHeaders = null,
|
2023-08-16 17:51:28 +09:00
|
|
|
}: UploadFromUrlArgs): Promise<MiDriveFile> {
|
2022-09-18 03:27:08 +09:00
|
|
|
// Create temp file
|
|
|
|
const [path, cleanup] = await createTemp();
|
2023-03-10 09:37:22 +09:00
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
try {
|
|
|
|
// write content at URL to temp file
|
2023-03-04 16:51:07 +09:00
|
|
|
const { filename: name } = await this.downloadService.downloadUrl(url, path);
|
|
|
|
|
|
|
|
// If the comment is same as the name, skip comment
|
|
|
|
// (image.name is passed in when receiving attachment)
|
|
|
|
if (comment !== null && name === comment) {
|
|
|
|
comment = null;
|
|
|
|
}
|
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
const driveFile = await this.addFile({ user, path, name, comment, folderId, force, isLink, url, uri, sensitive, requestIp, requestHeaders });
|
2022-09-19 03:11:50 +09:00
|
|
|
this.downloaderLogger.succ(`Got: ${driveFile.id}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
return driveFile!;
|
|
|
|
} catch (err) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.downloaderLogger.error(`Failed to create drive file: ${err}`, {
|
2022-09-18 03:27:08 +09:00
|
|
|
url: url,
|
|
|
|
e: err,
|
|
|
|
});
|
|
|
|
throw err;
|
|
|
|
} finally {
|
|
|
|
cleanup();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|