2023-09-20 13:16:33 +02:00
|
|
|
import { AssetType, LibraryType } from '@app/infra/entities';
|
2024-01-31 17:26:51 +01:00
|
|
|
import { ImmichLogger } from '@app/infra/logger';
|
2023-12-14 17:55:40 +01:00
|
|
|
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
|
2023-09-20 13:16:33 +02:00
|
|
|
import { R_OK } from 'node:constants';
|
2024-02-02 04:18:00 +01:00
|
|
|
import { EventEmitter } from 'node:events';
|
2023-09-20 13:16:33 +02:00
|
|
|
import { Stats } from 'node:fs';
|
2024-02-02 04:18:00 +01:00
|
|
|
import path, { basename, parse } from 'node:path';
|
2024-01-31 17:26:51 +01:00
|
|
|
import picomatch from 'picomatch';
|
2023-10-09 16:25:03 +02:00
|
|
|
import { AccessCore, Permission } from '../access';
|
2023-12-10 05:34:12 +01:00
|
|
|
import { AuthDto } from '../auth';
|
2023-09-20 13:16:33 +02:00
|
|
|
import { mimeTypes } from '../domain.constant';
|
2023-10-31 21:19:12 +01:00
|
|
|
import { usePagination, validateCronExpression } from '../domain.util';
|
2023-10-11 00:59:13 +02:00
|
|
|
import { IBaseJob, IEntityJob, ILibraryFileJob, ILibraryRefreshJob, JOBS_ASSET_PAGINATION_SIZE, JobName } from '../job';
|
2024-02-02 04:18:00 +01:00
|
|
|
|
2023-10-09 16:25:03 +02:00
|
|
|
import {
|
|
|
|
IAccessRepository,
|
|
|
|
IAssetRepository,
|
|
|
|
ICryptoRepository,
|
|
|
|
IJobRepository,
|
|
|
|
ILibraryRepository,
|
|
|
|
IStorageRepository,
|
2023-10-31 21:19:12 +01:00
|
|
|
ISystemConfigRepository,
|
2023-10-09 16:25:03 +02:00
|
|
|
IUserRepository,
|
|
|
|
WithProperty,
|
|
|
|
} from '../repositories';
|
2023-10-31 21:19:12 +01:00
|
|
|
import { SystemConfigCore } from '../system-config';
|
2023-09-20 13:16:33 +02:00
|
|
|
import {
|
|
|
|
CreateLibraryDto,
|
|
|
|
LibraryResponseDto,
|
|
|
|
LibraryStatsResponseDto,
|
|
|
|
ScanLibraryDto,
|
2024-02-29 19:35:37 +01:00
|
|
|
SearchLibraryDto,
|
2023-09-20 13:16:33 +02:00
|
|
|
UpdateLibraryDto,
|
2024-02-20 16:53:12 +01:00
|
|
|
ValidateLibraryDto,
|
|
|
|
ValidateLibraryImportPathResponseDto,
|
|
|
|
ValidateLibraryResponseDto,
|
2023-10-09 05:52:12 +02:00
|
|
|
mapLibrary,
|
2023-09-20 13:16:33 +02:00
|
|
|
} from './library.dto';
|
|
|
|
|
|
|
|
@Injectable()
|
2024-01-31 09:15:54 +01:00
|
|
|
export class LibraryService extends EventEmitter {
|
2023-12-14 17:55:40 +01:00
|
|
|
readonly logger = new ImmichLogger(LibraryService.name);
|
2023-09-20 13:16:33 +02:00
|
|
|
private access: AccessCore;
|
2023-10-31 21:19:12 +01:00
|
|
|
private configCore: SystemConfigCore;
|
2024-01-31 09:15:54 +01:00
|
|
|
private watchLibraries = false;
|
2024-02-13 14:48:47 +01:00
|
|
|
private watchers: Record<string, () => void> = {};
|
2024-01-31 09:15:54 +01:00
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
constructor(
|
|
|
|
@Inject(IAccessRepository) accessRepository: IAccessRepository,
|
|
|
|
@Inject(IAssetRepository) private assetRepository: IAssetRepository,
|
2023-10-31 21:19:12 +01:00
|
|
|
@Inject(ISystemConfigRepository) configRepository: ISystemConfigRepository,
|
2023-09-20 13:16:33 +02:00
|
|
|
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
|
|
|
|
@Inject(IJobRepository) private jobRepository: IJobRepository,
|
|
|
|
@Inject(ILibraryRepository) private repository: ILibraryRepository,
|
|
|
|
@Inject(IStorageRepository) private storageRepository: IStorageRepository,
|
|
|
|
@Inject(IUserRepository) private userRepository: IUserRepository,
|
|
|
|
) {
|
2024-01-31 09:15:54 +01:00
|
|
|
super();
|
2023-10-23 14:37:51 +02:00
|
|
|
this.access = AccessCore.create(accessRepository);
|
2023-10-31 21:19:12 +01:00
|
|
|
this.configCore = SystemConfigCore.create(configRepository);
|
|
|
|
this.configCore.addValidator((config) => {
|
2024-01-31 17:26:51 +01:00
|
|
|
const { scan } = config.library;
|
|
|
|
if (!validateCronExpression(scan.cronExpression)) {
|
|
|
|
throw new Error(`Invalid cron expression ${scan.cronExpression}`);
|
2023-10-31 21:19:12 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async init() {
|
|
|
|
const config = await this.configCore.getConfig();
|
2024-01-31 17:26:51 +01:00
|
|
|
const { watch, scan } = config.library;
|
|
|
|
this.watchLibraries = watch.enabled;
|
2023-10-31 21:19:12 +01:00
|
|
|
this.jobRepository.addCronJob(
|
|
|
|
'libraryScan',
|
2024-01-31 17:26:51 +01:00
|
|
|
scan.cronExpression,
|
2023-10-31 21:19:12 +01:00
|
|
|
() => this.jobRepository.queue({ name: JobName.LIBRARY_QUEUE_SCAN_ALL, data: { force: false } }),
|
2024-01-31 17:26:51 +01:00
|
|
|
scan.enabled,
|
2023-10-31 21:19:12 +01:00
|
|
|
);
|
|
|
|
|
2024-01-31 09:15:54 +01:00
|
|
|
if (this.watchLibraries) {
|
|
|
|
await this.watchAll();
|
|
|
|
}
|
|
|
|
|
2024-01-31 17:26:51 +01:00
|
|
|
this.configCore.config$.subscribe(async ({ library }) => {
|
|
|
|
this.jobRepository.updateCronJob('libraryScan', library.scan.cronExpression, library.scan.enabled);
|
2024-01-31 09:15:54 +01:00
|
|
|
|
2024-01-31 17:26:51 +01:00
|
|
|
if (library.watch.enabled !== this.watchLibraries) {
|
|
|
|
this.watchLibraries = library.watch.enabled;
|
2024-02-02 04:18:00 +01:00
|
|
|
await (this.watchLibraries ? this.watchAll() : this.unwatchAll());
|
2024-01-31 09:15:54 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private async watch(id: string): Promise<boolean> {
|
|
|
|
if (!this.watchLibraries) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const library = await this.findOrFail(id);
|
|
|
|
|
|
|
|
if (library.type !== LibraryType.EXTERNAL) {
|
|
|
|
throw new BadRequestException('Can only watch external libraries');
|
|
|
|
} else if (library.importPaths.length === 0) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
await this.unwatch(id);
|
|
|
|
|
|
|
|
this.logger.log(`Starting to watch library ${library.id} with import path(s) ${library.importPaths}`);
|
|
|
|
|
|
|
|
const matcher = picomatch(`**/*{${mimeTypes.getSupportedFileExtensions().join(',')}}`, {
|
|
|
|
nocase: true,
|
|
|
|
ignore: library.exclusionPatterns,
|
|
|
|
});
|
|
|
|
|
2024-02-13 14:48:47 +01:00
|
|
|
let _resolve: () => void;
|
|
|
|
const ready$ = new Promise<void>((resolve) => (_resolve = resolve));
|
|
|
|
|
|
|
|
this.watchers[id] = this.storageRepository.watch(
|
|
|
|
library.importPaths,
|
|
|
|
{
|
2024-02-28 21:20:10 +01:00
|
|
|
usePolling: false,
|
2024-02-13 14:48:47 +01:00
|
|
|
ignoreInitial: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
onReady: () => _resolve(),
|
|
|
|
onAdd: async (path) => {
|
|
|
|
this.logger.debug(`File add event received for ${path} in library ${library.id}}`);
|
|
|
|
if (matcher(path)) {
|
|
|
|
await this.scanAssets(library.id, [path], library.ownerId, false);
|
|
|
|
}
|
|
|
|
this.emit('add', path);
|
|
|
|
},
|
|
|
|
onChange: async (path) => {
|
|
|
|
this.logger.debug(`Detected file change for ${path} in library ${library.id}`);
|
|
|
|
if (matcher(path)) {
|
|
|
|
// Note: if the changed file was not previously imported, it will be imported now.
|
|
|
|
await this.scanAssets(library.id, [path], library.ownerId, false);
|
|
|
|
}
|
|
|
|
this.emit('change', path);
|
|
|
|
},
|
|
|
|
onUnlink: async (path) => {
|
|
|
|
this.logger.debug(`Detected deleted file at ${path} in library ${library.id}`);
|
|
|
|
const asset = await this.assetRepository.getByLibraryIdAndOriginalPath(library.id, path);
|
|
|
|
if (asset && matcher(path)) {
|
|
|
|
await this.assetRepository.save({ id: asset.id, isOffline: true });
|
|
|
|
}
|
|
|
|
this.emit('unlink', path);
|
|
|
|
},
|
|
|
|
onError: (error) => {
|
|
|
|
// TODO: should we log, or throw an exception?
|
|
|
|
this.logger.error(`Library watcher for library ${library.id} encountered error: ${error}`);
|
|
|
|
},
|
|
|
|
},
|
|
|
|
);
|
2024-01-31 09:15:54 +01:00
|
|
|
|
|
|
|
// Wait for the watcher to initialize before returning
|
2024-02-13 14:48:47 +01:00
|
|
|
await ready$;
|
2024-01-31 09:15:54 +01:00
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
async unwatch(id: string) {
|
2024-02-13 14:48:47 +01:00
|
|
|
if (this.watchers[id]) {
|
2024-01-31 09:15:54 +01:00
|
|
|
await this.watchers[id]();
|
|
|
|
delete this.watchers[id];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async unwatchAll() {
|
|
|
|
for (const id in this.watchers) {
|
|
|
|
await this.unwatch(id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async watchAll() {
|
|
|
|
const libraries = await this.repository.getAll(false, LibraryType.EXTERNAL);
|
|
|
|
|
|
|
|
for (const library of libraries) {
|
|
|
|
await this.watch(library.id);
|
|
|
|
}
|
2023-09-20 13:16:33 +02:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async getStatistics(auth: AuthDto, id: string): Promise<LibraryStatsResponseDto> {
|
|
|
|
await this.access.requirePermission(auth, Permission.LIBRARY_READ, id);
|
2024-02-29 19:35:37 +01:00
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
return this.repository.getStatistics(id);
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async getCount(auth: AuthDto): Promise<number> {
|
|
|
|
return this.repository.getCountForUser(auth.user.id);
|
2023-09-20 13:16:33 +02:00
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async get(auth: AuthDto, id: string): Promise<LibraryResponseDto> {
|
|
|
|
await this.access.requirePermission(auth, Permission.LIBRARY_READ, id);
|
2024-02-29 19:35:37 +01:00
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
const library = await this.findOrFail(id);
|
|
|
|
return mapLibrary(library);
|
|
|
|
}
|
|
|
|
|
2024-02-29 19:35:37 +01:00
|
|
|
async getAll(auth: AuthDto, dto: SearchLibraryDto): Promise<LibraryResponseDto[]> {
|
|
|
|
const libraries = await this.repository.getAll(false, dto.type);
|
|
|
|
return libraries.map((library) => mapLibrary(library));
|
|
|
|
}
|
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
async handleQueueCleanup(): Promise<boolean> {
|
|
|
|
this.logger.debug('Cleaning up any pending library deletions');
|
|
|
|
const pendingDeletion = await this.repository.getAllDeleted();
|
2024-01-01 21:45:42 +01:00
|
|
|
await this.jobRepository.queueAll(
|
|
|
|
pendingDeletion.map((libraryToDelete) => ({ name: JobName.LIBRARY_DELETE, data: { id: libraryToDelete.id } })),
|
|
|
|
);
|
2023-09-20 13:16:33 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async create(auth: AuthDto, dto: CreateLibraryDto): Promise<LibraryResponseDto> {
|
2023-09-20 13:16:33 +02:00
|
|
|
switch (dto.type) {
|
2024-02-02 04:18:00 +01:00
|
|
|
case LibraryType.EXTERNAL: {
|
2023-09-20 13:16:33 +02:00
|
|
|
if (!dto.name) {
|
|
|
|
dto.name = 'New External Library';
|
|
|
|
}
|
|
|
|
break;
|
2024-02-02 04:18:00 +01:00
|
|
|
}
|
|
|
|
case LibraryType.UPLOAD: {
|
2023-09-20 13:16:33 +02:00
|
|
|
if (!dto.name) {
|
|
|
|
dto.name = 'New Upload Library';
|
|
|
|
}
|
|
|
|
if (dto.importPaths && dto.importPaths.length > 0) {
|
|
|
|
throw new BadRequestException('Upload libraries cannot have import paths');
|
|
|
|
}
|
|
|
|
if (dto.exclusionPatterns && dto.exclusionPatterns.length > 0) {
|
|
|
|
throw new BadRequestException('Upload libraries cannot have exclusion patterns');
|
|
|
|
}
|
2024-01-31 09:15:54 +01:00
|
|
|
if (dto.isWatched) {
|
|
|
|
throw new BadRequestException('Upload libraries cannot be watched');
|
|
|
|
}
|
2023-09-20 13:16:33 +02:00
|
|
|
break;
|
2024-02-02 04:18:00 +01:00
|
|
|
}
|
2023-09-20 13:16:33 +02:00
|
|
|
}
|
|
|
|
|
2024-02-29 19:35:37 +01:00
|
|
|
let ownerId = auth.user.id;
|
|
|
|
|
|
|
|
if (dto.ownerId) {
|
|
|
|
ownerId = dto.ownerId;
|
|
|
|
}
|
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
const library = await this.repository.create({
|
2024-02-29 19:35:37 +01:00
|
|
|
ownerId,
|
2023-09-20 13:16:33 +02:00
|
|
|
name: dto.name,
|
|
|
|
type: dto.type,
|
|
|
|
importPaths: dto.importPaths ?? [],
|
|
|
|
exclusionPatterns: dto.exclusionPatterns ?? [],
|
|
|
|
isVisible: dto.isVisible ?? true,
|
|
|
|
});
|
|
|
|
|
2024-01-31 09:15:54 +01:00
|
|
|
this.logger.log(`Creating ${dto.type} library for user ${auth.user.name}`);
|
|
|
|
|
|
|
|
if (dto.type === LibraryType.EXTERNAL && this.watchLibraries) {
|
|
|
|
await this.watch(library.id);
|
|
|
|
}
|
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
return mapLibrary(library);
|
|
|
|
}
|
|
|
|
|
2024-01-31 09:15:54 +01:00
|
|
|
private async scanAssets(libraryId: string, assetPaths: string[], ownerId: string, force = false) {
|
|
|
|
await this.jobRepository.queueAll(
|
|
|
|
assetPaths.map((assetPath) => ({
|
|
|
|
name: JobName.LIBRARY_SCAN_ASSET,
|
|
|
|
data: {
|
|
|
|
id: libraryId,
|
|
|
|
assetPath: path.normalize(assetPath),
|
|
|
|
ownerId,
|
|
|
|
force,
|
|
|
|
},
|
|
|
|
})),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-02-20 16:53:12 +01:00
|
|
|
private async validateImportPath(importPath: string): Promise<ValidateLibraryImportPathResponseDto> {
|
|
|
|
const validation = new ValidateLibraryImportPathResponseDto();
|
|
|
|
validation.importPath = importPath;
|
|
|
|
|
|
|
|
try {
|
|
|
|
const stat = await this.storageRepository.stat(importPath);
|
|
|
|
|
|
|
|
if (!stat.isDirectory()) {
|
|
|
|
validation.message = 'Not a directory';
|
|
|
|
return validation;
|
|
|
|
}
|
|
|
|
} catch (error: any) {
|
|
|
|
if (error.code === 'ENOENT') {
|
|
|
|
validation.message = 'Path does not exist (ENOENT)';
|
|
|
|
return validation;
|
|
|
|
}
|
|
|
|
validation.message = String(error);
|
|
|
|
return validation;
|
|
|
|
}
|
|
|
|
|
|
|
|
const access = await this.storageRepository.checkFileExists(importPath, R_OK);
|
|
|
|
|
|
|
|
if (!access) {
|
|
|
|
validation.message = 'Lacking read permission for folder';
|
|
|
|
return validation;
|
|
|
|
}
|
|
|
|
|
|
|
|
validation.isValid = true;
|
|
|
|
return validation;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async validate(auth: AuthDto, id: string, dto: ValidateLibraryDto): Promise<ValidateLibraryResponseDto> {
|
|
|
|
await this.access.requirePermission(auth, Permission.LIBRARY_UPDATE, id);
|
|
|
|
|
|
|
|
const response = new ValidateLibraryResponseDto();
|
|
|
|
|
|
|
|
if (dto.importPaths) {
|
|
|
|
response.importPaths = await Promise.all(
|
|
|
|
dto.importPaths.map(async (importPath) => {
|
|
|
|
return await this.validateImportPath(importPath);
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async update(auth: AuthDto, id: string, dto: UpdateLibraryDto): Promise<LibraryResponseDto> {
|
|
|
|
await this.access.requirePermission(auth, Permission.LIBRARY_UPDATE, id);
|
2024-02-29 19:35:37 +01:00
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
const library = await this.repository.update({ id, ...dto });
|
2024-01-31 09:15:54 +01:00
|
|
|
|
2024-02-20 16:53:12 +01:00
|
|
|
if (dto.importPaths) {
|
|
|
|
const validation = await this.validate(auth, id, { importPaths: dto.importPaths });
|
|
|
|
if (validation.importPaths) {
|
|
|
|
for (const path of validation.importPaths) {
|
|
|
|
if (!path.isValid) {
|
|
|
|
throw new BadRequestException(`Invalid import path: ${path.message}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-31 09:15:54 +01:00
|
|
|
if (dto.importPaths || dto.exclusionPatterns) {
|
|
|
|
// Re-watch library to use new paths and/or exclusion patterns
|
|
|
|
await this.watch(id);
|
|
|
|
}
|
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
return mapLibrary(library);
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async delete(auth: AuthDto, id: string) {
|
|
|
|
await this.access.requirePermission(auth, Permission.LIBRARY_DELETE, id);
|
2023-09-20 13:16:33 +02:00
|
|
|
|
|
|
|
const library = await this.findOrFail(id);
|
2023-12-10 05:34:12 +01:00
|
|
|
const uploadCount = await this.repository.getUploadLibraryCount(auth.user.id);
|
2023-09-20 13:16:33 +02:00
|
|
|
if (library.type === LibraryType.UPLOAD && uploadCount <= 1) {
|
|
|
|
throw new BadRequestException('Cannot delete the last upload library');
|
|
|
|
}
|
|
|
|
|
2024-01-31 09:15:54 +01:00
|
|
|
if (this.watchLibraries) {
|
|
|
|
await this.unwatch(id);
|
|
|
|
}
|
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
await this.repository.softDelete(id);
|
|
|
|
await this.jobRepository.queue({ name: JobName.LIBRARY_DELETE, data: { id } });
|
|
|
|
}
|
|
|
|
|
|
|
|
async handleDeleteLibrary(job: IEntityJob): Promise<boolean> {
|
|
|
|
const library = await this.repository.get(job.id, true);
|
|
|
|
if (!library) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO use pagination
|
2023-10-07 22:42:08 +02:00
|
|
|
const assetIds = await this.repository.getAssetIds(job.id, true);
|
2023-09-20 13:16:33 +02:00
|
|
|
this.logger.debug(`Will delete ${assetIds.length} asset(s) in library ${job.id}`);
|
2024-01-01 21:45:42 +01:00
|
|
|
await this.jobRepository.queueAll(
|
|
|
|
assetIds.map((assetId) => ({ name: JobName.ASSET_DELETION, data: { id: assetId, fromExternal: true } })),
|
|
|
|
);
|
2023-10-07 19:44:10 +02:00
|
|
|
|
2023-10-07 22:42:08 +02:00
|
|
|
if (assetIds.length === 0) {
|
|
|
|
this.logger.log(`Deleting library ${job.id}`);
|
|
|
|
await this.repository.delete(job.id);
|
|
|
|
}
|
2023-09-20 13:16:33 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
async handleAssetRefresh(job: ILibraryFileJob) {
|
|
|
|
const assetPath = path.normalize(job.assetPath);
|
|
|
|
|
|
|
|
const existingAssetEntity = await this.assetRepository.getByLibraryIdAndOriginalPath(job.id, assetPath);
|
|
|
|
|
|
|
|
let stats: Stats;
|
|
|
|
try {
|
|
|
|
stats = await this.storageRepository.stat(assetPath);
|
|
|
|
} catch (error: Error | any) {
|
|
|
|
// Can't access file, probably offline
|
|
|
|
if (existingAssetEntity) {
|
|
|
|
// Mark asset as offline
|
|
|
|
this.logger.debug(`Marking asset as offline: ${assetPath}`);
|
|
|
|
|
|
|
|
await this.assetRepository.save({ id: existingAssetEntity.id, isOffline: true });
|
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
// File can't be accessed and does not already exist in db
|
2024-02-29 19:35:37 +01:00
|
|
|
throw new BadRequestException('Cannot access file', { cause: error });
|
2023-09-20 13:16:33 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let doImport = false;
|
|
|
|
let doRefresh = false;
|
|
|
|
|
2023-10-09 05:16:13 +02:00
|
|
|
if (job.force) {
|
2023-09-20 13:16:33 +02:00
|
|
|
doRefresh = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!existingAssetEntity) {
|
|
|
|
// This asset is new to us, read it from disk
|
|
|
|
this.logger.debug(`Importing new asset: ${assetPath}`);
|
|
|
|
doImport = true;
|
|
|
|
} else if (stats.mtime.toISOString() !== existingAssetEntity.fileModifiedAt.toISOString()) {
|
|
|
|
// File modification time has changed since last time we checked, re-read from disk
|
|
|
|
this.logger.debug(
|
|
|
|
`File modification time has changed, re-importing asset: ${assetPath}. Old mtime: ${existingAssetEntity.fileModifiedAt}. New mtime: ${stats.mtime}`,
|
|
|
|
);
|
|
|
|
doRefresh = true;
|
2023-10-09 05:16:13 +02:00
|
|
|
} else if (!job.force && stats && !existingAssetEntity.isOffline) {
|
2023-09-20 13:16:33 +02:00
|
|
|
// Asset exists on disk and in db and mtime has not changed. Also, we are not forcing refresn. Therefore, do nothing
|
|
|
|
this.logger.debug(`Asset already exists in database and on disk, will not import: ${assetPath}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (stats && existingAssetEntity?.isOffline) {
|
|
|
|
// File was previously offline but is now online
|
|
|
|
this.logger.debug(`Marking previously-offline asset as online: ${assetPath}`);
|
|
|
|
await this.assetRepository.save({ id: existingAssetEntity.id, isOffline: false });
|
|
|
|
doRefresh = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!doImport && !doRefresh) {
|
|
|
|
// If we don't import, exit here
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
let assetType: AssetType;
|
|
|
|
|
|
|
|
if (mimeTypes.isImage(assetPath)) {
|
|
|
|
assetType = AssetType.IMAGE;
|
|
|
|
} else if (mimeTypes.isVideo(assetPath)) {
|
|
|
|
assetType = AssetType.VIDEO;
|
|
|
|
} else {
|
|
|
|
throw new BadRequestException(`Unsupported file type ${assetPath}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: doesn't xmp replace the file extension? Will need investigation
|
|
|
|
let sidecarPath: string | null = null;
|
|
|
|
if (await this.storageRepository.checkFileExists(`${assetPath}.xmp`, R_OK)) {
|
|
|
|
sidecarPath = `${assetPath}.xmp`;
|
|
|
|
}
|
|
|
|
|
2024-02-02 04:18:00 +01:00
|
|
|
const deviceAssetId = `${basename(assetPath)}`.replaceAll(/\s+/g, '');
|
2023-09-20 13:16:33 +02:00
|
|
|
|
|
|
|
let assetId;
|
|
|
|
if (doImport) {
|
|
|
|
const library = await this.repository.get(job.id, true);
|
|
|
|
if (library?.deletedAt) {
|
|
|
|
this.logger.error('Cannot import asset into deleted library');
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-01-31 09:15:54 +01:00
|
|
|
const pathHash = this.cryptoRepository.hashSha1(`path:${assetPath}`);
|
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
// TODO: In wait of refactoring the domain asset service, this function is just manually written like this
|
|
|
|
const addedAsset = await this.assetRepository.create({
|
|
|
|
ownerId: job.ownerId,
|
|
|
|
libraryId: job.id,
|
|
|
|
checksum: pathHash,
|
|
|
|
originalPath: assetPath,
|
|
|
|
deviceAssetId: deviceAssetId,
|
|
|
|
deviceId: 'Library Import',
|
2023-09-24 15:14:25 +02:00
|
|
|
fileCreatedAt: stats.mtime,
|
2023-09-20 13:16:33 +02:00
|
|
|
fileModifiedAt: stats.mtime,
|
2023-10-05 00:11:11 +02:00
|
|
|
localDateTime: stats.mtime,
|
2023-09-20 13:16:33 +02:00
|
|
|
type: assetType,
|
|
|
|
originalFileName: parse(assetPath).name,
|
|
|
|
sidecarPath,
|
|
|
|
isReadOnly: true,
|
|
|
|
isExternal: true,
|
|
|
|
});
|
|
|
|
assetId = addedAsset.id;
|
|
|
|
} else if (doRefresh && existingAssetEntity) {
|
|
|
|
assetId = existingAssetEntity.id;
|
|
|
|
await this.assetRepository.updateAll([existingAssetEntity.id], {
|
2023-09-24 15:14:25 +02:00
|
|
|
fileCreatedAt: stats.mtime,
|
2023-09-20 13:16:33 +02:00
|
|
|
fileModifiedAt: stats.mtime,
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
// Not importing and not refreshing, do nothing
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.logger.debug(`Queuing metadata extraction for: ${assetPath}`);
|
|
|
|
|
|
|
|
await this.jobRepository.queue({ name: JobName.METADATA_EXTRACTION, data: { id: assetId, source: 'upload' } });
|
|
|
|
|
|
|
|
if (assetType === AssetType.VIDEO) {
|
|
|
|
await this.jobRepository.queue({ name: JobName.VIDEO_CONVERSION, data: { id: assetId } });
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async queueScan(auth: AuthDto, id: string, dto: ScanLibraryDto) {
|
|
|
|
await this.access.requirePermission(auth, Permission.LIBRARY_UPDATE, id);
|
2023-09-20 13:16:33 +02:00
|
|
|
|
|
|
|
const library = await this.repository.get(id);
|
|
|
|
if (!library || library.type !== LibraryType.EXTERNAL) {
|
|
|
|
throw new BadRequestException('Can only refresh external libraries');
|
|
|
|
}
|
|
|
|
|
|
|
|
await this.jobRepository.queue({
|
|
|
|
name: JobName.LIBRARY_SCAN,
|
|
|
|
data: {
|
|
|
|
id,
|
|
|
|
refreshModifiedFiles: dto.refreshModifiedFiles ?? false,
|
|
|
|
refreshAllFiles: dto.refreshAllFiles ?? false,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-12-10 05:34:12 +01:00
|
|
|
async queueRemoveOffline(auth: AuthDto, id: string) {
|
2023-09-20 13:16:33 +02:00
|
|
|
this.logger.verbose(`Removing offline files from library: ${id}`);
|
2023-12-10 05:34:12 +01:00
|
|
|
await this.access.requirePermission(auth, Permission.LIBRARY_UPDATE, id);
|
2023-09-20 13:16:33 +02:00
|
|
|
|
|
|
|
await this.jobRepository.queue({
|
|
|
|
name: JobName.LIBRARY_REMOVE_OFFLINE,
|
|
|
|
data: {
|
|
|
|
id,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async handleQueueAllScan(job: IBaseJob): Promise<boolean> {
|
|
|
|
this.logger.debug(`Refreshing all external libraries: force=${job.force}`);
|
|
|
|
|
|
|
|
// Queue cleanup
|
|
|
|
await this.jobRepository.queue({ name: JobName.LIBRARY_QUEUE_CLEANUP, data: {} });
|
|
|
|
|
|
|
|
// Queue all library refresh
|
|
|
|
const libraries = await this.repository.getAll(true, LibraryType.EXTERNAL);
|
2024-01-01 21:45:42 +01:00
|
|
|
await this.jobRepository.queueAll(
|
|
|
|
libraries.map((library) => ({
|
2023-09-20 13:16:33 +02:00
|
|
|
name: JobName.LIBRARY_SCAN,
|
|
|
|
data: {
|
|
|
|
id: library.id,
|
|
|
|
refreshModifiedFiles: !job.force,
|
|
|
|
refreshAllFiles: job.force ?? false,
|
|
|
|
},
|
2024-01-01 21:45:42 +01:00
|
|
|
})),
|
|
|
|
);
|
2023-09-20 13:16:33 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
async handleOfflineRemoval(job: IEntityJob): Promise<boolean> {
|
2023-10-07 19:44:10 +02:00
|
|
|
const assetPagination = usePagination(JOBS_ASSET_PAGINATION_SIZE, (pagination) =>
|
|
|
|
this.assetRepository.getWith(pagination, WithProperty.IS_OFFLINE, job.id),
|
|
|
|
);
|
2023-09-20 13:16:33 +02:00
|
|
|
|
|
|
|
for await (const assets of assetPagination) {
|
2023-10-07 19:44:10 +02:00
|
|
|
this.logger.debug(`Removing ${assets.length} offline assets`);
|
2024-01-01 21:45:42 +01:00
|
|
|
await this.jobRepository.queueAll(
|
|
|
|
assets.map((asset) => ({ name: JobName.ASSET_DELETION, data: { id: asset.id, fromExternal: true } })),
|
|
|
|
);
|
2023-09-20 13:16:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-02-20 16:53:12 +01:00
|
|
|
// Check if a given path is in a user's external path. Both arguments are assumed to be normalized
|
|
|
|
private isInExternalPath(filePath: string, externalPath: string | null): boolean {
|
|
|
|
if (externalPath === null) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return filePath.startsWith(externalPath);
|
|
|
|
}
|
|
|
|
|
2023-09-20 13:16:33 +02:00
|
|
|
async handleQueueAssetRefresh(job: ILibraryRefreshJob): Promise<boolean> {
|
|
|
|
const library = await this.repository.get(job.id);
|
|
|
|
if (!library || library.type !== LibraryType.EXTERNAL) {
|
|
|
|
this.logger.warn('Can only refresh external libraries');
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.logger.verbose(`Refreshing library: ${job.id}`);
|
2024-02-20 16:53:12 +01:00
|
|
|
|
|
|
|
const pathValidation = await Promise.all(
|
|
|
|
library.importPaths.map(async (importPath) => await this.validateImportPath(importPath)),
|
|
|
|
);
|
|
|
|
|
|
|
|
const validImportPaths = pathValidation
|
|
|
|
.map((validation) => {
|
|
|
|
if (!validation.isValid) {
|
|
|
|
this.logger.error(`Skipping invalid import path: ${validation.importPath}. Reason: ${validation.message}`);
|
|
|
|
}
|
|
|
|
return validation;
|
|
|
|
})
|
|
|
|
.filter((validation) => validation.isValid)
|
|
|
|
.map((validation) => validation.importPath);
|
|
|
|
|
2024-02-02 04:18:00 +01:00
|
|
|
const rawPaths = await this.storageRepository.crawl({
|
2024-02-20 16:53:12 +01:00
|
|
|
pathsToCrawl: validImportPaths,
|
2024-02-02 04:18:00 +01:00
|
|
|
exclusionPatterns: library.exclusionPatterns,
|
|
|
|
});
|
|
|
|
|
2024-02-29 19:35:37 +01:00
|
|
|
const crawledAssetPaths = rawPaths.map((filePath) => path.normalize(filePath));
|
2023-09-20 13:16:33 +02:00
|
|
|
|
2024-01-31 09:15:54 +01:00
|
|
|
this.logger.debug(`Found ${crawledAssetPaths.length} asset(s) when crawling import paths ${library.importPaths}`);
|
2023-09-20 13:16:33 +02:00
|
|
|
const assetsInLibrary = await this.assetRepository.getByLibraryId([job.id]);
|
2023-10-11 00:59:13 +02:00
|
|
|
const onlineFiles = new Set(crawledAssetPaths);
|
|
|
|
const offlineAssetIds = assetsInLibrary
|
|
|
|
.filter((asset) => !onlineFiles.has(asset.originalPath))
|
|
|
|
.filter((asset) => !asset.isOffline)
|
|
|
|
.map((asset) => asset.id);
|
|
|
|
this.logger.debug(`Marking ${offlineAssetIds.length} assets as offline`);
|
2023-09-20 13:16:33 +02:00
|
|
|
|
2023-10-11 00:59:13 +02:00
|
|
|
await this.assetRepository.updateAll(offlineAssetIds, { isOffline: true });
|
2023-09-20 13:16:33 +02:00
|
|
|
|
|
|
|
if (crawledAssetPaths.length > 0) {
|
|
|
|
let filteredPaths: string[] = [];
|
|
|
|
if (job.refreshAllFiles || job.refreshModifiedFiles) {
|
|
|
|
filteredPaths = crawledAssetPaths;
|
|
|
|
} else {
|
2023-10-11 00:59:13 +02:00
|
|
|
const onlinePathsInLibrary = new Set(
|
|
|
|
assetsInLibrary.filter((asset) => !asset.isOffline).map((asset) => asset.originalPath),
|
|
|
|
);
|
|
|
|
filteredPaths = crawledAssetPaths.filter((assetPath) => !onlinePathsInLibrary.has(assetPath));
|
2023-09-20 13:16:33 +02:00
|
|
|
|
2023-10-11 00:59:13 +02:00
|
|
|
this.logger.debug(`Will import ${filteredPaths.length} new asset(s)`);
|
2023-09-20 13:16:33 +02:00
|
|
|
}
|
|
|
|
|
2024-01-31 09:15:54 +01:00
|
|
|
await this.scanAssets(job.id, filteredPaths, library.ownerId, job.refreshAllFiles ?? false);
|
2023-09-20 13:16:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
await this.repository.update({ id: job.id, refreshedAt: new Date() });
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async findOrFail(id: string) {
|
|
|
|
const library = await this.repository.get(id);
|
|
|
|
if (!library) {
|
|
|
|
throw new BadRequestException('Library not found');
|
|
|
|
}
|
|
|
|
return library;
|
|
|
|
}
|
|
|
|
}
|