1
0
mirror of https://github.com/immich-app/immich.git synced 2025-02-06 18:45:04 +02:00

refactor(server): config service (#13066)

* refactor(server): config service

* fix: function renaming

---------

Co-authored-by: Daniel Dietzler <mail@ddietzler.dev>
This commit is contained in:
Jason Rasmussen 2024-09-30 17:31:21 -04:00 committed by GitHub
parent f63d251490
commit a019fb670e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
30 changed files with 327 additions and 361 deletions

View File

@ -66,7 +66,7 @@ export class ServerInfoController {
@Get('config')
@EndpointLifecycle({ deprecatedAt: 'v1.107.0' })
getServerConfig(): Promise<ServerConfigDto> {
return this.service.getConfig();
return this.service.getSystemConfig();
}
@Get('statistics')

View File

@ -58,7 +58,7 @@ export class ServerController {
@Get('config')
getServerConfig(): Promise<ServerConfigDto> {
return this.service.getConfig();
return this.service.getSystemConfig();
}
@Get('statistics')

View File

@ -13,7 +13,7 @@ export class SystemConfigController {
@Get()
@Authenticated({ permission: Permission.SYSTEM_CONFIG_READ, admin: true })
getConfig(): Promise<SystemConfigDto> {
return this.service.getConfig();
return this.service.getSystemConfig();
}
@Get('defaults')
@ -25,7 +25,7 @@ export class SystemConfigController {
@Put()
@Authenticated({ permission: Permission.SYSTEM_CONFIG_UPDATE, admin: true })
updateConfig(@Body() dto: SystemConfigDto): Promise<SystemConfigDto> {
return this.service.updateConfig(dto);
return this.service.updateSystemConfig(dto);
}
@Get('storage-template-options')

View File

@ -1,7 +1,6 @@
import { randomUUID } from 'node:crypto';
import { dirname, join, resolve } from 'node:path';
import { APP_MEDIA_LOCATION } from 'src/constants';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { AssetEntity } from 'src/entities/asset.entity';
import { PersonEntity } from 'src/entities/person.entity';
import { AssetFileType, AssetPathType, ImageFormat, PathType, PersonPathType, StorageFolder } from 'src/enum';
@ -13,6 +12,7 @@ import { IPersonRepository } from 'src/interfaces/person.interface';
import { IStorageRepository } from 'src/interfaces/storage.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { getAssetFiles } from 'src/utils/asset.util';
import { getConfig } from 'src/utils/config';
export const THUMBNAIL_DIR = resolve(join(APP_MEDIA_LOCATION, StorageFolder.THUMBNAILS));
export const ENCODED_VIDEO_DIR = resolve(join(APP_MEDIA_LOCATION, StorageFolder.ENCODED_VIDEO));
@ -34,18 +34,15 @@ export type GeneratedAssetType = GeneratedImageType | AssetPathType.ENCODED_VIDE
let instance: StorageCore | null;
export class StorageCore {
private configCore;
private constructor(
private assetRepository: IAssetRepository,
private cryptoRepository: ICryptoRepository,
private moveRepository: IMoveRepository,
private personRepository: IPersonRepository,
private storageRepository: IStorageRepository,
systemMetadataRepository: ISystemMetadataRepository,
private systemMetadataRepository: ISystemMetadataRepository,
private logger: ILoggerRepository,
) {
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
) {}
static create(
assetRepository: IAssetRepository,
@ -248,7 +245,8 @@ export class StorageCore {
this.logger.warn(`Unable to complete move. File size mismatch: ${newPathSize} !== ${oldPathSize}`);
return false;
}
const config = await this.configCore.getConfig({ withCache: true });
const repos = { metadataRepo: this.systemMetadataRepository, logger: this.logger };
const config = await getConfig(repos, { withCache: true });
if (assetInfo && config.storageTemplate.hashVerificationEnabled) {
const { checksum } = assetInfo;
const newChecksum = await this.cryptoRepository.hashFile(newPath);

View File

@ -1,143 +0,0 @@
import { Injectable } from '@nestjs/common';
import AsyncLock from 'async-lock';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { load as loadYaml } from 'js-yaml';
import * as _ from 'lodash';
import { SystemConfig, defaults } from 'src/config';
import { SystemConfigDto } from 'src/dtos/system-config.dto';
import { SystemMetadataKey } from 'src/enum';
import { DatabaseLock } from 'src/interfaces/database.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { getKeysDeep, unsetDeep } from 'src/utils/misc';
import { DeepPartial } from 'typeorm';
export type SystemConfigValidator = (config: SystemConfig, newConfig: SystemConfig) => void | Promise<void>;
let instance: SystemConfigCore | null;
@Injectable()
export class SystemConfigCore {
private readonly asyncLock = new AsyncLock();
private config: SystemConfig | null = null;
private lastUpdated: number | null = null;
private constructor(
private repository: ISystemMetadataRepository,
private logger: ILoggerRepository,
) {}
static create(repository: ISystemMetadataRepository, logger: ILoggerRepository) {
if (!instance) {
instance = new SystemConfigCore(repository, logger);
}
return instance;
}
static reset() {
instance = null;
}
invalidateCache() {
this.config = null;
this.lastUpdated = null;
}
async getConfig({ withCache }: { withCache: boolean }): Promise<SystemConfig> {
if (!withCache || !this.config) {
const lastUpdated = this.lastUpdated;
await this.asyncLock.acquire(DatabaseLock[DatabaseLock.GetSystemConfig], async () => {
if (lastUpdated === this.lastUpdated) {
this.config = await this.buildConfig();
this.lastUpdated = Date.now();
}
});
}
return this.config!;
}
async updateConfig(newConfig: SystemConfig): Promise<SystemConfig> {
// get the difference between the new config and the default config
const partialConfig: DeepPartial<SystemConfig> = {};
for (const property of getKeysDeep(defaults)) {
const newValue = _.get(newConfig, property);
const isEmpty = newValue === undefined || newValue === null || newValue === '';
const defaultValue = _.get(defaults, property);
const isEqual = newValue === defaultValue || _.isEqual(newValue, defaultValue);
if (isEmpty || isEqual) {
continue;
}
_.set(partialConfig, property, newValue);
}
await this.repository.set(SystemMetadataKey.SYSTEM_CONFIG, partialConfig);
return this.getConfig({ withCache: false });
}
isUsingConfigFile() {
return !!process.env.IMMICH_CONFIG_FILE;
}
private async buildConfig() {
// load partial
const partial = this.isUsingConfigFile()
? await this.loadFromFile(process.env.IMMICH_CONFIG_FILE as string)
: await this.repository.get(SystemMetadataKey.SYSTEM_CONFIG);
// merge with defaults
const config = _.cloneDeep(defaults);
for (const property of getKeysDeep(partial)) {
_.set(config, property, _.get(partial, property));
}
// check for extra properties
const unknownKeys = _.cloneDeep(config);
for (const property of getKeysDeep(defaults)) {
unsetDeep(unknownKeys, property);
}
if (!_.isEmpty(unknownKeys)) {
this.logger.warn(`Unknown keys found: ${JSON.stringify(unknownKeys, null, 2)}`);
}
// validate full config
const errors = await validate(plainToInstance(SystemConfigDto, config));
if (errors.length > 0) {
if (this.isUsingConfigFile()) {
throw new Error(`Invalid value(s) in file: ${errors}`);
} else {
this.logger.error('Validation error', errors);
}
}
if (config.server.externalDomain.length > 0) {
config.server.externalDomain = new URL(config.server.externalDomain).origin;
}
if (!config.ffmpeg.acceptedVideoCodecs.includes(config.ffmpeg.targetVideoCodec)) {
config.ffmpeg.acceptedVideoCodecs.push(config.ffmpeg.targetVideoCodec);
}
if (!config.ffmpeg.acceptedAudioCodecs.includes(config.ffmpeg.targetAudioCodec)) {
config.ffmpeg.acceptedAudioCodecs.push(config.ffmpeg.targetAudioCodec);
}
return config;
}
private async loadFromFile(filepath: string) {
try {
const file = await this.repository.readFile(filepath);
return loadYaml(file.toString()) as unknown;
} catch (error: Error | any) {
this.logger.error(`Unable to load configuration file: ${filepath}`);
this.logger.error(error);
throw error;
}
}
}

View File

@ -1,7 +1,6 @@
import { BadRequestException, Inject } from '@nestjs/common';
import _ from 'lodash';
import { DateTime, Duration } from 'luxon';
import { SystemConfigCore } from 'src/cores/system-config.core';
import {
AssetResponseDto,
MemoryLaneResponseDto,
@ -38,13 +37,12 @@ import { IPartnerRepository } from 'src/interfaces/partner.interface';
import { IStackRepository } from 'src/interfaces/stack.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { IUserRepository } from 'src/interfaces/user.interface';
import { BaseService } from 'src/services/base.service';
import { requireAccess } from 'src/utils/access';
import { getAssetFiles, getMyPartnerIds, onAfterUnlink, onBeforeLink, onBeforeUnlink } from 'src/utils/asset.util';
import { usePagination } from 'src/utils/pagination';
export class AssetService {
private configCore: SystemConfigCore;
export class AssetService extends BaseService {
constructor(
@Inject(IAccessRepository) private access: IAccessRepository,
@Inject(IAssetRepository) private assetRepository: IAssetRepository,
@ -54,10 +52,10 @@ export class AssetService {
@Inject(IEventRepository) private eventRepository: IEventRepository,
@Inject(IPartnerRepository) private partnerRepository: IPartnerRepository,
@Inject(IStackRepository) private stackRepository: IStackRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(AssetService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
async getMemoryLane(auth: AuthDto, dto: MemoryLaneDto): Promise<MemoryLaneResponseDto[]> {
@ -214,7 +212,7 @@ export class AssetService {
}
async handleAssetDeletionCheck(): Promise<JobStatus> {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
const trashedDays = config.trash.enabled ? config.trash.days : 0;
const trashedBefore = DateTime.now()
.minus(Duration.fromObject({ days: trashedDays }))

View File

@ -13,7 +13,6 @@ import { IncomingHttpHeaders } from 'node:http';
import { Issuer, UserinfoResponse, custom, generators } from 'openid-client';
import { SystemConfig } from 'src/config';
import { LOGIN_URL, MOBILE_REDIRECT, SALT_ROUNDS } from 'src/constants';
import { SystemConfigCore } from 'src/cores/system-config.core';
import {
AuthDto,
ChangePasswordDto,
@ -39,6 +38,7 @@ import { ISessionRepository } from 'src/interfaces/session.interface';
import { ISharedLinkRepository } from 'src/interfaces/shared-link.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { IUserRepository } from 'src/interfaces/user.interface';
import { BaseService } from 'src/services/base.service';
import { isGranted } from 'src/utils/access';
import { HumanReadableSize } from 'src/utils/bytes';
import { createUser } from 'src/utils/user';
@ -70,27 +70,25 @@ export type ValidateRequest = {
};
@Injectable()
export class AuthService {
private configCore: SystemConfigCore;
export class AuthService extends BaseService {
constructor(
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
@Inject(IEventRepository) private eventRepository: IEventRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
@Inject(IUserRepository) private userRepository: IUserRepository,
@Inject(ISessionRepository) private sessionRepository: ISessionRepository,
@Inject(ISharedLinkRepository) private sharedLinkRepository: ISharedLinkRepository,
@Inject(IKeyRepository) private keyRepository: IKeyRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(AuthService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, logger);
custom.setHttpOptionsDefaults({ timeout: 30_000 });
}
async login(dto: LoginCredentialDto, details: LoginDetails) {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
if (!config.passwordLogin.enabled) {
throw new UnauthorizedException('Password login has been disabled');
}
@ -212,7 +210,7 @@ export class AuthService {
}
async authorize(dto: OAuthConfigDto): Promise<OAuthAuthorizeResponseDto> {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
if (!config.oauth.enabled) {
throw new BadRequestException('OAuth is not enabled');
}
@ -228,7 +226,7 @@ export class AuthService {
}
async callback(dto: OAuthCallbackDto, loginDetails: LoginDetails) {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
const profile = await this.getOAuthProfile(config, dto.url);
const { autoRegister, defaultStorageQuota, storageLabelClaim, storageQuotaClaim } = config.oauth;
this.logger.debug(`Logging in with OAuth: ${JSON.stringify(profile)}`);
@ -288,7 +286,7 @@ export class AuthService {
}
async link(auth: AuthDto, dto: OAuthCallbackDto): Promise<UserAdminResponseDto> {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
const { sub: oauthId } = await this.getOAuthProfile(config, dto.url);
const duplicate = await this.userRepository.getByOAuthId(oauthId);
if (duplicate && duplicate.id !== auth.user.id) {
@ -310,7 +308,7 @@ export class AuthService {
return LOGIN_URL;
}
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
if (!config.oauth.enabled) {
return LOGIN_URL;
}

View File

@ -0,0 +1,32 @@
import { Inject } from '@nestjs/common';
import { SystemConfig } from 'src/config';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { getConfig, updateConfig } from 'src/utils/config';
export class BaseService {
constructor(
@Inject(ISystemMetadataRepository) protected systemMetadataRepository: ISystemMetadataRepository,
@Inject(ILoggerRepository) protected logger: ILoggerRepository,
) {}
getConfig(options: { withCache: boolean }) {
return getConfig(
{
metadataRepo: this.systemMetadataRepository,
logger: this.logger,
},
options,
);
}
updateConfig(newConfig: SystemConfig) {
return updateConfig(
{
metadataRepo: this.systemMetadataRepository,
logger: this.logger,
},
newConfig,
);
}
}

View File

@ -1,24 +1,22 @@
import { Inject, Injectable } from '@nestjs/common';
import { SALT_ROUNDS } from 'src/constants';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { UserAdminResponseDto, mapUserAdmin } from 'src/dtos/user.dto';
import { ICryptoRepository } from 'src/interfaces/crypto.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { IUserRepository } from 'src/interfaces/user.interface';
import { BaseService } from 'src/services/base.service';
@Injectable()
export class CliService {
private configCore: SystemConfigCore;
export class CliService extends BaseService {
constructor(
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(IUserRepository) private userRepository: IUserRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(CliService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
async listUsers(): Promise<UserAdminResponseDto[]> {
@ -42,26 +40,26 @@ export class CliService {
}
async disablePasswordLogin(): Promise<void> {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
config.passwordLogin.enabled = false;
await this.configCore.updateConfig(config);
await this.updateConfig(config);
}
async enablePasswordLogin(): Promise<void> {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
config.passwordLogin.enabled = true;
await this.configCore.updateConfig(config);
await this.updateConfig(config);
}
async disableOAuthLogin(): Promise<void> {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
config.oauth.enabled = false;
await this.configCore.updateConfig(config);
await this.updateConfig(config);
}
async enableOAuthLogin(): Promise<void> {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
config.oauth.enabled = true;
await this.configCore.updateConfig(config);
await this.updateConfig(config);
}
}

View File

@ -1,5 +1,4 @@
import { Inject, Injectable } from '@nestjs/common';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { mapAsset } from 'src/dtos/asset-response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { DuplicateResponseDto, mapDuplicateResponse } from 'src/dtos/duplicate.dto';
@ -17,24 +16,23 @@ import {
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { AssetDuplicateResult, ISearchRepository } from 'src/interfaces/search.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
import { getAssetFiles } from 'src/utils/asset.util';
import { isDuplicateDetectionEnabled } from 'src/utils/misc';
import { usePagination } from 'src/utils/pagination';
@Injectable()
export class DuplicateService {
private configCore: SystemConfigCore;
export class DuplicateService extends BaseService {
constructor(
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(ISearchRepository) private searchRepository: ISearchRepository,
@Inject(IAssetRepository) private assetRepository: IAssetRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
@Inject(IJobRepository) private jobRepository: IJobRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(DuplicateService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, logger);
}
async getDuplicates(auth: AuthDto): Promise<DuplicateResponseDto[]> {
@ -44,7 +42,7 @@ export class DuplicateService {
}
async handleQueueSearchDuplicates({ force }: IBaseJob): Promise<JobStatus> {
const { machineLearning } = await this.configCore.getConfig({ withCache: false });
const { machineLearning } = await this.getConfig({ withCache: false });
if (!isDuplicateDetectionEnabled(machineLearning)) {
return JobStatus.SKIPPED;
}
@ -65,7 +63,7 @@ export class DuplicateService {
}
async handleSearchDuplicates({ id }: IEntityJob): Promise<JobStatus> {
const { machineLearning } = await this.configCore.getConfig({ withCache: true });
const { machineLearning } = await this.getConfig({ withCache: true });
if (!isDuplicateDetectionEnabled(machineLearning)) {
return JobStatus.SKIPPED;
}

View File

@ -1,6 +1,5 @@
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { snakeCase } from 'lodash';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import { mapAsset } from 'src/dtos/asset-response.dto';
import { AllJobStatusResponseDto, JobCommandDto, JobCreateDto, JobStatusDto } from 'src/dtos/job.dto';
@ -22,6 +21,7 @@ import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { IMetricRepository } from 'src/interfaces/metric.interface';
import { IPersonRepository } from 'src/interfaces/person.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
const asJobItem = (dto: JobCreateDto): JobItem => {
switch (dto.name) {
@ -44,8 +44,7 @@ const asJobItem = (dto: JobCreateDto): JobItem => {
};
@Injectable()
export class JobService {
private configCore: SystemConfigCore;
export class JobService extends BaseService {
private isMicroservices = false;
constructor(
@ -55,10 +54,10 @@ export class JobService {
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(IPersonRepository) private personRepository: IPersonRepository,
@Inject(IMetricRepository) private metricRepository: IMetricRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(JobService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, logger);
}
@OnEvent({ name: 'app.bootstrap' })
@ -198,7 +197,7 @@ export class JobService {
}
async init(jobHandlers: Record<JobName, JobHandler>) {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
for (const queueName of Object.values(QueueName)) {
let concurrency = 1;

View File

@ -3,7 +3,6 @@ import { R_OK } from 'node:constants';
import path, { basename, parse } from 'node:path';
import picomatch from 'picomatch';
import { StorageCore } from 'src/cores/storage.core';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import {
CreateLibraryDto,
@ -35,14 +34,14 @@ import { ILibraryRepository } from 'src/interfaces/library.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { IStorageRepository } from 'src/interfaces/storage.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
import { mimeTypes } from 'src/utils/mime-types';
import { handlePromiseError } from 'src/utils/misc';
import { usePagination } from 'src/utils/pagination';
import { validateCronExpression } from 'src/validation';
@Injectable()
export class LibraryService {
private configCore: SystemConfigCore;
export class LibraryService extends BaseService {
private watchLibraries = false;
private watchLock = false;
private watchers: Record<string, () => Promise<void>> = {};
@ -55,15 +54,15 @@ export class LibraryService {
@Inject(ILibraryRepository) private repository: ILibraryRepository,
@Inject(IStorageRepository) private storageRepository: IStorageRepository,
@Inject(IDatabaseRepository) private databaseRepository: IDatabaseRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(LibraryService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
@OnEvent({ name: 'app.bootstrap' })
async onBootstrap() {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
const { watch, scan } = config.library;

View File

@ -1,34 +1,26 @@
import { IAlbumRepository } from 'src/interfaces/album.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { IMapRepository } from 'src/interfaces/map.interface';
import { IPartnerRepository } from 'src/interfaces/partner.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { MapService } from 'src/services/map.service';
import { assetStub } from 'test/fixtures/asset.stub';
import { authStub } from 'test/fixtures/auth.stub';
import { newAlbumRepositoryMock } from 'test/repositories/album.repository.mock';
import { newLoggerRepositoryMock } from 'test/repositories/logger.repository.mock';
import { newMapRepositoryMock } from 'test/repositories/map.repository.mock';
import { newPartnerRepositoryMock } from 'test/repositories/partner.repository.mock';
import { newSystemMetadataRepositoryMock } from 'test/repositories/system-metadata.repository.mock';
import { Mocked } from 'vitest';
describe(MapService.name, () => {
let sut: MapService;
let albumMock: Mocked<IAlbumRepository>;
let loggerMock: Mocked<ILoggerRepository>;
let partnerMock: Mocked<IPartnerRepository>;
let mapMock: Mocked<IMapRepository>;
let systemMetadataMock: Mocked<ISystemMetadataRepository>;
beforeEach(() => {
albumMock = newAlbumRepositoryMock();
loggerMock = newLoggerRepositoryMock();
partnerMock = newPartnerRepositoryMock();
mapMock = newMapRepositoryMock();
systemMetadataMock = newSystemMetadataRepositoryMock();
sut = new MapService(albumMock, loggerMock, partnerMock, mapMock, systemMetadataMock);
sut = new MapService(albumMock, partnerMock, mapMock);
});
describe('getMapMarkers', () => {

View File

@ -1,27 +1,17 @@
import { Inject } from '@nestjs/common';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { AuthDto } from 'src/dtos/auth.dto';
import { MapMarkerDto, MapMarkerResponseDto, MapReverseGeocodeDto } from 'src/dtos/map.dto';
import { IAlbumRepository } from 'src/interfaces/album.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { IMapRepository } from 'src/interfaces/map.interface';
import { IPartnerRepository } from 'src/interfaces/partner.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { getMyPartnerIds } from 'src/utils/asset.util';
export class MapService {
private configCore: SystemConfigCore;
constructor(
@Inject(IAlbumRepository) private albumRepository: IAlbumRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(IPartnerRepository) private partnerRepository: IPartnerRepository,
@Inject(IMapRepository) private mapRepository: IMapRepository,
@Inject(ISystemMetadataRepository) private systemMetadataRepository: ISystemMetadataRepository,
) {
this.logger.setContext(MapService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, logger);
}
) {}
async getMapMarkers(auth: AuthDto, options: MapMarkerDto): Promise<MapMarkerResponseDto[]> {
const userIds = [auth.user.id];

View File

@ -1,8 +1,6 @@
import { Inject, Injectable } from '@nestjs/common';
import { dirname } from 'node:path';
import { StorageCore } from 'src/cores/storage.core';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { SystemConfigFFmpegDto } from 'src/dtos/system-config.dto';
import { AssetEntity } from 'src/entities/asset.entity';
import {
@ -43,14 +41,14 @@ import { IMoveRepository } from 'src/interfaces/move.interface';
import { IPersonRepository } from 'src/interfaces/person.interface';
import { IStorageRepository } from 'src/interfaces/storage.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
import { getAssetFiles } from 'src/utils/asset.util';
import { BaseConfig, ThumbnailConfig } from 'src/utils/media';
import { mimeTypes } from 'src/utils/mime-types';
import { usePagination } from 'src/utils/pagination';
@Injectable()
export class MediaService {
private configCore: SystemConfigCore;
export class MediaService extends BaseService {
private storageCore: StorageCore;
private maliOpenCL?: boolean;
private devices?: string[];
@ -64,10 +62,10 @@ export class MediaService {
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(IMoveRepository) moveRepository: IMoveRepository,
@Inject(ICryptoRepository) cryptoRepository: ICryptoRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(MediaService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
this.storageCore = StorageCore.create(
assetRepository,
cryptoRepository,
@ -161,7 +159,7 @@ export class MediaService {
}
async handleAssetMigration({ id }: IEntityJob): Promise<JobStatus> {
const { image } = await this.configCore.getConfig({ withCache: true });
const { image } = await this.getConfig({ withCache: true });
const [asset] = await this.assetRepository.getByIds([id], { files: true });
if (!asset) {
return JobStatus.FAILED;
@ -235,7 +233,7 @@ export class MediaService {
}
private async generateImageThumbnails(asset: AssetEntity) {
const { image } = await this.configCore.getConfig({ withCache: true });
const { image } = await this.getConfig({ withCache: true });
const previewPath = StorageCore.getImagePath(asset, AssetPathType.PREVIEW, image.preview.format);
const thumbnailPath = StorageCore.getImagePath(asset, AssetPathType.THUMBNAIL, image.thumbnail.format);
this.storageCore.ensureFolders(previewPath);
@ -269,7 +267,7 @@ export class MediaService {
}
private async generateVideoThumbnails(asset: AssetEntity) {
const { image, ffmpeg } = await this.configCore.getConfig({ withCache: true });
const { image, ffmpeg } = await this.getConfig({ withCache: true });
const previewPath = StorageCore.getImagePath(asset, AssetPathType.PREVIEW, image.preview.format);
const thumbnailPath = StorageCore.getImagePath(asset, AssetPathType.THUMBNAIL, image.thumbnail.format);
this.storageCore.ensureFolders(previewPath);
@ -339,7 +337,7 @@ export class MediaService {
return JobStatus.FAILED;
}
const { ffmpeg } = await this.configCore.getConfig({ withCache: true });
const { ffmpeg } = await this.getConfig({ withCache: true });
const target = this.getTranscodeTarget(ffmpeg, mainVideoStream, mainAudioStream);
if (target === TranscodeTarget.NONE && !this.isRemuxRequired(ffmpeg, format)) {
if (asset.encodedVideoPath) {

View File

@ -7,7 +7,6 @@ import { constants } from 'node:fs/promises';
import path from 'node:path';
import { SystemConfig } from 'src/config';
import { StorageCore } from 'src/cores/storage.core';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import { AssetFaceEntity } from 'src/entities/asset-face.entity';
import { AssetEntity } from 'src/entities/asset.entity';
@ -39,6 +38,7 @@ import { IStorageRepository } from 'src/interfaces/storage.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { ITagRepository } from 'src/interfaces/tag.interface';
import { IUserRepository } from 'src/interfaces/user.interface';
import { BaseService } from 'src/services/base.service';
import { isFaceImportEnabled } from 'src/utils/misc';
import { usePagination } from 'src/utils/pagination';
import { upsertTags } from 'src/utils/tag';
@ -97,9 +97,8 @@ const validateRange = (value: number | undefined, min: number, max: number): Non
};
@Injectable()
export class MetadataService {
export class MetadataService extends BaseService {
private storageCore: StorageCore;
private configCore: SystemConfigCore;
constructor(
@Inject(IAlbumRepository) private albumRepository: IAlbumRepository,
@ -117,10 +116,10 @@ export class MetadataService {
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(ITagRepository) private tagRepository: ITagRepository,
@Inject(IUserRepository) private userRepository: IUserRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(MetadataService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
this.storageCore = StorageCore.create(
assetRepository,
cryptoRepository,
@ -137,7 +136,7 @@ export class MetadataService {
if (app !== 'microservices') {
return;
}
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
await this.init(config);
}
@ -222,7 +221,7 @@ export class MetadataService {
}
async handleMetadataExtraction({ id }: IEntityJob): Promise<JobStatus> {
const { metadata, reverseGeocoding } = await this.configCore.getConfig({ withCache: true });
const { metadata, reverseGeocoding } = await this.getConfig({ withCache: true });
const [asset] = await this.assetRepository.getByIds([id]);
if (!asset) {
return JobStatus.FAILED;

View File

@ -1,6 +1,5 @@
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { DEFAULT_EXTERNAL_DOMAIN } from 'src/constants';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import { SystemConfigSmtpDto } from 'src/dtos/system-config.dto';
import { AlbumEntity } from 'src/entities/album.entity';
@ -20,27 +19,26 @@ import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { EmailImageAttachment, EmailTemplate, INotificationRepository } from 'src/interfaces/notification.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { IUserRepository } from 'src/interfaces/user.interface';
import { BaseService } from 'src/services/base.service';
import { getAssetFiles } from 'src/utils/asset.util';
import { getFilenameExtension } from 'src/utils/file';
import { isEqualObject } from 'src/utils/object';
import { getPreferences } from 'src/utils/preferences';
@Injectable()
export class NotificationService {
private configCore: SystemConfigCore;
export class NotificationService extends BaseService {
constructor(
@Inject(IEventRepository) private eventRepository: IEventRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(INotificationRepository) private notificationRepository: INotificationRepository,
@Inject(IUserRepository) private userRepository: IUserRepository,
@Inject(IJobRepository) private jobRepository: IJobRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
@Inject(IAssetRepository) private assetRepository: IAssetRepository,
@Inject(IAlbumRepository) private albumRepository: IAlbumRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(NotificationService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, logger);
}
@OnEvent({ name: 'config.update' })
@ -149,7 +147,7 @@ export class NotificationService {
throw new BadRequestException('Failed to verify SMTP configuration', { cause: error });
}
const { server } = await this.configCore.getConfig({ withCache: false });
const { server } = await this.getConfig({ withCache: false });
const { html, text } = await this.notificationRepository.renderEmail({
template: EmailTemplate.TEST_EMAIL,
data: {
@ -177,7 +175,7 @@ export class NotificationService {
return JobStatus.SKIPPED;
}
const { server } = await this.configCore.getConfig({ withCache: true });
const { server } = await this.getConfig({ withCache: true });
const { html, text } = await this.notificationRepository.renderEmail({
template: EmailTemplate.WELCOME,
data: {
@ -220,7 +218,7 @@ export class NotificationService {
const attachment = await this.getAlbumThumbnailAttachment(album);
const { server } = await this.configCore.getConfig({ withCache: false });
const { server } = await this.getConfig({ withCache: false });
const { html, text } = await this.notificationRepository.renderEmail({
template: EmailTemplate.ALBUM_INVITE,
data: {
@ -262,7 +260,7 @@ export class NotificationService {
const recipients = [...album.albumUsers.map((user) => user.user), owner].filter((user) => user.id !== senderId);
const attachment = await this.getAlbumThumbnailAttachment(album);
const { server } = await this.configCore.getConfig({ withCache: false });
const { server } = await this.getConfig({ withCache: false });
for (const recipient of recipients) {
const user = await this.userRepository.get(recipient.id, { withDeleted: false });
@ -303,7 +301,7 @@ export class NotificationService {
}
async handleSendEmail(data: IEmailJob): Promise<JobStatus> {
const { notifications } = await this.configCore.getConfig({ withCache: false });
const { notifications } = await this.getConfig({ withCache: false });
if (!notifications.smtp.enabled) {
return JobStatus.SKIPPED;
}

View File

@ -1,7 +1,6 @@
import { BadRequestException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { FACE_THUMBNAIL_SIZE } from 'src/constants';
import { StorageCore } from 'src/cores/storage.core';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { BulkIdErrorReason, BulkIdResponseDto } from 'src/dtos/asset-ids.response.dto';
import { AssetResponseDto, mapAsset } from 'src/dtos/asset-response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
@ -55,6 +54,7 @@ import { IPersonRepository, UpdateFacesData } from 'src/interfaces/person.interf
import { ISearchRepository } from 'src/interfaces/search.interface';
import { IStorageRepository } from 'src/interfaces/storage.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
import { checkAccess, requireAccess } from 'src/utils/access';
import { getAssetFiles } from 'src/utils/asset.util';
import { ImmichFileResponse } from 'src/utils/file';
@ -64,8 +64,7 @@ import { usePagination } from 'src/utils/pagination';
import { IsNull } from 'typeorm';
@Injectable()
export class PersonService {
private configCore: SystemConfigCore;
export class PersonService extends BaseService {
private storageCore: StorageCore;
constructor(
@ -75,15 +74,15 @@ export class PersonService {
@Inject(IMoveRepository) moveRepository: IMoveRepository,
@Inject(IMediaRepository) private mediaRepository: IMediaRepository,
@Inject(IPersonRepository) private repository: IPersonRepository,
@Inject(ISystemMetadataRepository) private systemMetadataRepository: ISystemMetadataRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(IStorageRepository) private storageRepository: IStorageRepository,
@Inject(IJobRepository) private jobRepository: IJobRepository,
@Inject(ISearchRepository) private smartInfoRepository: ISearchRepository,
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(PersonService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
this.storageCore = StorageCore.create(
assetRepository,
cryptoRepository,
@ -102,7 +101,7 @@ export class PersonService {
skip: (page - 1) * size,
};
const { machineLearning } = await this.configCore.getConfig({ withCache: false });
const { machineLearning } = await this.getConfig({ withCache: false });
const { items, hasNextPage } = await this.repository.getAllForUser(pagination, auth.user.id, {
minimumFaceCount: machineLearning.facialRecognition.minFaces,
withHidden,
@ -283,7 +282,7 @@ export class PersonService {
}
async handleQueueDetectFaces({ force }: IBaseJob): Promise<JobStatus> {
const { machineLearning } = await this.configCore.getConfig({ withCache: false });
const { machineLearning } = await this.getConfig({ withCache: false });
if (!isFacialRecognitionEnabled(machineLearning)) {
return JobStatus.SKIPPED;
}
@ -314,7 +313,7 @@ export class PersonService {
}
async handleDetectFaces({ id }: IEntityJob): Promise<JobStatus> {
const { machineLearning } = await this.configCore.getConfig({ withCache: true });
const { machineLearning } = await this.getConfig({ withCache: true });
if (!isFacialRecognitionEnabled(machineLearning)) {
return JobStatus.SKIPPED;
}
@ -375,7 +374,7 @@ export class PersonService {
}
async handleQueueRecognizeFaces({ force, nightly }: INightlyJob): Promise<JobStatus> {
const { machineLearning } = await this.configCore.getConfig({ withCache: false });
const { machineLearning } = await this.getConfig({ withCache: false });
if (!isFacialRecognitionEnabled(machineLearning)) {
return JobStatus.SKIPPED;
}
@ -425,7 +424,7 @@ export class PersonService {
}
async handleRecognizeFaces({ id, deferred }: IDeferrableJob): Promise<JobStatus> {
const { machineLearning } = await this.configCore.getConfig({ withCache: true });
const { machineLearning } = await this.getConfig({ withCache: true });
if (!isFacialRecognitionEnabled(machineLearning)) {
return JobStatus.SKIPPED;
}
@ -519,7 +518,7 @@ export class PersonService {
}
async handleGeneratePersonThumbnail(data: IEntityJob): Promise<JobStatus> {
const { machineLearning, metadata, image } = await this.configCore.getConfig({ withCache: true });
const { machineLearning, metadata, image } = await this.getConfig({ withCache: true });
if (!isFacialRecognitionEnabled(machineLearning) && !isFaceImportEnabled(metadata)) {
return JobStatus.SKIPPED;
}

View File

@ -1,5 +1,4 @@
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { AssetMapOptions, AssetResponseDto, mapAsset } from 'src/dtos/asset-response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { PersonResponseDto } from 'src/dtos/person.dto';
@ -24,13 +23,12 @@ import { IPartnerRepository } from 'src/interfaces/partner.interface';
import { IPersonRepository } from 'src/interfaces/person.interface';
import { ISearchRepository, SearchExploreItem } from 'src/interfaces/search.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
import { getMyPartnerIds } from 'src/utils/asset.util';
import { isSmartSearchEnabled } from 'src/utils/misc';
@Injectable()
export class SearchService {
private configCore: SystemConfigCore;
export class SearchService extends BaseService {
constructor(
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(IMachineLearningRepository) private machineLearning: IMachineLearningRepository,
@ -38,10 +36,10 @@ export class SearchService {
@Inject(ISearchRepository) private searchRepository: ISearchRepository,
@Inject(IAssetRepository) private assetRepository: IAssetRepository,
@Inject(IPartnerRepository) private partnerRepository: IPartnerRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(SearchService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, logger);
}
async searchPerson(auth: AuthDto, dto: SearchPeopleDto): Promise<PersonResponseDto[]> {
@ -101,7 +99,7 @@ export class SearchService {
}
async searchSmart(auth: AuthDto, dto: SmartSearchDto): Promise<SearchResponseDto> {
const { machineLearning } = await this.configCore.getConfig({ withCache: false });
const { machineLearning } = await this.getConfig({ withCache: false });
if (!isSmartSearchEnabled(machineLearning)) {
throw new BadRequestException('Smart search is not enabled');
}

View File

@ -176,9 +176,9 @@ describe(ServerService.name, () => {
});
});
describe('getConfig', () => {
describe('getSystemConfig', () => {
it('should respond the server configuration', async () => {
await expect(sut.getConfig()).resolves.toEqual({
await expect(sut.getSystemConfig()).resolves.toEqual({
loginPageMessage: '',
oauthButtonText: 'Login with OAuth',
trashDays: 30,

View File

@ -2,7 +2,6 @@ import { BadRequestException, Inject, Injectable, NotFoundException } from '@nes
import { getBuildMetadata, getServerLicensePublicKey } from 'src/config';
import { serverVersion } from 'src/constants';
import { StorageCore } from 'src/cores/storage.core';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import { LicenseKeyDto, LicenseResponseDto } from 'src/dtos/license.dto';
import {
@ -22,24 +21,24 @@ import { IServerInfoRepository } from 'src/interfaces/server-info.interface';
import { IStorageRepository } from 'src/interfaces/storage.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { IUserRepository, UserStatsQueryResponse } from 'src/interfaces/user.interface';
import { BaseService } from 'src/services/base.service';
import { asHumanReadable } from 'src/utils/bytes';
import { isUsingConfigFile } from 'src/utils/config';
import { mimeTypes } from 'src/utils/mime-types';
import { isDuplicateDetectionEnabled, isFacialRecognitionEnabled, isSmartSearchEnabled } from 'src/utils/misc';
@Injectable()
export class ServerService {
private configCore: SystemConfigCore;
export class ServerService extends BaseService {
constructor(
@Inject(IUserRepository) private userRepository: IUserRepository,
@Inject(IStorageRepository) private storageRepository: IStorageRepository,
@Inject(ISystemMetadataRepository) private systemMetadataRepository: ISystemMetadataRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(IServerInfoRepository) private serverInfoRepository: IServerInfoRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(ServerService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
@OnEvent({ name: 'app.bootstrap' })
@ -91,7 +90,7 @@ export class ServerService {
async getFeatures(): Promise<ServerFeaturesDto> {
const { reverseGeocoding, metadata, map, machineLearning, trash, oauth, passwordLogin, notifications } =
await this.configCore.getConfig({ withCache: false });
await this.getConfig({ withCache: false });
return {
smartSearch: isSmartSearchEnabled(machineLearning),
@ -106,18 +105,18 @@ export class ServerService {
oauth: oauth.enabled,
oauthAutoLaunch: oauth.autoLaunch,
passwordLogin: passwordLogin.enabled,
configFile: this.configCore.isUsingConfigFile(),
configFile: isUsingConfigFile(),
email: notifications.smtp.enabled,
};
}
async getTheme() {
const { theme } = await this.configCore.getConfig({ withCache: false });
const { theme } = await this.getConfig({ withCache: false });
return theme;
}
async getConfig(): Promise<ServerConfigDto> {
const config = await this.configCore.getConfig({ withCache: false });
async getSystemConfig(): Promise<ServerConfigDto> {
const config = await this.getConfig({ withCache: false });
const isInitialized = await this.userRepository.hasAdmin();
const onboarding = await this.systemMetadataRepository.get(SystemMetadataKey.ADMIN_ONBOARDING);

View File

@ -1,6 +1,5 @@
import { BadRequestException, ForbiddenException, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { DEFAULT_EXTERNAL_DOMAIN } from 'src/constants';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { AssetIdErrorReason, AssetIdsResponseDto } from 'src/dtos/asset-ids.response.dto';
import { AssetIdsDto } from 'src/dtos/asset.dto';
import { AuthDto } from 'src/dtos/auth.dto';
@ -20,22 +19,21 @@ import { ICryptoRepository } from 'src/interfaces/crypto.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { ISharedLinkRepository } from 'src/interfaces/shared-link.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
import { checkAccess, requireAccess } from 'src/utils/access';
import { OpenGraphTags } from 'src/utils/misc';
@Injectable()
export class SharedLinkService {
private configCore: SystemConfigCore;
export class SharedLinkService extends BaseService {
constructor(
@Inject(IAccessRepository) private access: IAccessRepository,
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
@Inject(ISharedLinkRepository) private repository: ISharedLinkRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(SharedLinkService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
getAll(auth: AuthDto): Promise<SharedLinkResponseDto[]> {
@ -195,7 +193,7 @@ export class SharedLinkService {
return null;
}
const config = await this.configCore.getConfig({ withCache: true });
const config = await this.getConfig({ withCache: true });
const sharedLink = await this.findOrFail(auth.sharedLink.userId, auth.sharedLink.id);
const assetId = sharedLink.album?.albumThumbnailAssetId || sharedLink.assets[0]?.id;
const assetCount = sharedLink.assets.length > 0 ? sharedLink.assets.length : sharedLink.album?.assets.length || 0;

View File

@ -1,6 +1,5 @@
import { Inject, Injectable } from '@nestjs/common';
import { SystemConfig } from 'src/config';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import { IAssetRepository, WithoutProperty } from 'src/interfaces/asset.interface';
import { DatabaseLock, IDatabaseRepository } from 'src/interfaces/database.interface';
@ -18,14 +17,13 @@ import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { IMachineLearningRepository } from 'src/interfaces/machine-learning.interface';
import { ISearchRepository } from 'src/interfaces/search.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
import { getAssetFiles } from 'src/utils/asset.util';
import { getCLIPModelInfo, isSmartSearchEnabled } from 'src/utils/misc';
import { usePagination } from 'src/utils/pagination';
@Injectable()
export class SmartInfoService {
private configCore: SystemConfigCore;
export class SmartInfoService extends BaseService {
constructor(
@Inject(IAssetRepository) private assetRepository: IAssetRepository,
@Inject(IDatabaseRepository) private databaseRepository: IDatabaseRepository,
@ -33,10 +31,10 @@ export class SmartInfoService {
@Inject(IMachineLearningRepository) private machineLearning: IMachineLearningRepository,
@Inject(ISearchRepository) private repository: ISearchRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(SmartInfoService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
@OnEvent({ name: 'app.bootstrap' })
@ -45,7 +43,7 @@ export class SmartInfoService {
return;
}
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
await this.init(config);
}
@ -106,7 +104,7 @@ export class SmartInfoService {
}
async handleQueueEncodeClip({ force }: IBaseJob): Promise<JobStatus> {
const { machineLearning } = await this.configCore.getConfig({ withCache: false });
const { machineLearning } = await this.getConfig({ withCache: false });
if (!isSmartSearchEnabled(machineLearning)) {
return JobStatus.SKIPPED;
}
@ -131,7 +129,7 @@ export class SmartInfoService {
}
async handleEncodeClip({ id }: IEntityJob): Promise<JobStatus> {
const { machineLearning } = await this.configCore.getConfig({ withCache: true });
const { machineLearning } = await this.getConfig({ withCache: true });
if (!isSmartSearchEnabled(machineLearning)) {
return JobStatus.SKIPPED;
}

View File

@ -13,7 +13,6 @@ import {
supportedYearTokens,
} from 'src/constants';
import { StorageCore } from 'src/cores/storage.core';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import { AssetEntity } from 'src/entities/asset.entity';
import { AssetPathType, AssetType, StorageFolder } from 'src/enum';
@ -29,6 +28,7 @@ import { IPersonRepository } from 'src/interfaces/person.interface';
import { IStorageRepository } from 'src/interfaces/storage.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { IUserRepository } from 'src/interfaces/user.interface';
import { BaseService } from 'src/services/base.service';
import { getLivePhotoMotionFilename } from 'src/utils/file';
import { usePagination } from 'src/utils/pagination';
@ -45,8 +45,7 @@ interface RenderMetadata {
}
@Injectable()
export class StorageTemplateService {
private configCore: SystemConfigCore;
export class StorageTemplateService extends BaseService {
private storageCore: StorageCore;
private _template: {
compiled: HandlebarsTemplateDelegate<any>;
@ -71,10 +70,10 @@ export class StorageTemplateService {
@Inject(IUserRepository) private userRepository: IUserRepository,
@Inject(ICryptoRepository) cryptoRepository: ICryptoRepository,
@Inject(IDatabaseRepository) private databaseRepository: IDatabaseRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(StorageTemplateService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
this.storageCore = StorageCore.create(
assetRepository,
cryptoRepository,
@ -117,7 +116,7 @@ export class StorageTemplateService {
}
async handleMigrationSingle({ id }: IEntityJob): Promise<JobStatus> {
const config = await this.configCore.getConfig({ withCache: true });
const config = await this.getConfig({ withCache: true });
const storageTemplateEnabled = config.storageTemplate.enabled;
if (!storageTemplateEnabled) {
return JobStatus.SKIPPED;
@ -147,7 +146,7 @@ export class StorageTemplateService {
async handleMigration(): Promise<JobStatus> {
this.logger.log('Starting storage template migration');
const { storageTemplate } = await this.configCore.getConfig({ withCache: true });
const { storageTemplate } = await this.getConfig({ withCache: true });
const { enabled } = storageTemplate;
if (!enabled) {
this.logger.log('Storage template migration disabled, skipping');

View File

@ -216,7 +216,7 @@ describe(SystemConfigService.name, () => {
it('should return the default config', async () => {
systemMock.get.mockResolvedValue({});
await expect(sut.getConfig()).resolves.toEqual(defaults);
await expect(sut.getSystemConfig()).resolves.toEqual(defaults);
});
it('should merge the overrides', async () => {
@ -227,7 +227,7 @@ describe(SystemConfigService.name, () => {
user: { deleteDelay: 15 },
});
await expect(sut.getConfig()).resolves.toEqual(updatedConfig);
await expect(sut.getSystemConfig()).resolves.toEqual(updatedConfig);
});
it('should load the config from a json file', async () => {
@ -235,7 +235,7 @@ describe(SystemConfigService.name, () => {
systemMock.readFile.mockResolvedValue(JSON.stringify(partialConfig));
await expect(sut.getConfig()).resolves.toEqual(updatedConfig);
await expect(sut.getSystemConfig()).resolves.toEqual(updatedConfig);
expect(systemMock.readFile).toHaveBeenCalledWith('immich-config.json');
});
@ -245,7 +245,7 @@ describe(SystemConfigService.name, () => {
systemMock.readFile.mockResolvedValue(`{ "ffmpeg2": true, "ffmpeg2": true }`);
await expect(sut.getConfig()).rejects.toBeInstanceOf(Error);
await expect(sut.getSystemConfig()).rejects.toBeInstanceOf(Error);
expect(systemMock.readFile).toHaveBeenCalledWith('immich-config.json');
expect(loggerMock.error).toHaveBeenCalledTimes(2);
@ -269,7 +269,7 @@ describe(SystemConfigService.name, () => {
`;
systemMock.readFile.mockResolvedValue(partialConfig);
await expect(sut.getConfig()).resolves.toEqual(updatedConfig);
await expect(sut.getSystemConfig()).resolves.toEqual(updatedConfig);
expect(systemMock.readFile).toHaveBeenCalledWith('immich-config.yaml');
});
@ -278,7 +278,7 @@ describe(SystemConfigService.name, () => {
process.env.IMMICH_CONFIG_FILE = 'immich-config.json';
systemMock.readFile.mockResolvedValue(JSON.stringify({}));
await expect(sut.getConfig()).resolves.toEqual(defaults);
await expect(sut.getSystemConfig()).resolves.toEqual(defaults);
expect(systemMock.readFile).toHaveBeenCalledWith('immich-config.json');
});
@ -288,7 +288,7 @@ describe(SystemConfigService.name, () => {
const partialConfig = { machineLearning: { url: 'immich_machine_learning' } };
systemMock.readFile.mockResolvedValue(JSON.stringify(partialConfig));
const config = await sut.getConfig();
const config = await sut.getSystemConfig();
expect(config.machineLearning.url).toEqual('immich_machine_learning');
});
@ -304,7 +304,7 @@ describe(SystemConfigService.name, () => {
const partialConfig = { server: { externalDomain } };
systemMock.readFile.mockResolvedValue(JSON.stringify(partialConfig));
const config = await sut.getConfig();
const config = await sut.getSystemConfig();
expect(config.server.externalDomain).toEqual(result ?? 'https://demo.immich.app');
});
}
@ -316,7 +316,7 @@ describe(SystemConfigService.name, () => {
`;
systemMock.readFile.mockResolvedValue(partialConfig);
await sut.getConfig();
await sut.getSystemConfig();
expect(loggerMock.warn).toHaveBeenCalled();
});
@ -335,10 +335,10 @@ describe(SystemConfigService.name, () => {
systemMock.readFile.mockResolvedValue(JSON.stringify(test.config));
if (test.warn) {
await sut.getConfig();
await sut.getSystemConfig();
expect(loggerMock.warn).toHaveBeenCalled();
} else {
await expect(sut.getConfig()).rejects.toBeInstanceOf(Error);
await expect(sut.getSystemConfig()).rejects.toBeInstanceOf(Error);
}
});
}
@ -382,7 +382,7 @@ describe(SystemConfigService.name, () => {
describe('updateConfig', () => {
it('should update the config and emit an event', async () => {
systemMock.get.mockResolvedValue(partialConfig);
await expect(sut.updateConfig(updatedConfig)).resolves.toEqual(updatedConfig);
await expect(sut.updateSystemConfig(updatedConfig)).resolves.toEqual(updatedConfig);
expect(eventMock.emit).toHaveBeenCalledWith(
'config.update',
expect.objectContaining({ oldConfig: expect.any(Object), newConfig: updatedConfig }),
@ -392,7 +392,7 @@ describe(SystemConfigService.name, () => {
it('should throw an error if a config file is in use', async () => {
process.env.IMMICH_CONFIG_FILE = 'immich-config.json';
systemMock.readFile.mockResolvedValue(JSON.stringify({}));
await expect(sut.updateConfig(defaults)).rejects.toBeInstanceOf(BadRequestException);
await expect(sut.updateSystemConfig(defaults)).rejects.toBeInstanceOf(BadRequestException);
expect(systemMock.set).not.toHaveBeenCalled();
});
});

View File

@ -12,36 +12,35 @@ import {
supportedWeekTokens,
supportedYearTokens,
} from 'src/constants';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import { SystemConfigDto, SystemConfigTemplateStorageOptionDto, mapConfig } from 'src/dtos/system-config.dto';
import { LogLevel } from 'src/enum';
import { ArgOf, IEventRepository } from 'src/interfaces/event.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
import { clearConfigCache, isUsingConfigFile } from 'src/utils/config';
import { toPlainObject } from 'src/utils/object';
@Injectable()
export class SystemConfigService {
private core: SystemConfigCore;
export class SystemConfigService extends BaseService {
constructor(
@Inject(ISystemMetadataRepository) repository: ISystemMetadataRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(IEventRepository) private eventRepository: IEventRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(SystemConfigService.name);
this.core = SystemConfigCore.create(repository, this.logger);
}
@OnEvent({ name: 'app.bootstrap', priority: -100 })
async onBootstrap() {
const config = await this.core.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
await this.eventRepository.emit('config.update', { newConfig: config });
}
async getConfig(): Promise<SystemConfigDto> {
const config = await this.core.getConfig({ withCache: false });
async getSystemConfig(): Promise<SystemConfigDto> {
const config = await this.getConfig({ withCache: false });
return mapConfig(config);
}
@ -57,7 +56,7 @@ export class SystemConfigService {
this.logger.setLogLevel(level);
this.logger.log(`LogLevel=${level} ${envLevel ? '(set via IMMICH_LOG_LEVEL)' : '(set via system config)'}`);
// TODO only do this if the event is a socket.io event
this.core.invalidateCache();
clearConfigCache();
}
@OnEvent({ name: 'config.validate' })
@ -67,12 +66,12 @@ export class SystemConfigService {
}
}
async updateConfig(dto: SystemConfigDto): Promise<SystemConfigDto> {
if (this.core.isUsingConfigFile()) {
async updateSystemConfig(dto: SystemConfigDto): Promise<SystemConfigDto> {
if (isUsingConfigFile()) {
throw new BadRequestException('Cannot update configuration while IMMICH_CONFIG_FILE is in use');
}
const oldConfig = await this.core.getConfig({ withCache: false });
const oldConfig = await this.getConfig({ withCache: false });
try {
await this.eventRepository.emit('config.validate', { newConfig: toPlainObject(dto), oldConfig });
@ -81,7 +80,7 @@ export class SystemConfigService {
throw new BadRequestException(error instanceof Error ? error.message : error);
}
const newConfig = await this.core.updateConfig(dto);
const newConfig = await this.updateConfig(dto);
await this.eventRepository.emit('config.update', { newConfig, oldConfig });
@ -104,7 +103,7 @@ export class SystemConfigService {
}
async getCustomCss(): Promise<string> {
const { theme } = await this.core.getConfig({ withCache: false });
const { theme } = await this.getConfig({ withCache: false });
return theme.customCss;
}

View File

@ -3,7 +3,6 @@ import { DateTime } from 'luxon';
import { getClientLicensePublicKey, getServerLicensePublicKey } from 'src/config';
import { SALT_ROUNDS } from 'src/constants';
import { StorageCore } from 'src/cores/storage.core';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { AuthDto } from 'src/dtos/auth.dto';
import { LicenseKeyDto, LicenseResponseDto } from 'src/dtos/license.dto';
import { UserPreferencesResponseDto, UserPreferencesUpdateDto, mapPreferences } from 'src/dtos/user-preferences.dto';
@ -19,13 +18,12 @@ import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { IStorageRepository } from 'src/interfaces/storage.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { IUserRepository, UserFindOptions } from 'src/interfaces/user.interface';
import { BaseService } from 'src/services/base.service';
import { ImmichFileResponse } from 'src/utils/file';
import { getPreferences, getPreferencesPartial, mergePreferences } from 'src/utils/preferences';
@Injectable()
export class UserService {
private configCore: SystemConfigCore;
export class UserService extends BaseService {
constructor(
@Inject(IAlbumRepository) private albumRepository: IAlbumRepository,
@Inject(ICryptoRepository) private cryptoRepository: ICryptoRepository,
@ -33,10 +31,10 @@ export class UserService {
@Inject(IStorageRepository) private storageRepository: IStorageRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(IUserRepository) private userRepository: IUserRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(UserService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
async search(): Promise<UserResponseDto[]> {
@ -189,7 +187,7 @@ export class UserService {
async handleUserDeleteCheck(): Promise<JobStatus> {
const users = await this.userRepository.getDeletedUsers();
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
await this.jobRepository.queueAll(
users.flatMap((user) =>
this.isReadyForDeletion(user, config.user.deleteDelay)
@ -201,7 +199,7 @@ export class UserService {
}
async handleUserDelete({ id, force }: IEntityJob): Promise<JobStatus> {
const config = await this.configCore.getConfig({ withCache: false });
const config = await this.getConfig({ withCache: false });
const user = await this.userRepository.get(id, { withDeleted: true });
if (!user) {
return JobStatus.FAILED;

View File

@ -2,7 +2,6 @@ import { Inject, Injectable } from '@nestjs/common';
import { DateTime } from 'luxon';
import semver, { SemVer } from 'semver';
import { isDev, serverVersion } from 'src/constants';
import { SystemConfigCore } from 'src/cores/system-config.core';
import { OnEvent } from 'src/decorators';
import { ReleaseNotification, ServerVersionResponseDto } from 'src/dtos/server.dto';
import { VersionCheckMetadata } from 'src/entities/system-metadata.entity';
@ -12,6 +11,7 @@ import { IJobRepository, JobName, JobStatus } from 'src/interfaces/job.interface
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { IServerInfoRepository } from 'src/interfaces/server-info.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { BaseService } from 'src/services/base.service';
const asNotification = ({ checkedAt, releaseVersion }: VersionCheckMetadata): ReleaseNotification => {
return {
@ -23,18 +23,16 @@ const asNotification = ({ checkedAt, releaseVersion }: VersionCheckMetadata): Re
};
@Injectable()
export class VersionService {
private configCore: SystemConfigCore;
export class VersionService extends BaseService {
constructor(
@Inject(IEventRepository) private eventRepository: IEventRepository,
@Inject(IJobRepository) private jobRepository: IJobRepository,
@Inject(IServerInfoRepository) private repository: IServerInfoRepository,
@Inject(ISystemMetadataRepository) private systemMetadataRepository: ISystemMetadataRepository,
@Inject(ILoggerRepository) private logger: ILoggerRepository,
@Inject(ISystemMetadataRepository) systemMetadataRepository: ISystemMetadataRepository,
@Inject(ILoggerRepository) logger: ILoggerRepository,
) {
super(systemMetadataRepository, logger);
this.logger.setContext(VersionService.name);
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
}
@OnEvent({ name: 'app.bootstrap' })
@ -58,7 +56,7 @@ export class VersionService {
return JobStatus.SKIPPED;
}
const { newVersionCheck } = await this.configCore.getConfig({ withCache: true });
const { newVersionCheck } = await this.getConfig({ withCache: true });
if (!newVersionCheck.enabled) {
return JobStatus.SKIPPED;
}

129
server/src/utils/config.ts Normal file
View File

@ -0,0 +1,129 @@
import AsyncLock from 'async-lock';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { load as loadYaml } from 'js-yaml';
import * as _ from 'lodash';
import { SystemConfig, defaults } from 'src/config';
import { SystemConfigDto } from 'src/dtos/system-config.dto';
import { SystemMetadataKey } from 'src/enum';
import { DatabaseLock } from 'src/interfaces/database.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { getKeysDeep, unsetDeep } from 'src/utils/misc';
import { DeepPartial } from 'typeorm';
export type SystemConfigValidator = (config: SystemConfig, newConfig: SystemConfig) => void | Promise<void>;
type RepoDeps = {
metadataRepo: ISystemMetadataRepository;
logger: ILoggerRepository;
};
const asyncLock = new AsyncLock();
let config: SystemConfig | null = null;
let lastUpdated: number | null = null;
export const clearConfigCache = () => {
config = null;
lastUpdated = null;
};
export const isUsingConfigFile = () => {
return !!process.env.IMMICH_CONFIG_FILE;
};
export const getConfig = async (repos: RepoDeps, { withCache }: { withCache: boolean }): Promise<SystemConfig> => {
if (!withCache || !config) {
const timestamp = lastUpdated;
await asyncLock.acquire(DatabaseLock[DatabaseLock.GetSystemConfig], async () => {
if (timestamp === lastUpdated) {
config = await buildConfig(repos);
lastUpdated = Date.now();
}
});
}
return config!;
};
export const updateConfig = async (repos: RepoDeps, newConfig: SystemConfig): Promise<SystemConfig> => {
const { metadataRepo } = repos;
// get the difference between the new config and the default config
const partialConfig: DeepPartial<SystemConfig> = {};
for (const property of getKeysDeep(defaults)) {
const newValue = _.get(newConfig, property);
const isEmpty = newValue === undefined || newValue === null || newValue === '';
const defaultValue = _.get(defaults, property);
const isEqual = newValue === defaultValue || _.isEqual(newValue, defaultValue);
if (isEmpty || isEqual) {
continue;
}
_.set(partialConfig, property, newValue);
}
await metadataRepo.set(SystemMetadataKey.SYSTEM_CONFIG, partialConfig);
return getConfig(repos, { withCache: false });
};
const loadFromFile = async ({ metadataRepo, logger }: RepoDeps, filepath: string) => {
try {
const file = await metadataRepo.readFile(filepath);
return loadYaml(file.toString()) as unknown;
} catch (error: Error | any) {
logger.error(`Unable to load configuration file: ${filepath}`);
logger.error(error);
throw error;
}
};
const buildConfig = async (repos: RepoDeps) => {
const { metadataRepo, logger } = repos;
// load partial
const partial = isUsingConfigFile()
? await loadFromFile(repos, process.env.IMMICH_CONFIG_FILE as string)
: await metadataRepo.get(SystemMetadataKey.SYSTEM_CONFIG);
// merge with defaults
const config = _.cloneDeep(defaults);
for (const property of getKeysDeep(partial)) {
_.set(config, property, _.get(partial, property));
}
// check for extra properties
const unknownKeys = _.cloneDeep(config);
for (const property of getKeysDeep(defaults)) {
unsetDeep(unknownKeys, property);
}
if (!_.isEmpty(unknownKeys)) {
logger.warn(`Unknown keys found: ${JSON.stringify(unknownKeys, null, 2)}`);
}
// validate full config
const errors = await validate(plainToInstance(SystemConfigDto, config));
if (errors.length > 0) {
if (isUsingConfigFile()) {
throw new Error(`Invalid value(s) in file: ${errors}`);
} else {
logger.error('Validation error', errors);
}
}
if (config.server.externalDomain.length > 0) {
config.server.externalDomain = new URL(config.server.externalDomain).origin;
}
if (!config.ffmpeg.acceptedVideoCodecs.includes(config.ffmpeg.targetVideoCodec)) {
config.ffmpeg.acceptedVideoCodecs.push(config.ffmpeg.targetVideoCodec);
}
if (!config.ffmpeg.acceptedAudioCodecs.includes(config.ffmpeg.targetAudioCodec)) {
config.ffmpeg.acceptedAudioCodecs.push(config.ffmpeg.targetAudioCodec);
}
return config;
};

View File

@ -1,12 +1,9 @@
import { SystemConfigCore } from 'src/cores/system-config.core';
import { ISystemMetadataRepository } from 'src/interfaces/system-metadata.interface';
import { clearConfigCache } from 'src/utils/config';
import { Mocked, vitest } from 'vitest';
export const newSystemMetadataRepositoryMock = (reset = true): Mocked<ISystemMetadataRepository> => {
if (reset) {
SystemConfigCore.reset();
}
export const newSystemMetadataRepositoryMock = (): Mocked<ISystemMetadataRepository> => {
clearConfigCache();
return {
get: vitest.fn() as any,
set: vitest.fn(),