Merge branch 'main' of https://github.com/immich-app/immich into feat/crawl-wrapper

This commit is contained in:
Jonathan Jogenfors
2026-02-13 22:54:58 +01:00
236 changed files with 15905 additions and 7319 deletions
+8 -8
View File
@@ -35,7 +35,7 @@
},
"dependencies": {
"@extism/extism": "2.0.0-rc13",
"@immich/walkrs": "file:../../walkrs",
"@immich/walkrs": "0.0.0",
"@nestjs/bullmq": "^11.0.1",
"@nestjs/common": "^11.0.4",
"@nestjs/core": "^11.0.4",
@@ -46,14 +46,14 @@
"@nestjs/websockets": "^11.0.4",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^2.0.0",
"@opentelemetry/exporter-prometheus": "^0.210.0",
"@opentelemetry/instrumentation-http": "^0.210.0",
"@opentelemetry/instrumentation-ioredis": "^0.58.0",
"@opentelemetry/instrumentation-nestjs-core": "^0.56.0",
"@opentelemetry/instrumentation-pg": "^0.62.0",
"@opentelemetry/exporter-prometheus": "^0.211.0",
"@opentelemetry/instrumentation-http": "^0.211.0",
"@opentelemetry/instrumentation-ioredis": "^0.59.0",
"@opentelemetry/instrumentation-nestjs-core": "^0.57.0",
"@opentelemetry/instrumentation-pg": "^0.63.0",
"@opentelemetry/resources": "^2.0.1",
"@opentelemetry/sdk-metrics": "^2.0.1",
"@opentelemetry/sdk-node": "^0.210.0",
"@opentelemetry/sdk-node": "^0.211.0",
"@opentelemetry/semantic-conventions": "^1.34.0",
"@react-email/components": "^0.5.0",
"@react-email/render": "^1.1.2",
@@ -70,7 +70,7 @@
"compression": "^1.8.0",
"cookie": "^1.0.2",
"cookie-parser": "^1.4.7",
"cron": "4.3.5",
"cron": "4.4.0",
"exiftool-vendored": "^34.3.0",
"express": "^5.1.0",
"fast-glob": "^3.3.2",
+2
View File
@@ -9,6 +9,7 @@ import {
import { DisableOAuthLogin, EnableOAuthLogin } from 'src/commands/oauth-login';
import { DisablePasswordLoginCommand, EnablePasswordLoginCommand } from 'src/commands/password-login';
import { PromptPasswordQuestions, ResetAdminPasswordCommand } from 'src/commands/reset-admin-password.command';
import { SchemaCheck } from 'src/commands/schema-check';
import { VersionCommand } from 'src/commands/version.command';
export const commandsAndQuestions = [
@@ -28,4 +29,5 @@ export const commandsAndQuestions = [
ChangeMediaLocationCommand,
PromptMediaLocationQuestions,
PromptConfirmMoveQuestions,
SchemaCheck,
];
+60
View File
@@ -0,0 +1,60 @@
import { Command, CommandRunner } from 'nest-commander';
import { ErrorMessages } from 'src/constants';
import { CliService } from 'src/services/cli.service';
import { asHuman } from 'src/sql-tools/schema-diff';
@Command({
name: 'schema-check',
description: 'Verify database migrations and check for schema drift',
})
export class SchemaCheck extends CommandRunner {
constructor(private service: CliService) {
super();
}
async run(): Promise<void> {
try {
const { migrations, drift } = await this.service.schemaReport();
if (migrations.every((item) => item.status === 'applied')) {
console.log('Migrations are up to date');
} else {
console.log('Migration issues detected:');
for (const migration of migrations) {
switch (migration.status) {
case 'deleted': {
console.log(` - ${migration.name} was applied, but the file no longer exists on disk`);
break;
}
case 'missing': {
console.log(` - ${migration.name} exists, but has not been applied to the database`);
break;
}
}
}
}
if (drift.items.length === 0) {
console.log('\nNo schema drift detected');
} else {
console.log(`\n${ErrorMessages.SchemaDrift}`);
for (const item of drift.items) {
console.log(` - ${item.type}: ` + asHuman(item));
}
console.log(`
The below SQL is automatically generated and may be helpful for resolving drift. ** Use at your own risk! **
\`\`\`sql
${drift.asSql().join('\n')}
\`\`\`
`);
}
} catch (error) {
console.error(error);
console.error('Unable to debug migrations');
}
}
}
+7
View File
@@ -4,6 +4,13 @@ import { dirname, join } from 'node:path';
import { SemVer } from 'semver';
import { ApiTag, DatabaseExtension, ExifOrientation, VectorIndex } from 'src/enum';
export const ErrorMessages = {
InconsistentMediaLocation:
'Detected an inconsistent media location. For more information, see https://docs.immich.app/errors#inconsistent-media-location',
SchemaDrift: `Detected schema drift. For more information, see https://docs.immich.app/errors#schema-drift`,
TypeOrmUpgrade: 'Invalid upgrade path. For more information, see https://docs.immich.app/errors/#typeorm-upgrade',
};
export const POSTGRES_VERSION_RANGE = '>=14.0.0';
export const VECTORCHORD_VERSION_RANGE = '>=0.3 <2';
export const VECTORS_VERSION_RANGE = '>=0.2 <0.4';
@@ -22,21 +22,39 @@ import { AuthDto } from 'src/dtos/auth.dto';
import {
SharedLinkCreateDto,
SharedLinkEditDto,
SharedLinkLoginDto,
SharedLinkPasswordDto,
SharedLinkResponseDto,
SharedLinkSearchDto,
} from 'src/dtos/shared-link.dto';
import { ApiTag, ImmichCookie, Permission } from 'src/enum';
import { Auth, Authenticated, GetLoginDetails } from 'src/middleware/auth.guard';
import { LoggingRepository } from 'src/repositories/logging.repository';
import { LoginDetails } from 'src/services/auth.service';
import { SharedLinkService } from 'src/services/shared-link.service';
import { respondWithCookie } from 'src/utils/response';
import { UUIDParamDto } from 'src/validation';
const getAuthTokens = (cookies: Record<string, string> | undefined) => {
return cookies?.[ImmichCookie.SharedLinkToken]?.split(',') || [];
};
const merge = (cookies: Record<string, string> | undefined, token: string) => {
const authTokens = getAuthTokens(cookies);
if (!authTokens.includes(token)) {
authTokens.push(token);
}
return authTokens.join(',');
};
@ApiTags(ApiTag.SharedLinks)
@Controller('shared-links')
export class SharedLinkController {
constructor(private service: SharedLinkService) {}
constructor(
private service: SharedLinkService,
private logger: LoggingRepository,
) {}
@Get()
@Authenticated({ permission: Permission.SharedLinkRead })
@@ -49,6 +67,28 @@ export class SharedLinkController {
return this.service.getAll(auth, dto);
}
@Post('login')
@Authenticated({ sharedLink: true })
@Endpoint({
summary: 'Shared link login',
description: 'Login to a password protected shared link',
history: new HistoryBuilder().added('v2.6.0').beta('v2.6.0'),
})
async sharedLinkLogin(
@Auth() auth: AuthDto,
@Body() dto: SharedLinkLoginDto,
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
@GetLoginDetails() loginDetails: LoginDetails,
): Promise<SharedLinkResponseDto> {
const { sharedLink, token } = await this.service.login(auth, dto);
return respondWithCookie(res, sharedLink, {
isSecure: loginDetails.isSecure,
values: [{ key: ImmichCookie.SharedLinkToken, value: merge(req.cookies, token) }],
});
}
@Get('me')
@Authenticated({ sharedLink: true })
@Endpoint({
@@ -59,19 +99,19 @@ export class SharedLinkController {
async getMySharedLink(
@Auth() auth: AuthDto,
@Query() dto: SharedLinkPasswordDto,
@Req() request: Request,
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
@GetLoginDetails() loginDetails: LoginDetails,
): Promise<SharedLinkResponseDto> {
const sharedLinkToken = request.cookies?.[ImmichCookie.SharedLinkToken];
if (sharedLinkToken) {
dto.token = sharedLinkToken;
if (dto.password) {
this.logger.deprecate(
'Passing shared link password via query parameters is deprecated and will be removed in the next major release. Please use POST /shared-links/login instead.',
);
return this.sharedLinkLogin(auth, { password: dto.password }, req, res, loginDetails);
}
const body = await this.service.getMine(auth, dto);
return respondWithCookie(res, body, {
isSecure: loginDetails.isSecure,
values: body.token ? [{ key: ImmichCookie.SharedLinkToken, value: body.token }] : [],
});
return this.service.getMine(auth, getAuthTokens(req.cookies));
}
@Get(':id')
+48 -78
View File
@@ -1,14 +1,14 @@
import { mapAsset } from 'src/dtos/asset-response.dto';
import { AssetEditAction } from 'src/dtos/editing.dto';
import { assetStub } from 'test/fixtures/asset.stub';
import { faceStub } from 'test/fixtures/face.stub';
import { personStub } from 'test/fixtures/person.stub';
import { AssetFaceFactory } from 'test/factories/asset-face.factory';
import { AssetFactory } from 'test/factories/asset.factory';
import { PersonFactory } from 'test/factories/person.factory';
describe('mapAsset', () => {
describe('peopleWithFaces', () => {
it('should transform all faces when a person has multiple faces in the same image', () => {
const person = PersonFactory.create();
const face1 = {
...faceStub.primaryFace1,
boundingBoxX1: 100,
boundingBoxY1: 100,
boundingBoxX2: 200,
@@ -18,8 +18,6 @@ describe('mapAsset', () => {
};
const face2 = {
...faceStub.primaryFace1,
id: 'assetFaceId-second',
boundingBoxX1: 300,
boundingBoxY1: 400,
boundingBoxX2: 400,
@@ -28,16 +26,22 @@ describe('mapAsset', () => {
imageHeight: 800,
};
const asset = {
...assetStub.withCropEdit,
faces: [face1, face2],
exifInfo: {
exifImageWidth: 1000,
exifImageHeight: 800,
},
};
const asset = AssetFactory.from()
.face(face1, (builder) => builder.person(person))
.face(face2, (builder) => builder.person(person))
.exif({ exifImageWidth: 1000, exifImageHeight: 800 })
.edit({
action: AssetEditAction.Crop,
parameters: {
width: 1512,
height: 1152,
x: 216,
y: 1512,
},
})
.build();
const result = mapAsset(asset as any);
const result = mapAsset(asset);
expect(result.people).toBeDefined();
expect(result.people).toHaveLength(1);
@@ -61,32 +65,22 @@ describe('mapAsset', () => {
});
it('should transform unassigned faces with edits and dimensions', () => {
const unassignedFace = {
...faceStub.noPerson1,
const unassignedFace = AssetFaceFactory.create({
boundingBoxX1: 100,
boundingBoxY1: 100,
boundingBoxX2: 200,
boundingBoxY2: 200,
imageWidth: 1000,
imageHeight: 800,
};
});
const asset = {
...assetStub.withCropEdit,
faces: [unassignedFace],
exifInfo: {
exifImageWidth: 1000,
exifImageHeight: 800,
},
edits: [
{
action: AssetEditAction.Crop,
parameters: { x: 50, y: 50, width: 500, height: 400 },
},
],
};
const asset = AssetFactory.from()
.face(unassignedFace)
.exif({ exifImageWidth: 1000, exifImageHeight: 800 })
.edit({ action: AssetEditAction.Crop, parameters: { x: 50, y: 50, width: 500, height: 400 } })
.build();
const result = mapAsset(asset as any);
const result = mapAsset(asset);
expect(result.unassignedFaces).toBeDefined();
expect(result.unassignedFaces).toHaveLength(1);
@@ -101,10 +95,6 @@ describe('mapAsset', () => {
it('should handle multiple people each with multiple faces', () => {
const person1Face1 = {
...faceStub.primaryFace1,
id: 'face-1-1',
person: personStub.withName,
personId: personStub.withName.id,
boundingBoxX1: 100,
boundingBoxY1: 100,
boundingBoxX2: 200,
@@ -114,10 +104,6 @@ describe('mapAsset', () => {
};
const person1Face2 = {
...faceStub.primaryFace1,
id: 'face-1-2',
person: personStub.withName,
personId: personStub.withName.id,
boundingBoxX1: 300,
boundingBoxY1: 300,
boundingBoxX2: 400,
@@ -127,10 +113,6 @@ describe('mapAsset', () => {
};
const person2Face1 = {
...faceStub.mergeFace1,
id: 'face-2-1',
person: personStub.mergePerson,
personId: personStub.mergePerson.id,
boundingBoxX1: 500,
boundingBoxY1: 100,
boundingBoxX2: 600,
@@ -139,23 +121,22 @@ describe('mapAsset', () => {
imageHeight: 800,
};
const asset = {
...assetStub.withCropEdit,
faces: [person1Face1, person1Face2, person2Face1],
exifInfo: {
exifImageWidth: 1000,
exifImageHeight: 800,
},
edits: [],
};
const person = PersonFactory.create({ id: 'person-1' });
const result = mapAsset(asset as any);
const asset = AssetFactory.from()
.face(person1Face1, (builder) => builder.person(person))
.face(person1Face2, (builder) => builder.person(person))
.face(person2Face1, (builder) => builder.person({ id: 'person-2' }))
.exif({ exifImageWidth: 1000, exifImageHeight: 800 })
.build();
const result = mapAsset(asset);
expect(result.people).toBeDefined();
expect(result.people).toHaveLength(2);
const person1 = result.people!.find((p) => p.id === personStub.withName.id);
const person2 = result.people!.find((p) => p.id === personStub.mergePerson.id);
const person1 = result.people!.find((p) => p.id === 'person-1');
const person2 = result.people!.find((p) => p.id === 'person-2');
expect(person1).toBeDefined();
expect(person1!.faces).toHaveLength(2);
@@ -173,10 +154,6 @@ describe('mapAsset', () => {
it('should combine faces of the same person into a single entry', () => {
const face1 = {
...faceStub.primaryFace1,
id: 'face-1',
person: personStub.withName,
personId: personStub.withName.id,
boundingBoxX1: 100,
boundingBoxY1: 100,
boundingBoxX2: 200,
@@ -186,10 +163,6 @@ describe('mapAsset', () => {
};
const face2 = {
...faceStub.primaryFace1,
id: 'face-2',
person: personStub.withName,
personId: personStub.withName.id,
boundingBoxX1: 300,
boundingBoxY1: 300,
boundingBoxX2: 400,
@@ -198,24 +171,21 @@ describe('mapAsset', () => {
imageHeight: 800,
};
const asset = {
...assetStub.withCropEdit,
faces: [face1, face2],
exifInfo: {
exifImageWidth: 1000,
exifImageHeight: 800,
},
edits: [],
};
const person = PersonFactory.create();
const result = mapAsset(asset as any);
const asset = AssetFactory.from()
.face(face1, (builder) => builder.person(person))
.face(face2, (builder) => builder.person(person))
.exif({ exifImageWidth: 1000, exifImageHeight: 800 })
.build();
const result = mapAsset(asset);
expect(result.people).toBeDefined();
expect(result.people).toHaveLength(1);
const person = result.people![0];
expect(person.id).toBe(personStub.withName.id);
expect(person.faces).toHaveLength(2);
expect(result.people![0].id).toBe(person.id);
expect(result.people![0].faces).toHaveLength(2);
});
});
});
+11 -3
View File
@@ -1,11 +1,11 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsString } from 'class-validator';
import { SharedLink } from 'src/database';
import { HistoryBuilder } from 'src/decorators';
import { HistoryBuilder, Property } from 'src/decorators';
import { AlbumResponseDto, mapAlbumWithoutAssets } from 'src/dtos/album.dto';
import { AssetResponseDto, mapAsset } from 'src/dtos/asset-response.dto';
import { SharedLinkType } from 'src/enum';
import { Optional, ValidateBoolean, ValidateDate, ValidateEnum, ValidateUUID } from 'src/validation';
import { Optional, ValidateBoolean, ValidateDate, ValidateEnum, ValidateString, ValidateUUID } from 'src/validation';
export class SharedLinkSearchDto {
@ValidateUUID({ optional: true, description: 'Filter by album ID' })
@@ -94,6 +94,11 @@ export class SharedLinkEditDto {
changeExpiryTime?: boolean;
}
export class SharedLinkLoginDto {
@ValidateString({ description: 'Shared link password', example: 'password' })
password!: string;
}
export class SharedLinkPasswordDto {
@ApiPropertyOptional({ example: 'password', description: 'Link password' })
@IsString()
@@ -112,7 +117,10 @@ export class SharedLinkResponseDto {
description!: string | null;
@ApiProperty({ description: 'Has password' })
password!: string | null;
@ApiPropertyOptional({ description: 'Access token' })
@Property({
description: 'Access token',
history: new HistoryBuilder().added('v1').stable('v2').deprecated('v2.6.0'),
})
token?: string | null;
@ApiProperty({ description: 'Owner user ID' })
userId!: string;
@@ -19,7 +19,9 @@ import { GenerateSql } from 'src/decorators';
import { DatabaseExtension, DatabaseLock, VectorIndex } from 'src/enum';
import { ConfigRepository } from 'src/repositories/config.repository';
import { LoggingRepository } from 'src/repositories/logging.repository';
import 'src/schema'; // make sure all schema definitions are imported for schemaFromCode
import { DB } from 'src/schema';
import { schemaDiff, schemaFromCode, schemaFromDatabase } from 'src/sql-tools';
import { ExtensionVersion, VectorExtension, VectorUpdateResult } from 'src/types';
import { vectorIndexQuery } from 'src/utils/database';
import { isValidInteger } from 'src/validation';
@@ -281,6 +283,27 @@ export class DatabaseRepository {
return rows[0].db;
}
getMigrations() {
return this.db.selectFrom('kysely_migrations').select(['name', 'timestamp']).orderBy('name', 'asc').execute();
}
async getSchemaDrift() {
const source = schemaFromCode({ overrides: true, namingStrategy: 'default' });
const target = await schemaFromDatabase(this.db, {});
const drift = schemaDiff(source, target, {
tables: { ignoreExtra: true },
constraints: { ignoreExtra: false },
indexes: { ignoreExtra: true },
triggers: { ignoreExtra: true },
columns: { ignoreExtra: true },
functions: { ignoreExtra: false },
parameters: { ignoreExtra: true },
});
return drift;
}
async getDimensionSize(table: string, column = 'embedding'): Promise<number> {
const { rows } = await sql<{ dimsize: number }>`
SELECT atttypmod as dimsize
@@ -106,7 +106,7 @@ export class MetadataRepository {
readTags(path: string): Promise<ImmichTags> {
const args = mimeTypes.isVideo(path) ? ['-ee'] : [];
return this.exiftool.read(path, args).catch((error) => {
return this.exiftool.read(path, { readArgs: args }).catch((error) => {
this.logger.warn(`Error reading exif data (${path}): ${error}\n${error?.stack}`);
return {};
}) as Promise<ImmichTags>;
+2
View File
@@ -168,6 +168,8 @@ export interface Migrations {
}
export interface DB {
kysely_migrations: { timestamp: string; name: string };
activity: ActivityTable;
album: AlbumTable;
@@ -1,4 +1,5 @@
import { Kysely, sql } from 'kysely';
import { ErrorMessages } from 'src/constants';
import { DatabaseExtension } from 'src/enum';
import { getVectorExtension } from 'src/repositories/database.repository';
import { LoggingRepository } from 'src/repositories/logging.repository';
@@ -16,9 +17,7 @@ export async function up(db: Kysely<any>): Promise<void> {
rows: [lastMigration],
} = await lastMigrationSql.execute(db);
if (lastMigration?.name !== 'AddMissingIndex1744910873956') {
throw new Error(
'Invalid upgrade path. For more information, see https://docs.immich.app/errors/#typeorm-upgrade',
);
throw new Error(ErrorMessages.TypeOrmUpgrade);
}
logger.log('Database has up to date TypeORM migrations, skipping initial Kysely migration');
return;
+135 -177
View File
@@ -9,13 +9,16 @@ import { AssetFile } from 'src/database';
import { AssetMediaStatus, AssetRejectReason, AssetUploadAction } from 'src/dtos/asset-media-response.dto';
import { AssetMediaCreateDto, AssetMediaReplaceDto, AssetMediaSize, UploadFieldName } from 'src/dtos/asset-media.dto';
import { MapAsset } from 'src/dtos/asset-response.dto';
import { AssetEditAction } from 'src/dtos/editing.dto';
import { AssetFileType, AssetStatus, AssetType, AssetVisibility, CacheControl, JobName } from 'src/enum';
import { AuthRequest } from 'src/middleware/auth.guard';
import { AssetMediaService } from 'src/services/asset-media.service';
import { UploadBody } from 'src/types';
import { ASSET_CHECKSUM_CONSTRAINT } from 'src/utils/database';
import { ImmichFileResponse } from 'src/utils/file';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFileFactory } from 'test/factories/asset-file.factory';
import { AssetFactory } from 'test/factories/asset.factory';
import { AuthFactory } from 'test/factories/auth.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { fileStub } from 'test/fixtures/file.stub';
import { userStub } from 'test/fixtures/user.stub';
@@ -426,56 +429,52 @@ describe(AssetMediaService.name, () => {
});
it('should handle a live photo', async () => {
mocks.asset.getById.mockResolvedValueOnce(assetStub.livePhotoMotionAsset);
mocks.asset.create.mockResolvedValueOnce(assetStub.livePhotoStillAsset);
const motionAsset = AssetFactory.from({ type: AssetType.Video, visibility: AssetVisibility.Hidden })
.owner(authStub.user1.user)
.build();
const asset = AssetFactory.create({ livePhotoVideoId: motionAsset.id });
mocks.asset.getById.mockResolvedValueOnce(motionAsset);
mocks.asset.create.mockResolvedValueOnce(asset);
await expect(
sut.uploadAsset(
authStub.user1,
{ ...createDto, livePhotoVideoId: 'live-photo-motion-asset' },
fileStub.livePhotoStill,
),
sut.uploadAsset(authStub.user1, { ...createDto, livePhotoVideoId: motionAsset.id }, fileStub.livePhotoStill),
).resolves.toEqual({
status: AssetMediaStatus.CREATED,
id: 'live-photo-still-asset',
id: asset.id,
});
expect(mocks.asset.getById).toHaveBeenCalledWith('live-photo-motion-asset');
expect(mocks.asset.getById).toHaveBeenCalledWith(motionAsset.id);
expect(mocks.asset.update).not.toHaveBeenCalled();
});
it('should hide the linked motion asset', async () => {
mocks.asset.getById.mockResolvedValueOnce({
...assetStub.livePhotoMotionAsset,
visibility: AssetVisibility.Timeline,
});
mocks.asset.create.mockResolvedValueOnce(assetStub.livePhotoStillAsset);
const motionAsset = AssetFactory.from({ type: AssetType.Video }).owner(authStub.user1.user).build();
const asset = AssetFactory.create();
mocks.asset.getById.mockResolvedValueOnce(motionAsset);
mocks.asset.create.mockResolvedValueOnce(asset);
await expect(
sut.uploadAsset(
authStub.user1,
{ ...createDto, livePhotoVideoId: 'live-photo-motion-asset' },
fileStub.livePhotoStill,
),
sut.uploadAsset(authStub.user1, { ...createDto, livePhotoVideoId: motionAsset.id }, fileStub.livePhotoStill),
).resolves.toEqual({
status: AssetMediaStatus.CREATED,
id: 'live-photo-still-asset',
id: asset.id,
});
expect(mocks.asset.getById).toHaveBeenCalledWith('live-photo-motion-asset');
expect(mocks.asset.getById).toHaveBeenCalledWith(motionAsset.id);
expect(mocks.asset.update).toHaveBeenCalledWith({
id: 'live-photo-motion-asset',
id: motionAsset.id,
visibility: AssetVisibility.Hidden,
});
});
it('should handle a sidecar file', async () => {
mocks.asset.getById.mockResolvedValueOnce(assetStub.image);
mocks.asset.create.mockResolvedValueOnce(assetStub.image);
const asset = AssetFactory.from().file({ type: AssetFileType.Sidecar }).build();
mocks.asset.getById.mockResolvedValueOnce(asset);
mocks.asset.create.mockResolvedValueOnce(asset);
await expect(sut.uploadAsset(authStub.user1, createDto, fileStub.photo, fileStub.photoSidecar)).resolves.toEqual({
status: AssetMediaStatus.CREATED,
id: assetStub.image.id,
id: asset.id,
});
expect(mocks.storage.utimes).toHaveBeenCalledWith(
@@ -501,13 +500,14 @@ describe(AssetMediaService.name, () => {
});
it('should download a file', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
mocks.asset.getForOriginal.mockResolvedValue(assetStub.image);
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForOriginal.mockResolvedValue(asset);
await expect(sut.downloadOriginal(authStub.admin, 'asset-1', {})).resolves.toEqual(
await expect(sut.downloadOriginal(authStub.admin, asset.id, {})).resolves.toEqual(
new ImmichFileResponse({
path: '/original/path.jpg',
fileName: 'asset-id.jpg',
path: asset.originalPath,
fileName: asset.originalFileName,
contentType: 'image/jpeg',
cacheControl: CacheControl.PrivateWithCache,
}),
@@ -515,28 +515,19 @@ describe(AssetMediaService.name, () => {
});
it('should download edited file by default when edits exist', async () => {
const editedAsset = {
...assetStub.withCropEdit,
files: [
...assetStub.withCropEdit.files,
{
id: 'edited-file',
type: AssetFileType.FullSize,
path: '/uploads/user-id/fullsize/edited.jpg',
isEdited: true,
},
],
};
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
mocks.asset.getForOriginal.mockResolvedValue({
...editedAsset,
editedPath: '/uploads/user-id/fullsize/edited.jpg',
});
const editedAsset = AssetFactory.from()
.edit()
.files([AssetFileType.FullSize, AssetFileType.Preview, AssetFileType.Thumbnail])
.file({ type: AssetFileType.FullSize, isEdited: true })
.build();
await expect(sut.downloadOriginal(authStub.admin, 'asset-1', { edited: true })).resolves.toEqual(
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([editedAsset.id]));
mocks.asset.getForOriginal.mockResolvedValue({ ...editedAsset, editedPath: editedAsset.files[3].path });
await expect(sut.downloadOriginal(AuthFactory.create(), editedAsset.id, {})).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/fullsize/edited.jpg',
fileName: 'asset-id.jpg',
path: editedAsset.files[3].path,
fileName: editedAsset.originalFileName,
contentType: 'image/jpeg',
cacheControl: CacheControl.PrivateWithCache,
}),
@@ -544,28 +535,19 @@ describe(AssetMediaService.name, () => {
});
it('should download edited file when edited=true', async () => {
const editedAsset = {
...assetStub.withCropEdit,
files: [
...assetStub.withCropEdit.files,
{
id: 'edited-file',
type: AssetFileType.FullSize,
path: '/uploads/user-id/fullsize/edited.jpg',
isEdited: true,
},
],
};
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
mocks.asset.getForOriginal.mockResolvedValue({
...editedAsset,
editedPath: '/uploads/user-id/fullsize/edited.jpg',
});
const editedAsset = AssetFactory.from()
.edit()
.files([AssetFileType.FullSize, AssetFileType.Preview, AssetFileType.Thumbnail])
.file({ type: AssetFileType.FullSize, isEdited: true })
.build();
await expect(sut.downloadOriginal(authStub.admin, 'asset-1', { edited: true })).resolves.toEqual(
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([editedAsset.id]));
mocks.asset.getForOriginal.mockResolvedValue({ ...editedAsset, editedPath: editedAsset.files[3].path });
await expect(sut.downloadOriginal(AuthFactory.create(), editedAsset.id, { edited: true })).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/fullsize/edited.jpg',
fileName: 'asset-id.jpg',
path: editedAsset.files[3].path,
fileName: editedAsset.originalFileName,
contentType: 'image/jpeg',
cacheControl: CacheControl.PrivateWithCache,
}),
@@ -573,28 +555,18 @@ describe(AssetMediaService.name, () => {
});
it('should not return the unedited version if requested using a shared link', async () => {
const editedAsset = {
...assetStub.withCropEdit,
files: [
...assetStub.withCropEdit.files,
{
id: 'edited-file',
type: AssetFileType.FullSize,
path: '/uploads/user-id/fullsize/edited.jpg',
isEdited: true,
},
],
};
mocks.access.asset.checkSharedLinkAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getForOriginal.mockResolvedValue({
...editedAsset,
editedPath: '/uploads/user-id/fullsize/edited.jpg',
});
const fullsizeEdited = AssetFileFactory.create({ type: AssetFileType.FullSize, isEdited: true });
const editedAsset = AssetFactory.from().edit({ action: AssetEditAction.Crop }).file(fullsizeEdited).build();
await expect(sut.downloadOriginal(authStub.adminSharedLink, 'asset-id', { edited: false })).resolves.toEqual(
mocks.access.asset.checkSharedLinkAccess.mockResolvedValue(new Set([editedAsset.id]));
mocks.asset.getForOriginal.mockResolvedValue({ ...editedAsset, editedPath: fullsizeEdited.path });
await expect(
sut.downloadOriginal(AuthFactory.from().sharedLink().build(), editedAsset.id, { edited: false }),
).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/fullsize/edited.jpg',
fileName: 'asset-id.jpg',
path: fullsizeEdited.path,
fileName: editedAsset.originalFileName,
contentType: 'image/jpeg',
cacheControl: CacheControl.PrivateWithCache,
}),
@@ -602,25 +574,19 @@ describe(AssetMediaService.name, () => {
});
it('should download original file when edited=false', async () => {
const editedAsset = {
...assetStub.withCropEdit,
files: [
...assetStub.withCropEdit.files,
{
id: 'edited-file',
type: AssetFileType.FullSize,
path: '/uploads/user-id/fullsize/edited.jpg',
isEdited: true,
},
],
};
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
const editedAsset = AssetFactory.from()
.edit()
.files([AssetFileType.FullSize, AssetFileType.Preview, AssetFileType.Thumbnail])
.file({ type: AssetFileType.FullSize, isEdited: true })
.build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([editedAsset.id]));
mocks.asset.getForOriginal.mockResolvedValue(editedAsset);
await expect(sut.downloadOriginal(authStub.admin, 'asset-1', { edited: false })).resolves.toEqual(
await expect(sut.downloadOriginal(AuthFactory.create(), editedAsset.id, { edited: false })).resolves.toEqual(
new ImmichFileResponse({
path: '/original/path.jpg',
fileName: 'asset-id.jpg',
path: editedAsset.originalPath,
fileName: editedAsset.originalFileName,
contentType: 'image/jpeg',
cacheControl: CacheControl.PrivateWithCache,
}),
@@ -638,129 +604,118 @@ describe(AssetMediaService.name, () => {
});
it('should fall back to preview if the requested thumbnail file does not exist', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...assetStub.image, path: '/path/to/preview.jpg' });
const asset = AssetFactory.from().file({ type: AssetFileType.Preview }).build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...asset, path: asset.files[0].path });
await expect(
sut.viewThumbnail(authStub.admin, assetStub.image.id, { size: AssetMediaSize.THUMBNAIL }),
).resolves.toEqual(
await expect(sut.viewThumbnail(authStub.admin, asset.id, { size: AssetMediaSize.THUMBNAIL })).resolves.toEqual(
new ImmichFileResponse({
path: '/path/to/preview.jpg',
path: asset.files[0].path,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'image/jpeg',
fileName: 'asset-id_thumbnail.jpg',
fileName: `IMG_${asset.id}_thumbnail.jpg`,
}),
);
});
it('should get preview file', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...assetStub.image, path: '/uploads/user-id/thumbs/path.jpg' });
await expect(
sut.viewThumbnail(authStub.admin, assetStub.image.id, { size: AssetMediaSize.PREVIEW }),
).resolves.toEqual(
const asset = AssetFactory.from().file({ type: AssetFileType.Preview }).build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...asset, path: asset.files[0].path });
await expect(sut.viewThumbnail(authStub.admin, asset.id, { size: AssetMediaSize.PREVIEW })).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/thumbs/path.jpg',
path: asset.files[0].path,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'image/jpeg',
fileName: 'asset-id_preview.jpg',
fileName: `IMG_${asset.id}_preview.jpg`,
}),
);
});
it('should get thumbnail file', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...assetStub.image, path: '/uploads/user-id/webp/path.ext' });
await expect(
sut.viewThumbnail(authStub.admin, assetStub.image.id, { size: AssetMediaSize.THUMBNAIL }),
).resolves.toEqual(
const asset = AssetFactory.from()
.file({ type: AssetFileType.Thumbnail, path: '/uploads/user-id/webp/path.ext' })
.build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...asset, path: asset.files[0].path });
await expect(sut.viewThumbnail(authStub.admin, asset.id, { size: AssetMediaSize.THUMBNAIL })).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/webp/path.ext',
path: asset.files[0].path,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'application/octet-stream',
fileName: 'asset-id_thumbnail.ext',
fileName: `IMG_${asset.id}_thumbnail.ext`,
}),
);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(assetStub.image.id, AssetFileType.Thumbnail, false);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(asset.id, AssetFileType.Thumbnail, false);
});
it('should get original thumbnail by default', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getForThumbnail.mockResolvedValue({
...assetStub.image,
path: '/uploads/user-id/thumbs/original-thumbnail.jpg',
});
await expect(
sut.viewThumbnail(authStub.admin, assetStub.image.id, { size: AssetMediaSize.THUMBNAIL }),
).resolves.toEqual(
const asset = AssetFactory.from().file({ type: AssetFileType.Thumbnail }).build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...asset, path: asset.files[0].path });
await expect(sut.viewThumbnail(authStub.admin, asset.id, { size: AssetMediaSize.THUMBNAIL })).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/thumbs/original-thumbnail.jpg',
path: asset.files[0].path,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'image/jpeg',
fileName: 'asset-id_thumbnail.jpg',
fileName: `IMG_${asset.id}_thumbnail.jpg`,
}),
);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(assetStub.image.id, AssetFileType.Thumbnail, false);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(asset.id, AssetFileType.Thumbnail, false);
});
it('should get edited thumbnail when edited=true', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getForThumbnail.mockResolvedValue({
...assetStub.image,
path: '/uploads/user-id/thumbs/edited-thumbnail.jpg',
});
const asset = AssetFactory.from().file({ type: AssetFileType.Thumbnail, isEdited: true }).build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...asset, path: asset.files[0].path });
await expect(
sut.viewThumbnail(authStub.admin, assetStub.image.id, { size: AssetMediaSize.THUMBNAIL, edited: true }),
sut.viewThumbnail(authStub.admin, asset.id, { size: AssetMediaSize.THUMBNAIL, edited: true }),
).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/thumbs/edited-thumbnail.jpg',
path: asset.files[0].path,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'image/jpeg',
fileName: 'asset-id_thumbnail.jpg',
fileName: `IMG_${asset.id}_thumbnail.jpg`,
}),
);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(assetStub.image.id, AssetFileType.Thumbnail, true);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(asset.id, AssetFileType.Thumbnail, true);
});
it('should get original thumbnail when edited=false', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getForThumbnail.mockResolvedValue({
...assetStub.image,
path: '/uploads/user-id/thumbs/original-thumbnail.jpg',
});
const asset = AssetFactory.from().file({ type: AssetFileType.Thumbnail }).build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...asset, path: asset.files[0].path });
await expect(
sut.viewThumbnail(authStub.admin, assetStub.image.id, { size: AssetMediaSize.THUMBNAIL, edited: false }),
sut.viewThumbnail(authStub.admin, asset.id, { size: AssetMediaSize.THUMBNAIL, edited: false }),
).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/thumbs/original-thumbnail.jpg',
path: asset.files[0].path,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'image/jpeg',
fileName: 'asset-id_thumbnail.jpg',
fileName: `IMG_${asset.id}_thumbnail.jpg`,
}),
);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(assetStub.image.id, AssetFileType.Thumbnail, false);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(asset.id, AssetFileType.Thumbnail, false);
});
it('should not return the unedited version if requested using a shared link', async () => {
mocks.access.asset.checkSharedLinkAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getForThumbnail.mockResolvedValue({
...assetStub.image,
path: '/uploads/user-id/thumbs/edited-thumbnail.jpg',
});
const asset = AssetFactory.from().file({ type: AssetFileType.Thumbnail }).build();
mocks.access.asset.checkSharedLinkAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForThumbnail.mockResolvedValue({ ...asset, path: asset.files[0].path });
await expect(
sut.viewThumbnail(authStub.adminSharedLink, assetStub.image.id, {
sut.viewThumbnail(authStub.adminSharedLink, asset.id, {
size: AssetMediaSize.THUMBNAIL,
edited: true,
}),
).resolves.toEqual(
new ImmichFileResponse({
path: '/uploads/user-id/thumbs/edited-thumbnail.jpg',
path: asset.files[0].path,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'image/jpeg',
fileName: 'asset-id_thumbnail.jpg',
fileName: `IMG_${asset.id}_thumbnail.jpg`,
}),
);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(assetStub.image.id, AssetFileType.Thumbnail, true);
expect(mocks.asset.getForThumbnail).toHaveBeenCalledWith(asset.id, AssetFileType.Thumbnail, true);
});
});
@@ -774,18 +729,20 @@ describe(AssetMediaService.name, () => {
});
it('should throw an error if the video asset could not be found', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
await expect(sut.playbackVideo(authStub.admin, assetStub.image.id)).rejects.toBeInstanceOf(NotFoundException);
await expect(sut.playbackVideo(authStub.admin, asset.id)).rejects.toBeInstanceOf(NotFoundException);
});
it('should return the encoded video path if available', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.hasEncodedVideo.id]));
mocks.asset.getForVideo.mockResolvedValue(assetStub.hasEncodedVideo);
const asset = AssetFactory.create({ encodedVideoPath: '/path/to/encoded/video.mp4' });
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForVideo.mockResolvedValue(asset);
await expect(sut.playbackVideo(authStub.admin, assetStub.hasEncodedVideo.id)).resolves.toEqual(
await expect(sut.playbackVideo(authStub.admin, asset.id)).resolves.toEqual(
new ImmichFileResponse({
path: assetStub.hasEncodedVideo.encodedVideoPath!,
path: asset.encodedVideoPath!,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'video/mp4',
}),
@@ -793,12 +750,13 @@ describe(AssetMediaService.name, () => {
});
it('should fall back to the original path', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.video.id]));
mocks.asset.getForVideo.mockResolvedValue(assetStub.video);
const asset = AssetFactory.create({ type: AssetType.Video, originalPath: '/original/path.ext' });
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getForVideo.mockResolvedValue(asset);
await expect(sut.playbackVideo(authStub.admin, assetStub.video.id)).resolves.toEqual(
await expect(sut.playbackVideo(authStub.admin, asset.id)).resolves.toEqual(
new ImmichFileResponse({
path: assetStub.video.originalPath,
path: asset.originalPath,
cacheControl: CacheControl.PrivateWithCache,
contentType: 'application/octet-stream',
}),
+144 -167
View File
@@ -1,16 +1,14 @@
import { BadRequestException } from '@nestjs/common';
import { DateTime } from 'luxon';
import { MapAsset } from 'src/dtos/asset-response.dto';
import { AssetJobName, AssetStatsResponseDto } from 'src/dtos/asset.dto';
import { AssetEditAction } from 'src/dtos/editing.dto';
import { AssetMetadataKey, AssetStatus, AssetType, AssetVisibility, JobName, JobStatus } from 'src/enum';
import { AssetFileType, AssetMetadataKey, AssetStatus, AssetType, AssetVisibility, JobName, JobStatus } from 'src/enum';
import { AssetStats } from 'src/repositories/asset.repository';
import { AssetService } from 'src/services/asset.service';
import { AssetFactory } from 'test/factories/asset.factory';
import { AuthFactory } from 'test/factories/auth.factory';
import { assetStub } from 'test/fixtures/asset.stub';
import { authStub } from 'test/fixtures/auth.stub';
import { factory } from 'test/small.factory';
import { factory, newUuid } from 'test/small.factory';
import { makeStream, newTestService, ServiceMocks } from 'test/utils';
const stats: AssetStats = {
@@ -34,14 +32,8 @@ describe(AssetService.name, () => {
expect(sut).toBeDefined();
});
const mockGetById = (assets: MapAsset[]) => {
mocks.asset.getById.mockImplementation((assetId) => Promise.resolve(assets.find((asset) => asset.id === assetId)));
};
beforeEach(() => {
({ sut, mocks } = newTestService(AssetService));
mockGetById([assetStub.livePhotoStillAsset, assetStub.livePhotoMotionAsset]);
});
describe('getStatistics', () => {
@@ -79,7 +71,7 @@ describe(AssetService.name, () => {
describe('getRandom', () => {
it('should get own random assets', async () => {
mocks.partner.getAll.mockResolvedValue([]);
mocks.asset.getRandom.mockResolvedValue([assetStub.image]);
mocks.asset.getRandom.mockResolvedValue([AssetFactory.create()]);
await sut.getRandom(authStub.admin, 1);
@@ -90,7 +82,7 @@ describe(AssetService.name, () => {
const partner = factory.partner({ inTimeline: false });
const auth = factory.auth({ user: { id: partner.sharedWithId } });
mocks.asset.getRandom.mockResolvedValue([assetStub.image]);
mocks.asset.getRandom.mockResolvedValue([AssetFactory.create()]);
mocks.partner.getAll.mockResolvedValue([partner]);
await sut.getRandom(auth, 1);
@@ -102,7 +94,7 @@ describe(AssetService.name, () => {
const partner = factory.partner({ inTimeline: true });
const auth = factory.auth({ user: { id: partner.sharedWithId } });
mocks.asset.getRandom.mockResolvedValue([assetStub.image]);
mocks.asset.getRandom.mockResolvedValue([AssetFactory.create()]);
mocks.partner.getAll.mockResolvedValue([partner]);
await sut.getRandom(auth, 1);
@@ -113,88 +105,90 @@ describe(AssetService.name, () => {
describe('get', () => {
it('should allow owner access', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getById.mockResolvedValue(assetStub.image);
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(asset);
await sut.get(authStub.admin, assetStub.image.id);
await sut.get(authStub.admin, asset.id);
expect(mocks.access.asset.checkOwnerAccess).toHaveBeenCalledWith(
authStub.admin.user.id,
new Set([assetStub.image.id]),
new Set([asset.id]),
undefined,
);
});
it('should allow shared link access', async () => {
mocks.access.asset.checkSharedLinkAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getById.mockResolvedValue(assetStub.image);
const asset = AssetFactory.create();
mocks.access.asset.checkSharedLinkAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(asset);
await sut.get(authStub.adminSharedLink, assetStub.image.id);
await sut.get(authStub.adminSharedLink, asset.id);
expect(mocks.access.asset.checkSharedLinkAccess).toHaveBeenCalledWith(
authStub.adminSharedLink.sharedLink?.id,
new Set([assetStub.image.id]),
new Set([asset.id]),
);
});
it('should strip metadata for shared link if exif is disabled', async () => {
mocks.access.asset.checkSharedLinkAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getById.mockResolvedValue(assetStub.image);
const asset = AssetFactory.from().exif({ description: 'foo' }).build();
mocks.access.asset.checkSharedLinkAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(asset);
const result = await sut.get(
{ ...authStub.adminSharedLink, sharedLink: { ...authStub.adminSharedLink.sharedLink!, showExif: false } },
assetStub.image.id,
asset.id,
);
expect(result).toEqual(expect.objectContaining({ hasMetadata: false }));
expect(result).not.toHaveProperty('exifInfo');
expect(mocks.access.asset.checkSharedLinkAccess).toHaveBeenCalledWith(
authStub.adminSharedLink.sharedLink?.id,
new Set([assetStub.image.id]),
new Set([asset.id]),
);
});
it('should allow partner sharing access', async () => {
mocks.access.asset.checkPartnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getById.mockResolvedValue(assetStub.image);
const asset = AssetFactory.create();
mocks.access.asset.checkPartnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(asset);
await sut.get(authStub.admin, assetStub.image.id);
await sut.get(authStub.admin, asset.id);
expect(mocks.access.asset.checkPartnerAccess).toHaveBeenCalledWith(
authStub.admin.user.id,
new Set([assetStub.image.id]),
);
expect(mocks.access.asset.checkPartnerAccess).toHaveBeenCalledWith(authStub.admin.user.id, new Set([asset.id]));
});
it('should allow shared album access', async () => {
mocks.access.asset.checkAlbumAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.asset.getById.mockResolvedValue(assetStub.image);
const asset = AssetFactory.create();
mocks.access.asset.checkAlbumAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(asset);
await sut.get(authStub.admin, assetStub.image.id);
await sut.get(authStub.admin, asset.id);
expect(mocks.access.asset.checkAlbumAccess).toHaveBeenCalledWith(
authStub.admin.user.id,
new Set([assetStub.image.id]),
);
expect(mocks.access.asset.checkAlbumAccess).toHaveBeenCalledWith(authStub.admin.user.id, new Set([asset.id]));
});
it('should throw an error for no access', async () => {
await expect(sut.get(authStub.admin, assetStub.image.id)).rejects.toBeInstanceOf(BadRequestException);
await expect(sut.get(authStub.admin, AssetFactory.create().id)).rejects.toBeInstanceOf(BadRequestException);
expect(mocks.asset.getById).not.toHaveBeenCalled();
});
it('should throw an error for an invalid shared link', async () => {
await expect(sut.get(authStub.adminSharedLink, assetStub.image.id)).rejects.toBeInstanceOf(BadRequestException);
await expect(sut.get(authStub.adminSharedLink, AssetFactory.create().id)).rejects.toBeInstanceOf(
BadRequestException,
);
expect(mocks.access.asset.checkOwnerAccess).not.toHaveBeenCalled();
expect(mocks.asset.getById).not.toHaveBeenCalled();
});
it('should throw an error if the asset could not be found', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
await expect(sut.get(authStub.admin, assetStub.image.id)).rejects.toBeInstanceOf(BadRequestException);
await expect(sut.get(authStub.admin, asset.id)).rejects.toBeInstanceOf(BadRequestException);
});
});
@@ -208,38 +202,41 @@ describe(AssetService.name, () => {
});
it('should update the asset', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
mocks.asset.getById.mockResolvedValue(assetStub.image);
mocks.asset.update.mockResolvedValue(assetStub.image);
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(asset);
mocks.asset.update.mockResolvedValue(asset);
await sut.update(authStub.admin, 'asset-1', { isFavorite: true });
await sut.update(authStub.admin, asset.id, { isFavorite: true });
expect(mocks.asset.update).toHaveBeenCalledWith({ id: 'asset-1', isFavorite: true });
expect(mocks.asset.update).toHaveBeenCalledWith({ id: asset.id, isFavorite: true });
});
it('should update the exif description', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
mocks.asset.getById.mockResolvedValue(assetStub.image);
mocks.asset.update.mockResolvedValue(assetStub.image);
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(asset);
mocks.asset.update.mockResolvedValue(asset);
await sut.update(authStub.admin, 'asset-1', { description: 'Test description' });
await sut.update(authStub.admin, asset.id, { description: 'Test description' });
expect(mocks.asset.upsertExif).toHaveBeenCalledWith(
{ assetId: 'asset-1', description: 'Test description', lockedProperties: ['description'] },
{ assetId: asset.id, description: 'Test description', lockedProperties: ['description'] },
{ lockedPropertiesBehavior: 'append' },
);
});
it('should update the exif rating', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
mocks.asset.getById.mockResolvedValueOnce(assetStub.image);
mocks.asset.update.mockResolvedValueOnce(assetStub.image);
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValueOnce(asset);
mocks.asset.update.mockResolvedValueOnce(asset);
await sut.update(authStub.admin, 'asset-1', { rating: 3 });
await sut.update(authStub.admin, asset.id, { rating: 3 });
expect(mocks.asset.upsertExif).toHaveBeenCalledWith(
{
assetId: 'asset-1',
assetId: asset.id,
rating: 3,
lockedProperties: ['rating'],
},
@@ -249,74 +246,79 @@ describe(AssetService.name, () => {
it('should fail linking a live video if the motion part could not be found', async () => {
const auth = AuthFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.livePhotoStillAsset.id]));
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
await expect(
sut.update(auth, assetStub.livePhotoStillAsset.id, {
livePhotoVideoId: assetStub.livePhotoMotionAsset.id,
sut.update(auth, asset.id, {
livePhotoVideoId: 'unknown',
}),
).rejects.toBeInstanceOf(BadRequestException);
expect(mocks.asset.update).not.toHaveBeenCalledWith({
id: assetStub.livePhotoStillAsset.id,
livePhotoVideoId: assetStub.livePhotoMotionAsset.id,
id: asset.id,
livePhotoVideoId: 'unknown',
});
expect(mocks.asset.update).not.toHaveBeenCalledWith({
id: assetStub.livePhotoMotionAsset.id,
id: 'unknown',
visibility: AssetVisibility.Timeline,
});
expect(mocks.event.emit).not.toHaveBeenCalledWith('AssetShow', {
assetId: assetStub.livePhotoMotionAsset.id,
assetId: 'unknown',
userId: auth.user.id,
});
});
it('should fail linking a live video if the motion part is not a video', async () => {
const auth = AuthFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.livePhotoStillAsset.id]));
mocks.asset.getById.mockResolvedValue(assetStub.livePhotoStillAsset);
const motionAsset = AssetFactory.from().owner(auth.user).build();
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(asset);
await expect(
sut.update(authStub.admin, assetStub.livePhotoStillAsset.id, {
livePhotoVideoId: assetStub.livePhotoMotionAsset.id,
sut.update(authStub.admin, asset.id, {
livePhotoVideoId: motionAsset.id,
}),
).rejects.toBeInstanceOf(BadRequestException);
expect(mocks.asset.update).not.toHaveBeenCalledWith({
id: assetStub.livePhotoStillAsset.id,
livePhotoVideoId: assetStub.livePhotoMotionAsset.id,
id: asset.id,
livePhotoVideoId: motionAsset.id,
});
expect(mocks.asset.update).not.toHaveBeenCalledWith({
id: assetStub.livePhotoMotionAsset.id,
id: motionAsset.id,
visibility: AssetVisibility.Timeline,
});
expect(mocks.event.emit).not.toHaveBeenCalledWith('AssetShow', {
assetId: assetStub.livePhotoMotionAsset.id,
assetId: motionAsset.id,
userId: auth.user.id,
});
});
it('should fail linking a live video if the motion part has a different owner', async () => {
const auth = AuthFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.livePhotoStillAsset.id]));
mocks.asset.getById.mockResolvedValue(assetStub.livePhotoMotionAsset);
const motionAsset = AssetFactory.create({ type: AssetType.Video });
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValue(motionAsset);
await expect(
sut.update(auth, assetStub.livePhotoStillAsset.id, {
livePhotoVideoId: assetStub.livePhotoMotionAsset.id,
sut.update(auth, asset.id, {
livePhotoVideoId: motionAsset.id,
}),
).rejects.toBeInstanceOf(BadRequestException);
expect(mocks.asset.update).not.toHaveBeenCalledWith({
id: assetStub.livePhotoStillAsset.id,
livePhotoVideoId: assetStub.livePhotoMotionAsset.id,
id: asset.id,
livePhotoVideoId: motionAsset.id,
});
expect(mocks.asset.update).not.toHaveBeenCalledWith({
id: assetStub.livePhotoMotionAsset.id,
id: motionAsset.id,
visibility: AssetVisibility.Timeline,
});
expect(mocks.event.emit).not.toHaveBeenCalledWith('AssetShow', {
assetId: assetStub.livePhotoMotionAsset.id,
assetId: motionAsset.id,
userId: auth.user.id,
});
});
@@ -346,35 +348,40 @@ describe(AssetService.name, () => {
it('should unlink a live video', async () => {
const auth = AuthFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.livePhotoStillAsset.id]));
mocks.asset.getById.mockResolvedValueOnce(assetStub.livePhotoStillAsset);
mocks.asset.getById.mockResolvedValueOnce(assetStub.livePhotoMotionAsset);
mocks.asset.update.mockResolvedValueOnce(assetStub.image);
const motionAsset = AssetFactory.from({ type: AssetType.Video, visibility: AssetVisibility.Hidden })
.owner(auth.user)
.build();
const asset = AssetFactory.create({ livePhotoVideoId: motionAsset.id });
const unlinkedAsset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValueOnce(asset);
mocks.asset.getById.mockResolvedValueOnce(motionAsset);
mocks.asset.update.mockResolvedValueOnce(unlinkedAsset);
await sut.update(auth, assetStub.livePhotoStillAsset.id, { livePhotoVideoId: null });
await sut.update(auth, asset.id, { livePhotoVideoId: null });
expect(mocks.asset.update).toHaveBeenCalledWith({
id: assetStub.livePhotoStillAsset.id,
id: asset.id,
livePhotoVideoId: null,
});
expect(mocks.asset.update).toHaveBeenCalledWith({
id: assetStub.livePhotoMotionAsset.id,
visibility: assetStub.livePhotoStillAsset.visibility,
id: motionAsset.id,
visibility: asset.visibility,
});
expect(mocks.event.emit).toHaveBeenCalledWith('AssetShow', {
assetId: assetStub.livePhotoMotionAsset.id,
assetId: motionAsset.id,
userId: auth.user.id,
});
});
it('should fail unlinking a live video if the asset could not be found', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.livePhotoStillAsset.id]));
// eslint-disable-next-line unicorn/no-useless-undefined
mocks.asset.getById.mockResolvedValueOnce(undefined);
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getById.mockResolvedValueOnce(void 0);
await expect(
sut.update(authStub.admin, assetStub.livePhotoStillAsset.id, { livePhotoVideoId: null }),
).rejects.toBeInstanceOf(BadRequestException);
await expect(sut.update(authStub.admin, asset.id, { livePhotoVideoId: null })).rejects.toBeInstanceOf(
BadRequestException,
);
expect(mocks.asset.update).not.toHaveBeenCalled();
expect(mocks.event.emit).not.toHaveBeenCalled();
@@ -555,7 +562,11 @@ describe(AssetService.name, () => {
describe('handleAssetDeletion', () => {
it('should clean up files', async () => {
const asset = assetStub.image;
const asset = AssetFactory.from()
.file({ type: AssetFileType.Thumbnail })
.file({ type: AssetFileType.Preview })
.file({ type: AssetFileType.FullSize })
.build();
mocks.assetJob.getForAssetDeletion.mockResolvedValue(asset);
await sut.handleAssetDeletion({ id: asset.id, deleteOnDisk: true });
@@ -565,12 +576,7 @@ describe(AssetService.name, () => {
{
name: JobName.FileDelete,
data: {
files: [
'/uploads/user-id/webp/path.ext',
'/uploads/user-id/thumbs/path.jpg',
'/uploads/user-id/fullsize/path.webp',
asset.originalPath,
],
files: [...asset.files.map(({ path }) => path), asset.originalPath],
},
},
],
@@ -579,91 +585,60 @@ describe(AssetService.name, () => {
});
it('should delete the entire stack if deleted asset was the primary asset and the stack would only contain one asset afterwards', async () => {
const asset = AssetFactory.from()
.stack({}, (builder) => builder.asset())
.build();
mocks.stack.delete.mockResolvedValue();
mocks.assetJob.getForAssetDeletion.mockResolvedValue({
...assetStub.primaryImage,
stack: {
id: 'stack-id',
primaryAssetId: assetStub.primaryImage.id,
assets: [{ id: 'one-asset' }],
},
...asset,
// TODO the specific query filters out the primary asset from `stack.assets`. This should be in a mapper eventually
stack: { ...asset.stack!, assets: asset.stack!.assets.filter(({ id }) => id !== asset.stack!.primaryAssetId) },
});
await sut.handleAssetDeletion({ id: assetStub.primaryImage.id, deleteOnDisk: true });
await sut.handleAssetDeletion({ id: asset.id, deleteOnDisk: true });
expect(mocks.stack.delete).toHaveBeenCalledWith('stack-id');
expect(mocks.stack.delete).toHaveBeenCalledWith(asset.stackId);
});
it('should delete a live photo', async () => {
mocks.assetJob.getForAssetDeletion.mockResolvedValue(assetStub.livePhotoStillAsset as any);
const motionAsset = AssetFactory.from({ type: AssetType.Video, visibility: AssetVisibility.Hidden }).build();
const asset = AssetFactory.create({ livePhotoVideoId: motionAsset.id });
mocks.assetJob.getForAssetDeletion.mockResolvedValue(asset);
mocks.asset.getLivePhotoCount.mockResolvedValue(0);
await sut.handleAssetDeletion({
id: assetStub.livePhotoStillAsset.id,
id: asset.id,
deleteOnDisk: true,
});
expect(mocks.job.queue.mock.calls).toEqual([
[
{
name: JobName.AssetDelete,
data: {
id: assetStub.livePhotoMotionAsset.id,
deleteOnDisk: true,
},
},
],
[
{
name: JobName.FileDelete,
data: {
files: [
'/uploads/user-id/webp/path.ext',
'/uploads/user-id/thumbs/path.jpg',
'/uploads/user-id/fullsize/path.webp',
'fake_path/asset_1.jpeg',
],
},
},
],
[{ name: JobName.AssetDelete, data: { id: motionAsset.id, deleteOnDisk: true } }],
[{ name: JobName.FileDelete, data: { files: [asset.originalPath] } }],
]);
});
it('should not delete a live motion part if it is being used by another asset', async () => {
const asset = AssetFactory.create({ livePhotoVideoId: newUuid() });
mocks.asset.getLivePhotoCount.mockResolvedValue(2);
mocks.assetJob.getForAssetDeletion.mockResolvedValue(assetStub.livePhotoStillAsset as any);
mocks.assetJob.getForAssetDeletion.mockResolvedValue(asset);
await sut.handleAssetDeletion({
id: assetStub.livePhotoStillAsset.id,
deleteOnDisk: true,
});
await sut.handleAssetDeletion({ id: asset.id, deleteOnDisk: true });
expect(mocks.job.queue.mock.calls).toEqual([
[
{
name: JobName.FileDelete,
data: {
files: [
'/uploads/user-id/webp/path.ext',
'/uploads/user-id/thumbs/path.jpg',
'/uploads/user-id/fullsize/path.webp',
'fake_path/asset_1.jpeg',
],
},
},
],
[{ name: JobName.FileDelete, data: { files: [`/data/library/IMG_${asset.id}.jpg`] } }],
]);
});
it('should update usage', async () => {
mocks.assetJob.getForAssetDeletion.mockResolvedValue(assetStub.image);
await sut.handleAssetDeletion({ id: assetStub.image.id, deleteOnDisk: true });
expect(mocks.user.updateUsage).toHaveBeenCalledWith(assetStub.image.ownerId, -5000);
const asset = AssetFactory.from().exif({ fileSizeInByte: 5000 }).build();
mocks.assetJob.getForAssetDeletion.mockResolvedValue(asset);
await sut.handleAssetDeletion({ id: asset.id, deleteOnDisk: true });
expect(mocks.user.updateUsage).toHaveBeenCalledWith(asset.ownerId, -5000);
});
it('should fail if asset could not be found', async () => {
mocks.assetJob.getForAssetDeletion.mockResolvedValue(void 0);
await expect(sut.handleAssetDeletion({ id: assetStub.image.id, deleteOnDisk: true })).resolves.toBe(
await expect(sut.handleAssetDeletion({ id: AssetFactory.create().id, deleteOnDisk: true })).resolves.toBe(
JobStatus.Failed,
);
});
@@ -681,28 +656,30 @@ describe(AssetService.name, () => {
it('should return OCR data for an asset', async () => {
const ocr1 = factory.assetOcr({ text: 'Hello World' });
const ocr2 = factory.assetOcr({ text: 'Test Image' });
const asset = AssetFactory.from().exif().build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.ocr.getByAssetId.mockResolvedValue([ocr1, ocr2]);
mocks.asset.getById.mockResolvedValue(assetStub.image);
mocks.asset.getById.mockResolvedValue(asset);
await expect(sut.getOcr(authStub.admin, 'asset-1')).resolves.toEqual([ocr1, ocr2]);
await expect(sut.getOcr(authStub.admin, asset.id)).resolves.toEqual([ocr1, ocr2]);
expect(mocks.access.asset.checkOwnerAccess).toHaveBeenCalledWith(
authStub.admin.user.id,
new Set(['asset-1']),
new Set([asset.id]),
undefined,
);
expect(mocks.ocr.getByAssetId).toHaveBeenCalledWith('asset-1');
expect(mocks.ocr.getByAssetId).toHaveBeenCalledWith(asset.id);
});
it('should return empty array when no OCR data exists', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
const asset = AssetFactory.from().exif().build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.ocr.getByAssetId.mockResolvedValue([]);
mocks.asset.getById.mockResolvedValue(assetStub.image);
await expect(sut.getOcr(authStub.admin, 'asset-1')).resolves.toEqual([]);
mocks.asset.getById.mockResolvedValue(asset);
await expect(sut.getOcr(authStub.admin, asset.id)).resolves.toEqual([]);
expect(mocks.ocr.getByAssetId).toHaveBeenCalledWith('asset-1');
expect(mocks.ocr.getByAssetId).toHaveBeenCalledWith(asset.id);
});
});
@@ -746,7 +723,7 @@ describe(AssetService.name, () => {
describe('getUserAssetsByDeviceId', () => {
it('get assets by device id', async () => {
const assets = [assetStub.image, assetStub.image1];
const assets = [AssetFactory.create(), AssetFactory.create()];
mocks.asset.getAllByDeviceId.mockResolvedValue(assets.map((asset) => asset.deviceAssetId));
+45 -1
View File
@@ -1,15 +1,59 @@
import { Injectable } from '@nestjs/common';
import { isAbsolute } from 'node:path';
import { isAbsolute, join } from 'node:path';
import { SALT_ROUNDS } from 'src/constants';
import { MaintenanceAuthDto } from 'src/dtos/maintenance.dto';
import { UserAdminResponseDto, mapUserAdmin } from 'src/dtos/user.dto';
import { MaintenanceAction, SystemMetadataKey } from 'src/enum';
import { BaseService } from 'src/services/base.service';
import { schemaDiff } from 'src/sql-tools';
import { createMaintenanceLoginUrl, generateMaintenanceSecret } from 'src/utils/maintenance';
import { getExternalDomain } from 'src/utils/misc';
export type SchemaReport = {
migrations: MigrationStatus[];
drift: ReturnType<typeof schemaDiff>;
};
type MigrationStatus = {
name: string;
status: 'applied' | 'missing' | 'deleted';
};
@Injectable()
export class CliService extends BaseService {
async schemaReport(): Promise<SchemaReport> {
// eslint-disable-next-line unicorn/prefer-module
const allFiles = await this.storageRepository.readdir(join(__dirname, '../schema/migrations'));
const files = allFiles.filter((file) => file.endsWith('.js')).map((file) => file.slice(0, -3));
const rows = await this.databaseRepository.getMigrations();
const filesSet = new Set(files);
const rowsSet = new Set(rows.map((item) => item.name));
const combined = [...filesSet, ...rowsSet].toSorted();
const migrations: MigrationStatus[] = [];
for (const name of combined) {
if (filesSet.has(name) && rowsSet.has(name)) {
migrations.push({ name, status: 'applied' });
continue;
}
if (filesSet.has(name) && !rowsSet.has(name)) {
migrations.push({ name, status: 'missing' });
continue;
}
if (!filesSet.has(name) && rowsSet.has(name)) {
migrations.push({ name, status: 'deleted' });
continue;
}
}
const drift = await this.databaseRepository.getSchemaDrift();
return { migrations, drift };
}
async listUsers(): Promise<UserAdminResponseDto[]> {
const users = await this.userRepository.getList({ withDeleted: true });
return users.map((user) => mapUserAdmin(user));
@@ -21,6 +21,11 @@ describe(DatabaseService.name, () => {
extensionRange = '0.2.x';
mocks.database.getVectorExtension.mockResolvedValue(DatabaseExtension.VectorChord);
mocks.database.getExtensionVersionRange.mockReturnValue(extensionRange);
mocks.database.getSchemaDrift.mockResolvedValue({
items: [],
asSql: () => [],
asHuman: () => [],
});
versionBelowRange = '0.1.0';
minVersionInRange = '0.2.0';
+12 -1
View File
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common';
import semver from 'semver';
import { EXTENSION_NAMES, VECTOR_EXTENSIONS } from 'src/constants';
import { ErrorMessages, EXTENSION_NAMES, VECTOR_EXTENSIONS } from 'src/constants';
import { OnEvent } from 'src/decorators';
import { BootstrapEventPriority, DatabaseExtension, DatabaseLock, VectorIndex } from 'src/enum';
import { BaseService } from 'src/services/base.service';
@@ -124,6 +124,17 @@ export class DatabaseService extends BaseService {
const { database } = this.configRepository.getEnv();
if (!database.skipMigrations) {
await this.databaseRepository.runMigrations();
this.logger.log('Checking for schema drift');
const drift = await this.databaseRepository.getSchemaDrift();
if (drift.items.length === 0) {
this.logger.log('No schema drift detected');
} else {
this.logger.warn(`${ErrorMessages.SchemaDrift} or run \`immich-admin schema-check\``);
for (const warning of drift.asHuman()) {
this.logger.warn(` - ${warning}`);
}
}
}
await Promise.all([
this.databaseRepository.prewarm(VectorIndex.Clip),
+20 -27
View File
@@ -3,7 +3,6 @@ import { Readable } from 'node:stream';
import { DownloadResponseDto } from 'src/dtos/download.dto';
import { DownloadService } from 'src/services/download.service';
import { AssetFactory } from 'test/factories/asset.factory';
import { assetStub } from 'test/fixtures/asset.stub';
import { authStub } from 'test/fixtures/auth.stub';
import { makeStream, newTestService, ServiceMocks } from 'test/utils';
import { vitest } from 'vitest';
@@ -37,21 +36,18 @@ describe(DownloadService.name, () => {
finalize: vitest.fn(),
stream: new Readable(),
};
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1', 'asset-2']));
mocks.asset.getByIds.mockResolvedValue([{ ...assetStub.noResizePath, id: 'asset-1' }]);
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id, 'unknown-asset']));
mocks.asset.getByIds.mockResolvedValue([asset]);
mocks.storage.createZipStream.mockReturnValue(archiveMock);
await expect(sut.downloadArchive(authStub.admin, { assetIds: ['asset-1', 'asset-2'] })).resolves.toEqual({
await expect(sut.downloadArchive(authStub.admin, { assetIds: [asset.id, 'unknown-asset'] })).resolves.toEqual({
stream: archiveMock.stream,
});
expect(archiveMock.addFile).toHaveBeenCalledTimes(1);
expect(archiveMock.addFile).toHaveBeenNthCalledWith(
1,
expect.stringContaining('/data/library/IMG_123.jpg'),
'IMG_123.jpg',
);
expect(archiveMock.addFile).toHaveBeenNthCalledWith(1, asset.originalPath, asset.originalFileName);
});
it('should log a warning if the original path could not be resolved', async () => {
@@ -108,15 +104,14 @@ describe(DownloadService.name, () => {
finalize: vitest.fn(),
stream: new Readable(),
};
const asset1 = AssetFactory.create({ originalFileName: 'IMG_123.jpg' });
const asset2 = AssetFactory.create({ originalFileName: 'IMG_123.jpg' });
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1', 'asset-2']));
mocks.asset.getByIds.mockResolvedValue([
{ ...assetStub.noResizePath, id: 'asset-1' },
{ ...assetStub.noResizePath, id: 'asset-2' },
]);
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset1.id, asset2.id]));
mocks.asset.getByIds.mockResolvedValue([asset1, asset2]);
mocks.storage.createZipStream.mockReturnValue(archiveMock);
await expect(sut.downloadArchive(authStub.admin, { assetIds: ['asset-1', 'asset-2'] })).resolves.toEqual({
await expect(sut.downloadArchive(authStub.admin, { assetIds: [asset1.id, asset2.id] })).resolves.toEqual({
stream: archiveMock.stream,
});
@@ -131,15 +126,14 @@ describe(DownloadService.name, () => {
finalize: vitest.fn(),
stream: new Readable(),
};
const asset1 = AssetFactory.create({ originalFileName: 'IMG_123.jpg' });
const asset2 = AssetFactory.create({ originalFileName: 'IMG_123.jpg' });
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1', 'asset-2']));
mocks.asset.getByIds.mockResolvedValue([
{ ...assetStub.noResizePath, id: 'asset-2' },
{ ...assetStub.noResizePath, id: 'asset-1' },
]);
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset1.id, asset2.id]));
mocks.asset.getByIds.mockResolvedValue([asset2, asset1]);
mocks.storage.createZipStream.mockReturnValue(archiveMock);
await expect(sut.downloadArchive(authStub.admin, { assetIds: ['asset-1', 'asset-2'] })).resolves.toEqual({
await expect(sut.downloadArchive(authStub.admin, { assetIds: [asset1.id, asset2.id] })).resolves.toEqual({
stream: archiveMock.stream,
});
@@ -155,18 +149,17 @@ describe(DownloadService.name, () => {
stream: new Readable(),
};
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-1']));
mocks.asset.getByIds.mockResolvedValue([
{ ...assetStub.noResizePath, id: 'asset-1', originalPath: '/path/to/symlink.jpg' },
]);
const asset = AssetFactory.create({ originalPath: '/path/to/symlink.jpg' });
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.asset.getByIds.mockResolvedValue([asset]);
mocks.storage.realpath.mockResolvedValue('/path/to/realpath.jpg');
mocks.storage.createZipStream.mockReturnValue(archiveMock);
await expect(sut.downloadArchive(authStub.admin, { assetIds: ['asset-1'] })).resolves.toEqual({
await expect(sut.downloadArchive(authStub.admin, { assetIds: [asset.id] })).resolves.toEqual({
stream: archiveMock.stream,
});
expect(archiveMock.addFile).toHaveBeenCalledWith('/path/to/realpath.jpg', 'IMG_123.jpg');
expect(archiveMock.addFile).toHaveBeenCalledWith('/path/to/realpath.jpg', asset.originalFileName);
});
});
+30 -35
View File
@@ -1,8 +1,9 @@
import { AssetType, AssetVisibility, JobName, JobStatus } from 'src/enum';
import { DuplicateService } from 'src/services/duplicate.service';
import { SearchService } from 'src/services/search.service';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { newUuid } from 'test/small.factory';
import { makeStream, newTestService, ServiceMocks } from 'test/utils';
import { beforeEach, vitest } from 'vitest';
@@ -38,19 +39,17 @@ describe(SearchService.name, () => {
describe('getDuplicates', () => {
it('should get duplicates', async () => {
const asset = AssetFactory.create();
mocks.duplicateRepository.getAll.mockResolvedValue([
{
duplicateId: 'duplicate-id',
assets: [assetStub.image, assetStub.image],
assets: [asset, asset],
},
]);
await expect(sut.getDuplicates(authStub.admin)).resolves.toEqual([
{
duplicateId: 'duplicate-id',
assets: [
expect.objectContaining({ id: assetStub.image.id }),
expect.objectContaining({ id: assetStub.image.id }),
],
assets: [expect.objectContaining({ id: asset.id }), expect.objectContaining({ id: asset.id })],
},
]);
});
@@ -101,7 +100,8 @@ describe(SearchService.name, () => {
});
it('should queue missing assets', async () => {
mocks.assetJob.streamForSearchDuplicates.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForSearchDuplicates.mockReturnValue(makeStream([asset]));
await sut.handleQueueSearchDuplicates({});
@@ -109,13 +109,14 @@ describe(SearchService.name, () => {
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{
name: JobName.AssetDetectDuplicates,
data: { id: assetStub.image.id },
data: { id: asset.id },
},
]);
});
it('should queue all assets', async () => {
mocks.assetJob.streamForSearchDuplicates.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForSearchDuplicates.mockReturnValue(makeStream([asset]));
await sut.handleQueueSearchDuplicates({ force: true });
@@ -123,7 +124,7 @@ describe(SearchService.name, () => {
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{
name: JobName.AssetDetectDuplicates,
data: { id: assetStub.image.id },
data: { id: asset.id },
},
]);
});
@@ -150,9 +151,7 @@ describe(SearchService.name, () => {
},
},
});
const id = assetStub.livePhotoMotionAsset.id;
const result = await sut.handleSearchDuplicates({ id });
const result = await sut.handleSearchDuplicates({ id: newUuid() });
expect(result).toBe(JobStatus.Skipped);
expect(mocks.assetJob.getForSearchDuplicatesJob).not.toHaveBeenCalled();
@@ -167,9 +166,7 @@ describe(SearchService.name, () => {
},
},
});
const id = assetStub.livePhotoMotionAsset.id;
const result = await sut.handleSearchDuplicates({ id });
const result = await sut.handleSearchDuplicates({ id: newUuid() });
expect(result).toBe(JobStatus.Skipped);
expect(mocks.assetJob.getForSearchDuplicatesJob).not.toHaveBeenCalled();
@@ -178,51 +175,49 @@ describe(SearchService.name, () => {
it('should fail if asset is not found', async () => {
mocks.assetJob.getForSearchDuplicatesJob.mockResolvedValue(void 0);
const result = await sut.handleSearchDuplicates({ id: assetStub.image.id });
const asset = AssetFactory.create();
const result = await sut.handleSearchDuplicates({ id: asset.id });
expect(result).toBe(JobStatus.Failed);
expect(mocks.logger.error).toHaveBeenCalledWith(`Asset ${assetStub.image.id} not found`);
expect(mocks.logger.error).toHaveBeenCalledWith(`Asset ${asset.id} not found`);
});
it('should skip if asset is part of stack', async () => {
const id = assetStub.primaryImage.id;
mocks.assetJob.getForSearchDuplicatesJob.mockResolvedValue({ ...hasEmbedding, stackId: 'stack-id' });
const asset = AssetFactory.from().stack().build();
mocks.assetJob.getForSearchDuplicatesJob.mockResolvedValue({ ...hasEmbedding, stackId: asset.stackId });
const result = await sut.handleSearchDuplicates({ id });
const result = await sut.handleSearchDuplicates({ id: asset.id });
expect(result).toBe(JobStatus.Skipped);
expect(mocks.logger.debug).toHaveBeenCalledWith(`Asset ${id} is part of a stack, skipping`);
expect(mocks.logger.debug).toHaveBeenCalledWith(`Asset ${asset.id} is part of a stack, skipping`);
});
it('should skip if asset is not visible', async () => {
const id = assetStub.livePhotoMotionAsset.id;
mocks.assetJob.getForSearchDuplicatesJob.mockResolvedValue({
...hasEmbedding,
visibility: AssetVisibility.Hidden,
});
const asset = AssetFactory.create({ visibility: AssetVisibility.Hidden });
mocks.assetJob.getForSearchDuplicatesJob.mockResolvedValue({ ...hasEmbedding, ...asset });
const result = await sut.handleSearchDuplicates({ id });
const result = await sut.handleSearchDuplicates({ id: asset.id });
expect(result).toBe(JobStatus.Skipped);
expect(mocks.logger.debug).toHaveBeenCalledWith(`Asset ${id} is not visible, skipping`);
expect(mocks.logger.debug).toHaveBeenCalledWith(`Asset ${asset.id} is not visible, skipping`);
});
it('should fail if asset is missing embedding', async () => {
mocks.assetJob.getForSearchDuplicatesJob.mockResolvedValue({ ...hasEmbedding, embedding: null });
const result = await sut.handleSearchDuplicates({ id: assetStub.image.id });
const asset = AssetFactory.create();
const result = await sut.handleSearchDuplicates({ id: asset.id });
expect(result).toBe(JobStatus.Failed);
expect(mocks.logger.debug).toHaveBeenCalledWith(`Asset ${assetStub.image.id} is missing embedding`);
expect(mocks.logger.debug).toHaveBeenCalledWith(`Asset ${asset.id} is missing embedding`);
});
it('should search for duplicates and update asset with duplicateId', async () => {
mocks.assetJob.getForSearchDuplicatesJob.mockResolvedValue(hasEmbedding);
mocks.duplicateRepository.search.mockResolvedValue([
{ assetId: assetStub.image.id, distance: 0.01, duplicateId: null },
]);
const asset = AssetFactory.create();
mocks.duplicateRepository.search.mockResolvedValue([{ assetId: asset.id, distance: 0.01, duplicateId: null }]);
mocks.duplicateRepository.merge.mockResolvedValue();
const expectedAssetIds = [assetStub.image.id, hasEmbedding.id];
const expectedAssetIds = [asset.id, hasEmbedding.id];
const result = await sut.handleSearchDuplicates({ id: hasEmbedding.id });
+7 -6
View File
@@ -1,7 +1,8 @@
import { ImmichWorker, JobName, JobStatus, QueueName } from 'src/enum';
import { AssetType, ImmichWorker, JobName, JobStatus, QueueName } from 'src/enum';
import { JobService } from 'src/services/job.service';
import { JobItem } from 'src/types';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { newUuid } from 'test/small.factory';
import { newTestService, ServiceMocks } from 'test/utils';
describe(JobService.name, () => {
@@ -55,22 +56,22 @@ describe(JobService.name, () => {
{
item: { name: JobName.AssetGenerateThumbnails, data: { id: 'asset-1' } },
jobs: [],
stub: [assetStub.image],
stub: [AssetFactory.create({ id: 'asset-1' })],
},
{
item: { name: JobName.AssetGenerateThumbnails, data: { id: 'asset-1' } },
jobs: [],
stub: [assetStub.video],
stub: [AssetFactory.create({ id: 'asset-1', type: AssetType.Video })],
},
{
item: { name: JobName.AssetGenerateThumbnails, data: { id: 'asset-1', source: 'upload' } },
jobs: [JobName.SmartSearch, JobName.AssetDetectFaces, JobName.Ocr],
stub: [assetStub.livePhotoStillAsset],
stub: [AssetFactory.create({ id: 'asset-1', livePhotoVideoId: newUuid() })],
},
{
item: { name: JobName.AssetGenerateThumbnails, data: { id: 'asset-1', source: 'upload' } },
jobs: [JobName.SmartSearch, JobName.AssetDetectFaces, JobName.Ocr, JobName.AssetEncodeVideo],
stub: [assetStub.video],
stub: [AssetFactory.create({ id: 'asset-1', type: AssetType.Video })],
},
{
item: { name: JobName.SmartSearch, data: { id: 'asset-1' } },
+59 -51
View File
@@ -5,11 +5,11 @@ import { mapLibrary } from 'src/dtos/library.dto';
import { AssetType, CronJob, ImmichWorker, JobName, JobStatus } from 'src/enum';
import { LibraryService } from 'src/services/library.service';
import { ILibraryBulkIdsJob, ILibraryFileJob } from 'src/types';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { systemConfigStub } from 'test/fixtures/system-config.stub';
import { makeMockWatcher } from 'test/repositories/storage.repository.mock';
import { factory, newUuid } from 'test/small.factory';
import { factory, newDate, newUuid } from 'test/small.factory';
import { makeStream, newTestService, ServiceMocks } from 'test/utils';
import { vitest } from 'vitest';
@@ -299,13 +299,13 @@ describe(LibraryService.name, () => {
it('should queue asset sync', async () => {
const library = factory.library({ importPaths: ['/foo', '/bar'] });
const asset = AssetFactory.create({ libraryId: library.id, isExternal: true });
mocks.library.get.mockResolvedValue(library);
mocks.storage.walk.mockResolvedValue([]);
mocks.library.streamAssetIds.mockReturnValue(makeStream([assetStub.external]));
mocks.storage.walk.mockImplementation(async function* generator() {});
mocks.library.streamAssetIds.mockReturnValue(makeStream([asset]));
mocks.asset.getLibraryAssetCount.mockResolvedValue(1);
mocks.asset.detectOfflineExternalAssets.mockResolvedValue({ numUpdatedRows: 0n });
mocks.library.streamAssetIds.mockReturnValue(makeStream([assetStub.external]));
const response = await sut.handleQueueSyncAssets({ id: library.id });
@@ -315,7 +315,7 @@ describe(LibraryService.name, () => {
libraryId: library.id,
importPaths: library.importPaths,
exclusionPatterns: library.exclusionPatterns,
assetIds: [assetStub.external.id],
assetIds: [asset.id],
progressCounter: 1,
totalAssets: 1,
},
@@ -336,8 +336,9 @@ describe(LibraryService.name, () => {
describe('handleSyncAssets', () => {
it('should offline assets no longer on disk', async () => {
const asset = AssetFactory.create({ libraryId: 'library-id', isExternal: true });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.external.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/'],
exclusionPatterns: [],
@@ -345,20 +346,21 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.external]);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockRejectedValue(new Error('ENOENT, no such file or directory'));
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
expect(mocks.asset.updateAll).toHaveBeenCalledWith([assetStub.external.id], {
expect(mocks.asset.updateAll).toHaveBeenCalledWith([asset.id], {
isOffline: true,
deletedAt: expect.anything(),
});
});
it('should set assets deleted from disk as offline', async () => {
const asset = AssetFactory.create({ libraryId: 'library-id', isExternal: true });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.external.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/data/user2'],
exclusionPatterns: [],
@@ -366,20 +368,21 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.external]);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockRejectedValue(new Error('Could not read file'));
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
expect(mocks.asset.updateAll).toHaveBeenCalledWith([assetStub.external.id], {
expect(mocks.asset.updateAll).toHaveBeenCalledWith([asset.id], {
isOffline: true,
deletedAt: expect.anything(),
});
});
it('should do nothing with offline assets deleted from disk', async () => {
const asset = AssetFactory.create({ isOffline: true, deletedAt: newDate() });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.trashedOffline.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/data/user2'],
exclusionPatterns: [],
@@ -387,7 +390,7 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.trashedOffline]);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockRejectedValue(new Error('Could not read file'));
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
@@ -396,8 +399,9 @@ describe(LibraryService.name, () => {
});
it('should un-trash an asset previously marked as offline', async () => {
const asset = AssetFactory.create({ originalPath: '/original/path.jpg', isOffline: true, deletedAt: newDate() });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.trashedOffline.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/original/'],
exclusionPatterns: [],
@@ -405,20 +409,21 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.trashedOffline]);
mocks.storage.stat.mockResolvedValue({ mtime: assetStub.external.fileModifiedAt } as Stats);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockResolvedValue({ mtime: newDate() } as Stats);
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
expect(mocks.asset.updateAll).toHaveBeenCalledWith([assetStub.external.id], {
expect(mocks.asset.updateAll).toHaveBeenCalledWith([asset.id], {
isOffline: false,
deletedAt: null,
});
});
it('should do nothing with offline asset if covered by exclusion pattern', async () => {
const asset = AssetFactory.create({ originalPath: '/original/path.jpg', isOffline: true, deletedAt: newDate() });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.trashedOffline.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/original/'],
exclusionPatterns: ['**/path.jpg'],
@@ -426,8 +431,8 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.trashedOffline]);
mocks.storage.stat.mockResolvedValue({ mtime: assetStub.external.fileModifiedAt } as Stats);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockResolvedValue({ mtime: newDate() } as Stats);
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
@@ -437,8 +442,9 @@ describe(LibraryService.name, () => {
});
it('should do nothing with offline asset if not in import path', async () => {
const asset = AssetFactory.create({ originalPath: '/original/path.jpg', isOffline: true, deletedAt: newDate() });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.trashedOffline.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/import/'],
exclusionPatterns: [],
@@ -446,8 +452,8 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.trashedOffline]);
mocks.storage.stat.mockResolvedValue({ mtime: assetStub.external.fileModifiedAt } as Stats);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockResolvedValue({ mtime: newDate() } as Stats);
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
@@ -457,8 +463,9 @@ describe(LibraryService.name, () => {
});
it('should do nothing with unchanged online assets', async () => {
const asset = AssetFactory.create({ libraryId: 'library-id', isExternal: true });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.external.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/'],
exclusionPatterns: [],
@@ -466,8 +473,8 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.external]);
mocks.storage.stat.mockResolvedValue({ mtime: assetStub.external.fileModifiedAt } as Stats);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockResolvedValue({ mtime: asset.fileModifiedAt } as Stats);
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
@@ -475,8 +482,9 @@ describe(LibraryService.name, () => {
});
it('should not touch fileCreatedAt when un-trashing an asset previously marked as offline', async () => {
const asset = AssetFactory.create({ isOffline: true, deletedAt: newDate() });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.trashedOffline.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/'],
exclusionPatterns: [],
@@ -484,13 +492,13 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.trashedOffline]);
mocks.storage.stat.mockResolvedValue({ mtime: assetStub.trashedOffline.fileModifiedAt } as Stats);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockResolvedValue({ mtime: newDate() } as Stats);
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
expect(mocks.asset.updateAll).toHaveBeenCalledWith(
[assetStub.trashedOffline.id],
[asset.id],
expect.not.objectContaining({
fileCreatedAt: expect.anything(),
}),
@@ -498,8 +506,9 @@ describe(LibraryService.name, () => {
});
it('should update with online assets that have changed', async () => {
const asset = AssetFactory.create({ libraryId: 'library-id', isExternal: true });
const mockAssetJob: ILibraryBulkIdsJob = {
assetIds: [assetStub.external.id],
assetIds: [asset.id],
libraryId: newUuid(),
importPaths: ['/'],
exclusionPatterns: [],
@@ -507,13 +516,9 @@ describe(LibraryService.name, () => {
progressCounter: 0,
};
if (assetStub.external.fileModifiedAt == null) {
throw new Error('fileModifiedAt is null');
}
const mtime = new Date(asset.fileModifiedAt.getDate() + 1);
const mtime = new Date(assetStub.external.fileModifiedAt.getDate() + 1);
mocks.assetJob.getForSyncAssets.mockResolvedValue([assetStub.external]);
mocks.assetJob.getForSyncAssets.mockResolvedValue([asset]);
mocks.storage.stat.mockResolvedValue({ mtime } as Stats);
await expect(sut.handleSyncAssets(mockAssetJob)).resolves.toBe(JobStatus.Success);
@@ -522,7 +527,7 @@ describe(LibraryService.name, () => {
{
name: JobName.SidecarCheck,
data: {
id: assetStub.external.id,
id: asset.id,
source: 'upload',
},
},
@@ -541,13 +546,14 @@ describe(LibraryService.name, () => {
it('should import a new asset', async () => {
const library = factory.library();
const asset = AssetFactory.create();
const mockLibraryJob: ILibraryFileJob = {
libraryId: library.id,
paths: ['/data/user1/photo.jpg'],
};
mocks.asset.createAll.mockResolvedValue([assetStub.image]);
mocks.asset.createAll.mockResolvedValue([asset]);
mocks.library.get.mockResolvedValue(library);
await expect(sut.handleSyncFiles(mockLibraryJob)).resolves.toBe(JobStatus.Success);
@@ -568,7 +574,7 @@ describe(LibraryService.name, () => {
{
name: JobName.SidecarCheck,
data: {
id: assetStub.image.id,
id: asset.id,
source: 'upload',
},
},
@@ -595,7 +601,7 @@ describe(LibraryService.name, () => {
it('should delete a library', async () => {
const library = factory.library();
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(assetStub.image);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(AssetFactory.create());
mocks.library.get.mockResolvedValue(library);
await sut.delete(library.id);
@@ -607,7 +613,7 @@ describe(LibraryService.name, () => {
it('should allow an external library to be deleted', async () => {
const library = factory.library();
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(assetStub.image);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(AssetFactory.create());
mocks.library.get.mockResolvedValue(library);
await sut.delete(library.id);
@@ -623,7 +629,7 @@ describe(LibraryService.name, () => {
it('should unwatch an external library when deleted', async () => {
const library = factory.library({ importPaths: ['/foo', '/bar'] });
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(assetStub.image);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(AssetFactory.create());
mocks.library.get.mockResolvedValue(library);
mocks.library.getAll.mockResolvedValue([library]);
@@ -955,7 +961,7 @@ describe(LibraryService.name, () => {
mocks.library.get.mockResolvedValue(library);
mocks.library.getAll.mockResolvedValue([library]);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(assetStub.image);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(AssetFactory.create());
mocks.storage.watch.mockImplementation(makeMockWatcher({ items: [{ event: 'add', value: '/foo/photo.jpg' }] }));
await sut.watchAll();
@@ -974,7 +980,7 @@ describe(LibraryService.name, () => {
mocks.library.get.mockResolvedValue(library);
mocks.library.getAll.mockResolvedValue([library]);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(assetStub.image);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(AssetFactory.create());
mocks.storage.watch.mockImplementation(
makeMockWatcher({ items: [{ event: 'change', value: '/foo/photo.jpg' }] }),
);
@@ -992,12 +998,13 @@ describe(LibraryService.name, () => {
it('should handle a file unlink event', async () => {
const library = factory.library({ importPaths: ['/foo', '/bar'] });
const asset = AssetFactory.create();
mocks.library.get.mockResolvedValue(library);
mocks.library.getAll.mockResolvedValue([library]);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(assetStub.image);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(asset);
mocks.storage.watch.mockImplementation(
makeMockWatcher({ items: [{ event: 'unlink', value: assetStub.image.originalPath }] }),
makeMockWatcher({ items: [{ event: 'unlink', value: asset.originalPath }] }),
);
await sut.watchAll();
@@ -1006,16 +1013,17 @@ describe(LibraryService.name, () => {
name: JobName.LibraryRemoveAsset,
data: {
libraryId: library.id,
paths: [assetStub.image.originalPath],
paths: [asset.originalPath],
},
});
});
it('should handle an error event', async () => {
const library = factory.library({ importPaths: ['/foo', '/bar'] });
const asset = AssetFactory.create({ libraryId: library.id, isExternal: true });
mocks.library.get.mockResolvedValue(library);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(assetStub.external);
mocks.asset.getByLibraryIdAndOriginalPath.mockResolvedValue(asset);
mocks.library.getAll.mockResolvedValue([library]);
mocks.storage.watch.mockImplementation(
makeMockWatcher({
@@ -1108,7 +1116,7 @@ describe(LibraryService.name, () => {
const library = factory.library();
mocks.library.get.mockResolvedValue(library);
mocks.library.streamAssetIds.mockReturnValue(makeStream([assetStub.image1]));
mocks.library.streamAssetIds.mockReturnValue(makeStream([AssetFactory.create()]));
await expect(sut.handleDeleteLibrary({ id: library.id })).resolves.toBe(JobStatus.Success);
});
+36 -27
View File
@@ -1,7 +1,8 @@
import { MapService } from 'src/services/map.service';
import { albumStub } from 'test/fixtures/album.stub';
import { assetStub } from 'test/fixtures/asset.stub';
import { authStub } from 'test/fixtures/auth.stub';
import { AlbumFactory } from 'test/factories/album.factory';
import { AssetFactory } from 'test/factories/asset.factory';
import { AuthFactory } from 'test/factories/auth.factory';
import { userStub } from 'test/fixtures/user.stub';
import { factory } from 'test/small.factory';
import { newTestService, ServiceMocks } from 'test/utils';
@@ -15,36 +16,41 @@ describe(MapService.name, () => {
describe('getMapMarkers', () => {
it('should get geo information of assets', async () => {
const asset = assetStub.withLocation;
const auth = AuthFactory.create();
const asset = AssetFactory.from()
.exif({ latitude: 42, longitude: 69, city: 'city', state: 'state', country: 'country' })
.build();
const marker = {
id: asset.id,
lat: asset.exifInfo!.latitude!,
lon: asset.exifInfo!.longitude!,
city: asset.exifInfo!.city,
state: asset.exifInfo!.state,
country: asset.exifInfo!.country,
lat: asset.exifInfo.latitude!,
lon: asset.exifInfo.longitude!,
city: asset.exifInfo.city,
state: asset.exifInfo.state,
country: asset.exifInfo.country,
};
mocks.partner.getAll.mockResolvedValue([]);
mocks.map.getMapMarkers.mockResolvedValue([marker]);
const markers = await sut.getMapMarkers(authStub.user1, {});
const markers = await sut.getMapMarkers(auth, {});
expect(markers).toHaveLength(1);
expect(markers[0]).toEqual(marker);
});
it('should include partner assets', async () => {
const partner = factory.partner();
const auth = factory.auth({ user: { id: partner.sharedWithId } });
const auth = AuthFactory.create();
const partner = factory.partner({ sharedWithId: auth.user.id });
const asset = assetStub.withLocation;
const asset = AssetFactory.from()
.exif({ latitude: 42, longitude: 69, city: 'city', state: 'state', country: 'country' })
.build();
const marker = {
id: asset.id,
lat: asset.exifInfo!.latitude!,
lon: asset.exifInfo!.longitude!,
city: asset.exifInfo!.city,
state: asset.exifInfo!.state,
country: asset.exifInfo!.country,
lat: asset.exifInfo.latitude!,
lon: asset.exifInfo.longitude!,
city: asset.exifInfo.city,
state: asset.exifInfo.state,
country: asset.exifInfo.country,
};
mocks.partner.getAll.mockResolvedValue([partner]);
mocks.map.getMapMarkers.mockResolvedValue([marker]);
@@ -61,21 +67,24 @@ describe(MapService.name, () => {
});
it('should include assets from shared albums', async () => {
const asset = assetStub.withLocation;
const auth = AuthFactory.create(userStub.user1);
const asset = AssetFactory.from()
.exif({ latitude: 42, longitude: 69, city: 'city', state: 'state', country: 'country' })
.build();
const marker = {
id: asset.id,
lat: asset.exifInfo!.latitude!,
lon: asset.exifInfo!.longitude!,
city: asset.exifInfo!.city,
state: asset.exifInfo!.state,
country: asset.exifInfo!.country,
lat: asset.exifInfo.latitude!,
lon: asset.exifInfo.longitude!,
city: asset.exifInfo.city,
state: asset.exifInfo.state,
country: asset.exifInfo.country,
};
mocks.partner.getAll.mockResolvedValue([]);
mocks.map.getMapMarkers.mockResolvedValue([marker]);
mocks.album.getOwned.mockResolvedValue([albumStub.empty]);
mocks.album.getShared.mockResolvedValue([albumStub.sharedWithUser]);
mocks.album.getOwned.mockResolvedValue([AlbumFactory.create()]);
mocks.album.getShared.mockResolvedValue([AlbumFactory.from().albumUser({ userId: userStub.user1.id }).build()]);
const markers = await sut.getMapMarkers(authStub.user1, { withSharedAlbums: true });
const markers = await sut.getMapMarkers(auth, { withSharedAlbums: true });
expect(markers).toHaveLength(1);
expect(markers[0]).toEqual(marker);
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,14 +1,16 @@
import { plainToInstance } from 'class-transformer';
import { defaults, SystemConfig } from 'src/config';
import { AlbumUser } from 'src/database';
import { SystemConfigDto } from 'src/dtos/system-config.dto';
import { AssetFileType, JobName, JobStatus, UserMetadataKey } from 'src/enum';
import { NotificationService } from 'src/services/notification.service';
import { INotifyAlbumUpdateJob } from 'src/types';
import { albumStub } from 'test/fixtures/album.stub';
import { assetStub } from 'test/fixtures/asset.stub';
import { AlbumFactory } from 'test/factories/album.factory';
import { AssetFileFactory } from 'test/factories/asset-file.factory';
import { AssetFactory } from 'test/factories/asset.factory';
import { UserFactory } from 'test/factories/user.factory';
import { notificationStub } from 'test/fixtures/notification.stub';
import { userStub } from 'test/fixtures/user.stub';
import { newUuid } from 'test/small.factory';
import { newTestService, ServiceMocks } from 'test/utils';
const configs = {
@@ -267,14 +269,14 @@ describe(NotificationService.name, () => {
});
it('should skip if recipient could not be found', async () => {
mocks.album.getById.mockResolvedValue(albumStub.empty);
mocks.album.getById.mockResolvedValue(AlbumFactory.create());
await expect(sut.handleAlbumInvite({ id: '', recipientId: '' })).resolves.toBe(JobStatus.Skipped);
expect(mocks.job.queue).not.toHaveBeenCalled();
});
it('should skip if the recipient has email notifications disabled', async () => {
mocks.album.getById.mockResolvedValue(albumStub.empty);
mocks.album.getById.mockResolvedValue(AlbumFactory.create());
mocks.user.get.mockResolvedValue({
...userStub.user1,
metadata: [
@@ -290,7 +292,7 @@ describe(NotificationService.name, () => {
});
it('should skip if the recipient has email notifications for album invite disabled', async () => {
mocks.album.getById.mockResolvedValue(albumStub.empty);
mocks.album.getById.mockResolvedValue(AlbumFactory.create());
mocks.user.get.mockResolvedValue({
...userStub.user1,
metadata: [
@@ -306,7 +308,7 @@ describe(NotificationService.name, () => {
});
it('should send invite email', async () => {
mocks.album.getById.mockResolvedValue(albumStub.empty);
mocks.album.getById.mockResolvedValue(AlbumFactory.create());
mocks.user.get.mockResolvedValue({
...userStub.user1,
metadata: [
@@ -328,7 +330,8 @@ describe(NotificationService.name, () => {
});
it('should send invite email without album thumbnail if thumbnail asset does not exist', async () => {
mocks.album.getById.mockResolvedValue(albumStub.emptyWithValidThumbnail);
const album = AlbumFactory.create({ albumThumbnailAssetId: newUuid() });
mocks.album.getById.mockResolvedValue(album);
mocks.user.get.mockResolvedValue({
...userStub.user1,
metadata: [
@@ -345,7 +348,7 @@ describe(NotificationService.name, () => {
await expect(sut.handleAlbumInvite({ id: '', recipientId: '' })).resolves.toBe(JobStatus.Success);
expect(mocks.assetJob.getAlbumThumbnailFiles).toHaveBeenCalledWith(
albumStub.emptyWithValidThumbnail.albumThumbnailAssetId,
album.albumThumbnailAssetId,
AssetFileType.Thumbnail,
);
expect(mocks.job.queue).toHaveBeenCalledWith({
@@ -358,7 +361,9 @@ describe(NotificationService.name, () => {
});
it('should send invite email with album thumbnail as jpeg', async () => {
mocks.album.getById.mockResolvedValue(albumStub.emptyWithValidThumbnail);
const assetFile = AssetFileFactory.create({ type: AssetFileType.Thumbnail });
const album = AlbumFactory.create({ albumThumbnailAssetId: assetFile.assetId });
mocks.album.getById.mockResolvedValue(album);
mocks.user.get.mockResolvedValue({
...userStub.user1,
metadata: [
@@ -371,13 +376,11 @@ describe(NotificationService.name, () => {
mocks.systemMetadata.get.mockResolvedValue({ server: {} });
mocks.notification.create.mockResolvedValue(notificationStub.albumEvent);
mocks.email.renderEmail.mockResolvedValue({ html: '', text: '' });
mocks.assetJob.getAlbumThumbnailFiles.mockResolvedValue([
{ id: '1', type: AssetFileType.Thumbnail, path: 'path-to-thumb.jpg', isEdited: false },
]);
mocks.assetJob.getAlbumThumbnailFiles.mockResolvedValue([assetFile]);
await expect(sut.handleAlbumInvite({ id: '', recipientId: '' })).resolves.toBe(JobStatus.Success);
expect(mocks.assetJob.getAlbumThumbnailFiles).toHaveBeenCalledWith(
albumStub.emptyWithValidThumbnail.albumThumbnailAssetId,
album.albumThumbnailAssetId,
AssetFileType.Thumbnail,
);
expect(mocks.job.queue).toHaveBeenCalledWith({
@@ -390,7 +393,9 @@ describe(NotificationService.name, () => {
});
it('should send invite email with album thumbnail and arbitrary extension', async () => {
mocks.album.getById.mockResolvedValue(albumStub.emptyWithValidThumbnail);
const asset = AssetFactory.from().file({ type: AssetFileType.Thumbnail }).build();
const album = AlbumFactory.from({ albumThumbnailAssetId: asset.id }).asset(asset).build();
mocks.album.getById.mockResolvedValue(album);
mocks.user.get.mockResolvedValue({
...userStub.user1,
metadata: [
@@ -403,18 +408,18 @@ describe(NotificationService.name, () => {
mocks.systemMetadata.get.mockResolvedValue({ server: {} });
mocks.notification.create.mockResolvedValue(notificationStub.albumEvent);
mocks.email.renderEmail.mockResolvedValue({ html: '', text: '' });
mocks.assetJob.getAlbumThumbnailFiles.mockResolvedValue([{ ...assetStub.image.files[2], isEdited: false }]);
mocks.assetJob.getAlbumThumbnailFiles.mockResolvedValue([asset.files[0]]);
await expect(sut.handleAlbumInvite({ id: '', recipientId: '' })).resolves.toBe(JobStatus.Success);
expect(mocks.assetJob.getAlbumThumbnailFiles).toHaveBeenCalledWith(
albumStub.emptyWithValidThumbnail.albumThumbnailAssetId,
album.albumThumbnailAssetId,
AssetFileType.Thumbnail,
);
expect(mocks.job.queue).toHaveBeenCalledWith({
name: JobName.SendMail,
data: expect.objectContaining({
subject: expect.stringContaining('You have been added to a shared album'),
imageAttachments: [{ filename: 'album-thumbnail.ext', path: expect.anything(), cid: expect.anything() }],
imageAttachments: [{ filename: 'album-thumbnail.jpg', path: expect.anything(), cid: expect.anything() }],
}),
});
});
@@ -427,85 +432,74 @@ describe(NotificationService.name, () => {
});
it('should skip if owner could not be found', async () => {
mocks.album.getById.mockResolvedValue(albumStub.emptyWithValidThumbnail);
mocks.album.getById.mockResolvedValue(AlbumFactory.create({ ownerId: 'non-existent' }));
await expect(sut.handleAlbumUpdate({ id: '', recipientId: '1' })).resolves.toBe(JobStatus.Skipped);
expect(mocks.systemMetadata.get).not.toHaveBeenCalled();
});
it('should skip recipient that could not be looked up', async () => {
mocks.album.getById.mockResolvedValue({
...albumStub.emptyWithValidThumbnail,
albumUsers: [{ user: { id: userStub.user1.id } } as AlbumUser],
});
mocks.user.get.mockResolvedValueOnce(userStub.user1);
const album = AlbumFactory.from().albumUser({ userId: 'non-existent' }).build();
mocks.album.getById.mockResolvedValue(album);
mocks.user.get.mockResolvedValueOnce(album.owner);
mocks.notification.create.mockResolvedValue(notificationStub.albumEvent);
mocks.email.renderEmail.mockResolvedValue({ html: '', text: '' });
mocks.assetJob.getAlbumThumbnailFiles.mockResolvedValue([]);
await sut.handleAlbumUpdate({ id: '', recipientId: userStub.user1.id });
expect(mocks.user.get).toHaveBeenCalledWith(userStub.user1.id, { withDeleted: false });
await sut.handleAlbumUpdate({ id: '', recipientId: 'non-existent' });
expect(mocks.user.get).toHaveBeenCalledWith('non-existent', { withDeleted: false });
expect(mocks.email.renderEmail).not.toHaveBeenCalled();
});
it('should skip recipient with disabled email notifications', async () => {
mocks.album.getById.mockResolvedValue({
...albumStub.emptyWithValidThumbnail,
albumUsers: [{ user: { id: userStub.user1.id } } as AlbumUser],
});
mocks.user.get.mockResolvedValue({
...userStub.user1,
metadata: [
{
key: UserMetadataKey.Preferences,
value: { emailNotifications: { enabled: false, albumUpdate: true } },
},
],
});
const user = UserFactory.from()
.metadata({
key: UserMetadataKey.Preferences,
value: { emailNotifications: { enabled: false, albumUpdate: true } },
})
.build();
const album = AlbumFactory.from().albumUser({ userId: user.id }).build();
mocks.album.getById.mockResolvedValue(album);
mocks.user.get.mockResolvedValue(user);
mocks.notification.create.mockResolvedValue(notificationStub.albumEvent);
mocks.email.renderEmail.mockResolvedValue({ html: '', text: '' });
mocks.assetJob.getAlbumThumbnailFiles.mockResolvedValue([]);
await sut.handleAlbumUpdate({ id: '', recipientId: userStub.user1.id });
expect(mocks.user.get).toHaveBeenCalledWith(userStub.user1.id, { withDeleted: false });
await sut.handleAlbumUpdate({ id: '', recipientId: user.id });
expect(mocks.user.get).toHaveBeenCalledWith(user.id, { withDeleted: false });
expect(mocks.email.renderEmail).not.toHaveBeenCalled();
});
it('should skip recipient with disabled email notifications for the album update event', async () => {
mocks.album.getById.mockResolvedValue({
...albumStub.emptyWithValidThumbnail,
albumUsers: [{ user: { id: userStub.user1.id } } as AlbumUser],
});
mocks.user.get.mockResolvedValue({
...userStub.user1,
metadata: [
{
key: UserMetadataKey.Preferences,
value: { emailNotifications: { enabled: true, albumUpdate: false } },
},
],
});
const user = UserFactory.from()
.metadata({
key: UserMetadataKey.Preferences,
value: { emailNotifications: { enabled: true, albumUpdate: false } },
})
.build();
const album = AlbumFactory.from().albumUser({ userId: user.id }).build();
mocks.album.getById.mockResolvedValue(album);
mocks.user.get.mockResolvedValue(user);
mocks.notification.create.mockResolvedValue(notificationStub.albumEvent);
mocks.email.renderEmail.mockResolvedValue({ html: '', text: '' });
mocks.assetJob.getAlbumThumbnailFiles.mockResolvedValue([]);
await sut.handleAlbumUpdate({ id: '', recipientId: userStub.user1.id });
expect(mocks.user.get).toHaveBeenCalledWith(userStub.user1.id, { withDeleted: false });
await sut.handleAlbumUpdate({ id: '', recipientId: user.id });
expect(mocks.user.get).toHaveBeenCalledWith(user.id, { withDeleted: false });
expect(mocks.email.renderEmail).not.toHaveBeenCalled();
});
it('should send email', async () => {
mocks.album.getById.mockResolvedValue({
...albumStub.emptyWithValidThumbnail,
albumUsers: [{ user: { id: userStub.user1.id } } as AlbumUser],
});
mocks.user.get.mockResolvedValue(userStub.user1);
const user = UserFactory.create();
const album = AlbumFactory.from().albumUser({ userId: user.id }).build();
mocks.album.getById.mockResolvedValue(album);
mocks.user.get.mockResolvedValue(user);
mocks.notification.create.mockResolvedValue(notificationStub.albumEvent);
mocks.email.renderEmail.mockResolvedValue({ html: '', text: '' });
mocks.assetJob.getAlbumThumbnailFiles.mockResolvedValue([]);
await sut.handleAlbumUpdate({ id: '', recipientId: userStub.user1.id });
expect(mocks.user.get).toHaveBeenCalledWith(userStub.user1.id, { withDeleted: false });
await sut.handleAlbumUpdate({ id: '', recipientId: user.id });
expect(mocks.user.get).toHaveBeenCalledWith(user.id, { withDeleted: false });
expect(mocks.email.renderEmail).toHaveBeenCalled();
expect(mocks.job.queue).toHaveBeenCalled();
});
+50 -39
View File
@@ -1,6 +1,6 @@
import { AssetVisibility, ImmichWorker, JobName, JobStatus } from 'src/enum';
import { AssetFileType, AssetVisibility, ImmichWorker, JobName, JobStatus } from 'src/enum';
import { OcrService } from 'src/services/ocr.service';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { systemConfigStub } from 'test/fixtures/system-config.stub';
import { makeStream, newTestService, ServiceMocks } from 'test/utils';
@@ -14,7 +14,7 @@ describe(OcrService.name, () => {
mocks.config.getWorker.mockReturnValue(ImmichWorker.Microservices);
mocks.assetJob.getForOcr.mockResolvedValue({
visibility: AssetVisibility.Timeline,
previewFile: assetStub.image.files[1].path,
previewFile: '/uploads/user-id/thumbs/path.jpg',
});
});
@@ -41,20 +41,22 @@ describe(OcrService.name, () => {
});
it('should queue the assets without ocr', async () => {
mocks.assetJob.streamForOcrJob.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForOcrJob.mockReturnValue(makeStream([asset]));
await sut.handleQueueOcr({ force: false });
expect(mocks.job.queueAll).toHaveBeenCalledWith([{ name: JobName.Ocr, data: { id: assetStub.image.id } }]);
expect(mocks.job.queueAll).toHaveBeenCalledWith([{ name: JobName.Ocr, data: { id: asset.id } }]);
expect(mocks.assetJob.streamForOcrJob).toHaveBeenCalledWith(false);
});
it('should queue all the assets', async () => {
mocks.assetJob.streamForOcrJob.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForOcrJob.mockReturnValue(makeStream([asset]));
await sut.handleQueueOcr({ force: true });
expect(mocks.job.queueAll).toHaveBeenCalledWith([{ name: JobName.Ocr, data: { id: assetStub.image.id } }]);
expect(mocks.job.queueAll).toHaveBeenCalledWith([{ name: JobName.Ocr, data: { id: asset.id } }]);
expect(mocks.assetJob.streamForOcrJob).toHaveBeenCalledWith(true);
});
});
@@ -70,15 +72,17 @@ describe(OcrService.name, () => {
});
it('should skip assets without a resize path', async () => {
const asset = AssetFactory.create();
mocks.assetJob.getForOcr.mockResolvedValue({ visibility: AssetVisibility.Timeline, previewFile: null });
expect(await sut.handleOcr({ id: assetStub.noResizePath.id })).toEqual(JobStatus.Failed);
expect(await sut.handleOcr({ id: asset.id })).toEqual(JobStatus.Failed);
expect(mocks.ocr.upsert).not.toHaveBeenCalled();
expect(mocks.machineLearning.ocr).not.toHaveBeenCalled();
});
it('should save the returned objects', async () => {
const asset = AssetFactory.create();
mocks.machineLearning.ocr.mockResolvedValue({
box: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160],
boxScore: [0.9, 0.8],
@@ -86,7 +90,7 @@ describe(OcrService.name, () => {
textScore: [0.95, 0.85],
});
expect(await sut.handleOcr({ id: assetStub.image.id })).toEqual(JobStatus.Success);
expect(await sut.handleOcr({ id: asset.id })).toEqual(JobStatus.Success);
expect(mocks.machineLearning.ocr).toHaveBeenCalledWith(
'/uploads/user-id/thumbs/path.jpg',
@@ -98,10 +102,10 @@ describe(OcrService.name, () => {
}),
);
expect(mocks.ocr.upsert).toHaveBeenCalledWith(
assetStub.image.id,
asset.id,
[
{
assetId: assetStub.image.id,
assetId: asset.id,
boxScore: 0.9,
text: 'One Two Three',
textScore: 0.95,
@@ -115,7 +119,7 @@ describe(OcrService.name, () => {
y4: 80,
},
{
assetId: assetStub.image.id,
assetId: asset.id,
boxScore: 0.8,
text: 'Four Five',
textScore: 0.85,
@@ -134,6 +138,7 @@ describe(OcrService.name, () => {
});
it('should apply config settings', async () => {
const asset = AssetFactory.create();
mocks.systemMetadata.get.mockResolvedValue({
machineLearning: {
enabled: true,
@@ -148,7 +153,7 @@ describe(OcrService.name, () => {
});
mockOcrResult();
expect(await sut.handleOcr({ id: assetStub.image.id })).toEqual(JobStatus.Success);
expect(await sut.handleOcr({ id: asset.id })).toEqual(JobStatus.Success);
expect(mocks.machineLearning.ocr).toHaveBeenCalledWith(
'/uploads/user-id/thumbs/path.jpg',
@@ -159,16 +164,17 @@ describe(OcrService.name, () => {
maxResolution: 1500,
}),
);
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, [], '');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, [], '');
});
it('should skip invisible assets', async () => {
const asset = AssetFactory.from().file({ type: AssetFileType.Preview }).build();
mocks.assetJob.getForOcr.mockResolvedValue({
visibility: AssetVisibility.Hidden,
previewFile: assetStub.image.files[1].path,
previewFile: asset.files[0].path,
});
expect(await sut.handleOcr({ id: assetStub.livePhotoMotionAsset.id })).toEqual(JobStatus.Skipped);
expect(await sut.handleOcr({ id: asset.id })).toEqual(JobStatus.Skipped);
expect(mocks.machineLearning.ocr).not.toHaveBeenCalled();
expect(mocks.ocr.upsert).not.toHaveBeenCalled();
@@ -177,7 +183,7 @@ describe(OcrService.name, () => {
it('should fail if asset could not be found', async () => {
mocks.assetJob.getForOcr.mockResolvedValue(void 0);
expect(await sut.handleOcr({ id: assetStub.image.id })).toEqual(JobStatus.Failed);
expect(await sut.handleOcr({ id: 'non-existent' })).toEqual(JobStatus.Failed);
expect(mocks.machineLearning.ocr).not.toHaveBeenCalled();
expect(mocks.ocr.upsert).not.toHaveBeenCalled();
@@ -185,79 +191,84 @@ describe(OcrService.name, () => {
describe('search tokenization', () => {
it('should generate bigrams for Chinese text', async () => {
const asset = AssetFactory.create();
mockOcrResult('機器學習');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, expect.any(Array), '機器 器學 學習');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), '機器 器學 學習');
});
it('should generate bigrams for Japanese text', async () => {
const asset = AssetFactory.create();
mockOcrResult('テスト');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, expect.any(Array), 'テス スト');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), 'テス スト');
});
it('should generate bigrams for Korean text', async () => {
const asset = AssetFactory.create();
mockOcrResult('한국어');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, expect.any(Array), '한국 국어');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), '한국 국어');
});
it('should pass through Latin text unchanged', async () => {
const asset = AssetFactory.create();
mockOcrResult('Hello World');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, expect.any(Array), 'Hello World');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), 'Hello World');
});
it('should handle mixed CJK and Latin text', async () => {
const asset = AssetFactory.create();
mockOcrResult('機器學習Model');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, expect.any(Array), '機器 器學 學習 Model');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), '機器 器學 學習 Model');
});
it('should handle year followed by CJK', async () => {
const asset = AssetFactory.create();
mockOcrResult('2024年レポート');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(
assetStub.image.id,
expect.any(Array),
'2024 年レ レポ ポー ート',
);
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), '2024 年レ レポ ポー ート');
});
it('should join multiple OCR boxes', async () => {
const asset = AssetFactory.create();
mockOcrResult('機器', 'Learning');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, expect.any(Array), '機器 Learning');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), '機器 Learning');
});
it('should normalize whitespace', async () => {
const asset = AssetFactory.create();
mockOcrResult(' Hello World ');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, expect.any(Array), 'Hello World');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), 'Hello World');
});
it('should keep single CJK characters', async () => {
const asset = AssetFactory.create();
mockOcrResult('A', '中', 'B');
await sut.handleOcr({ id: assetStub.image.id });
await sut.handleOcr({ id: asset.id });
expect(mocks.ocr.upsert).toHaveBeenCalledWith(assetStub.image.id, expect.any(Array), 'A 中 B');
expect(mocks.ocr.upsert).toHaveBeenCalledWith(asset.id, expect.any(Array), 'A 中 B');
});
});
});
+49 -49
View File
@@ -1,12 +1,12 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { BulkIdErrorReason } from 'src/dtos/asset-ids.response.dto';
import { mapFaces, mapPerson, PersonResponseDto } from 'src/dtos/person.dto';
import { CacheControl, JobName, JobStatus, SourceType, SystemMetadataKey } from 'src/enum';
import { AssetFileType, CacheControl, JobName, JobStatus, SourceType, SystemMetadataKey } from 'src/enum';
import { DetectedFaces } from 'src/repositories/machine-learning.repository';
import { FaceSearchResult } from 'src/repositories/search.repository';
import { PersonService } from 'src/services/person.service';
import { ImmichFileResponse } from 'src/utils/file';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { faceStub } from 'test/fixtures/face.stub';
import { personStub } from 'test/fixtures/person.stub';
@@ -261,7 +261,7 @@ describe(PersonService.name, () => {
it("should update a person's thumbnailPath", async () => {
mocks.person.update.mockResolvedValue(personStub.withName);
mocks.person.getFacesByIds.mockResolvedValue([faceStub.face1]);
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([faceStub.face1.assetId]));
mocks.access.person.checkOwnerAccess.mockResolvedValue(new Set(['person-1']));
await expect(
@@ -331,7 +331,7 @@ describe(PersonService.name, () => {
await expect(
sut.reassignFaces(authStub.admin, personStub.noName.id, {
data: [{ personId: personStub.withName.id, assetId: assetStub.image.id }],
data: [{ personId: personStub.withName.id, assetId: faceStub.face1.assetId }],
}),
).resolves.toBeDefined();
@@ -352,9 +352,10 @@ describe(PersonService.name, () => {
describe('getFacesById', () => {
it('should get the bounding boxes for an asset', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([faceStub.face1.assetId]));
const asset = AssetFactory.from({ id: faceStub.face1.assetId }).exif().build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.person.getFaces.mockResolvedValue([faceStub.primaryFace1]);
mocks.asset.getById.mockResolvedValue(assetStub.image);
mocks.asset.getById.mockResolvedValue(asset);
await expect(sut.getFacesById(authStub.admin, { id: faceStub.face1.assetId })).resolves.toStrictEqual([
mapFaces(faceStub.primaryFace1, authStub.admin),
]);
@@ -455,7 +456,8 @@ describe(PersonService.name, () => {
});
it('should queue missing assets', async () => {
mocks.assetJob.streamForDetectFacesJob.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForDetectFacesJob.mockReturnValue(makeStream([asset]));
await sut.handleQueueDetectFaces({ force: false });
@@ -464,13 +466,14 @@ describe(PersonService.name, () => {
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{
name: JobName.AssetDetectFaces,
data: { id: assetStub.image.id },
data: { id: asset.id },
},
]);
});
it('should queue all assets', async () => {
mocks.assetJob.streamForDetectFacesJob.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForDetectFacesJob.mockReturnValue(makeStream([asset]));
mocks.person.getAllWithoutFaces.mockResolvedValue([personStub.withName]);
await sut.handleQueueDetectFaces({ force: true });
@@ -483,13 +486,14 @@ describe(PersonService.name, () => {
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{
name: JobName.AssetDetectFaces,
data: { id: assetStub.image.id },
data: { id: asset.id },
},
]);
});
it('should refresh all assets', async () => {
mocks.assetJob.streamForDetectFacesJob.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForDetectFacesJob.mockReturnValue(makeStream([asset]));
await sut.handleQueueDetectFaces({ force: undefined });
@@ -501,16 +505,17 @@ describe(PersonService.name, () => {
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{
name: JobName.AssetDetectFaces,
data: { id: assetStub.image.id },
data: { id: asset.id },
},
]);
expect(mocks.job.queue).toHaveBeenCalledWith({ name: JobName.PersonCleanup });
});
it('should delete existing people and faces if forced', async () => {
const asset = AssetFactory.create();
mocks.person.getAll.mockReturnValue(makeStream([faceStub.face1.person, personStub.randomPerson]));
mocks.person.getAllFaces.mockReturnValue(makeStream([faceStub.face1]));
mocks.assetJob.streamForDetectFacesJob.mockReturnValue(makeStream([assetStub.image]));
mocks.assetJob.streamForDetectFacesJob.mockReturnValue(makeStream([asset]));
mocks.person.getAllWithoutFaces.mockResolvedValue([personStub.randomPerson]);
mocks.person.deleteFaces.mockResolvedValue();
@@ -520,7 +525,7 @@ describe(PersonService.name, () => {
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{
name: JobName.AssetDetectFaces,
data: { id: assetStub.image.id },
data: { id: asset.id },
},
]);
expect(mocks.person.delete).toHaveBeenCalledWith([personStub.randomPerson.id]);
@@ -718,26 +723,28 @@ describe(PersonService.name, () => {
});
it('should skip when no resize path', async () => {
mocks.assetJob.getForDetectFacesJob.mockResolvedValue({ ...assetStub.noResizePath, files: [] });
await sut.handleDetectFaces({ id: assetStub.noResizePath.id });
const asset = AssetFactory.create();
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(asset);
await sut.handleDetectFaces({ id: asset.id });
expect(mocks.machineLearning.detectFaces).not.toHaveBeenCalled();
});
it('should handle no results', async () => {
const start = Date.now();
const asset = AssetFactory.from().file({ type: AssetFileType.Preview }).build();
mocks.machineLearning.detectFaces.mockResolvedValue({ imageHeight: 500, imageWidth: 400, faces: [] });
mocks.assetJob.getForDetectFacesJob.mockResolvedValue({ ...assetStub.image, files: [assetStub.image.files[1]] });
await sut.handleDetectFaces({ id: assetStub.image.id });
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(asset);
await sut.handleDetectFaces({ id: asset.id });
expect(mocks.machineLearning.detectFaces).toHaveBeenCalledWith(
'/uploads/user-id/thumbs/path.jpg',
asset.files[0].path,
expect.objectContaining({ minScore: 0.7, modelName: 'buffalo_l' }),
);
expect(mocks.job.queue).not.toHaveBeenCalled();
expect(mocks.job.queueAll).not.toHaveBeenCalled();
expect(mocks.asset.upsertJobStatus).toHaveBeenCalledWith({
assetId: assetStub.image.id,
assetId: asset.id,
facesRecognizedAt: expect.any(Date),
});
const facesRecognizedAt = mocks.asset.upsertJobStatus.mock.calls[0][0].facesRecognizedAt as Date;
@@ -745,14 +752,15 @@ describe(PersonService.name, () => {
});
it('should create a face with no person and queue recognition job', async () => {
const asset = AssetFactory.from().file({ type: AssetFileType.Preview }).build();
mocks.machineLearning.detectFaces.mockResolvedValue(detectFaceMock);
mocks.search.searchFaces.mockResolvedValue([{ ...faceStub.face1, distance: 0.7 }]);
mocks.assetJob.getForDetectFacesJob.mockResolvedValue({ ...assetStub.image, files: [assetStub.image.files[1]] });
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(asset);
mocks.person.refreshFaces.mockResolvedValue();
await sut.handleDetectFaces({ id: assetStub.image.id });
await sut.handleDetectFaces({ id: asset.id });
expect(mocks.person.refreshFaces).toHaveBeenCalledWith([face], [], [faceSearch]);
expect(mocks.person.refreshFaces).toHaveBeenCalledWith([{ ...face, assetId: asset.id }], [], [faceSearch]);
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{ name: JobName.FacialRecognitionQueueAll, data: { force: false } },
{ name: JobName.FacialRecognition, data: { id: faceId } },
@@ -762,14 +770,11 @@ describe(PersonService.name, () => {
});
it('should delete an existing face not among the new detected faces', async () => {
const asset = AssetFactory.from().face(faceStub.primaryFace1).file({ type: AssetFileType.Preview }).build();
mocks.machineLearning.detectFaces.mockResolvedValue({ faces: [], imageHeight: 500, imageWidth: 400 });
mocks.assetJob.getForDetectFacesJob.mockResolvedValue({
...assetStub.image,
faces: [faceStub.primaryFace1],
files: [assetStub.image.files[1]],
});
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(asset);
await sut.handleDetectFaces({ id: assetStub.image.id });
await sut.handleDetectFaces({ id: asset.id });
expect(mocks.person.refreshFaces).toHaveBeenCalledWith([], [faceStub.primaryFace1.id], []);
expect(mocks.job.queueAll).not.toHaveBeenCalled();
@@ -778,17 +783,18 @@ describe(PersonService.name, () => {
});
it('should add new face and delete an existing face not among the new detected faces', async () => {
const asset = AssetFactory.from().face(faceStub.primaryFace1).file({ type: AssetFileType.Preview }).build();
mocks.machineLearning.detectFaces.mockResolvedValue(detectFaceMock);
mocks.assetJob.getForDetectFacesJob.mockResolvedValue({
...assetStub.image,
faces: [faceStub.primaryFace1],
files: [assetStub.image.files[1]],
});
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(asset);
mocks.person.refreshFaces.mockResolvedValue();
await sut.handleDetectFaces({ id: assetStub.image.id });
await sut.handleDetectFaces({ id: asset.id });
expect(mocks.person.refreshFaces).toHaveBeenCalledWith([face], [faceStub.primaryFace1.id], [faceSearch]);
expect(mocks.person.refreshFaces).toHaveBeenCalledWith(
[{ ...face, assetId: asset.id }],
[faceStub.primaryFace1.id],
[faceSearch],
);
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{ name: JobName.FacialRecognitionQueueAll, data: { force: false } },
{ name: JobName.FacialRecognition, data: { id: faceId } },
@@ -798,15 +804,12 @@ describe(PersonService.name, () => {
});
it('should add embedding to matching metadata face', async () => {
const asset = AssetFactory.from().face(faceStub.fromExif1).file({ type: AssetFileType.Preview }).build();
mocks.machineLearning.detectFaces.mockResolvedValue(detectFaceMock);
mocks.assetJob.getForDetectFacesJob.mockResolvedValue({
...assetStub.image,
faces: [faceStub.fromExif1],
files: [assetStub.image.files[1]],
});
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(asset);
mocks.person.refreshFaces.mockResolvedValue();
await sut.handleDetectFaces({ id: assetStub.image.id });
await sut.handleDetectFaces({ id: asset.id });
expect(mocks.person.refreshFaces).toHaveBeenCalledWith(
[],
@@ -819,16 +822,13 @@ describe(PersonService.name, () => {
});
it('should not add embedding to non-matching metadata face', async () => {
const asset = AssetFactory.from().face(faceStub.fromExif2).file({ type: AssetFileType.Preview }).build();
mocks.machineLearning.detectFaces.mockResolvedValue(detectFaceMock);
mocks.assetJob.getForDetectFacesJob.mockResolvedValue({
...assetStub.image,
faces: [faceStub.fromExif2],
files: [assetStub.image.files[1]],
});
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(asset);
await sut.handleDetectFaces({ id: assetStub.image.id });
await sut.handleDetectFaces({ id: asset.id });
expect(mocks.person.refreshFaces).toHaveBeenCalledWith([face], [], [faceSearch]);
expect(mocks.person.refreshFaces).toHaveBeenCalledWith([{ ...face, assetId: asset.id }], [], [faceSearch]);
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{ name: JobName.FacialRecognitionQueueAll, data: { force: false } },
{ name: JobName.FacialRecognition, data: { id: faceId } },
+10 -7
View File
@@ -2,7 +2,8 @@ import { BadRequestException } from '@nestjs/common';
import { mapAsset } from 'src/dtos/asset-response.dto';
import { SearchSuggestionType } from 'src/dtos/search.dto';
import { SearchService } from 'src/services/search.service';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { AuthFactory } from 'test/factories/auth.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { personStub } from 'test/fixtures/person.stub';
import { newTestService, ServiceMocks } from 'test/utils';
@@ -64,16 +65,18 @@ describe(SearchService.name, () => {
describe('getExploreData', () => {
it('should get assets by city and tag', async () => {
const auth = AuthFactory.create();
const asset = AssetFactory.from()
.exif({ latitude: 42, longitude: 69, city: 'city', state: 'state', country: 'country' })
.build();
mocks.asset.getAssetIdByCity.mockResolvedValue({
fieldName: 'exifInfo.city',
items: [{ value: 'test-city', data: assetStub.withLocation.id }],
items: [{ value: 'city', data: asset.id }],
});
mocks.asset.getByIdsWithAllRelationsButStacks.mockResolvedValue([assetStub.withLocation]);
const expectedResponse = [
{ fieldName: 'exifInfo.city', items: [{ value: 'test-city', data: mapAsset(assetStub.withLocation) }] },
];
mocks.asset.getByIdsWithAllRelationsButStacks.mockResolvedValue([asset as never]);
const expectedResponse = [{ fieldName: 'exifInfo.city', items: [{ value: 'city', data: mapAsset(asset) }] }];
const result = await sut.getExploreData(authStub.user1);
const result = await sut.getExploreData(auth);
expect(result).toEqual(expectedResponse);
});
+49 -43
View File
@@ -1,10 +1,10 @@
import { BadRequestException, ForbiddenException, UnauthorizedException } from '@nestjs/common';
import _ from 'lodash';
import { AssetIdErrorReason } from 'src/dtos/asset-ids.response.dto';
import { SharedLinkType } from 'src/enum';
import { SharedLinkService } from 'src/services/shared-link.service';
import { albumStub } from 'test/fixtures/album.stub';
import { assetStub } from 'test/fixtures/asset.stub';
import { AlbumFactory } from 'test/factories/album.factory';
import { AssetFactory } from 'test/factories/asset.factory';
import { SharedLinkFactory } from 'test/factories/shared-link.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { sharedLinkResponseStub, sharedLinkStub } from 'test/fixtures/shared-link.stub';
import { factory } from 'test/small.factory';
@@ -35,14 +35,14 @@ describe(SharedLinkService.name, () => {
describe('getMine', () => {
it('should only work for a public user', async () => {
await expect(sut.getMine(authStub.admin, {})).rejects.toBeInstanceOf(ForbiddenException);
await expect(sut.getMine(authStub.admin, [])).rejects.toBeInstanceOf(ForbiddenException);
expect(mocks.sharedLink.get).not.toHaveBeenCalled();
});
it('should return the shared link for the public user', async () => {
const authDto = authStub.adminSharedLink;
mocks.sharedLink.get.mockResolvedValue(sharedLinkStub.valid);
await expect(sut.getMine(authDto, {})).resolves.toEqual(sharedLinkResponseStub.valid);
await expect(sut.getMine(authDto, [])).resolves.toEqual(sharedLinkResponseStub.valid);
expect(mocks.sharedLink.get).toHaveBeenCalledWith(authDto.user.id, authDto.sharedLink?.id);
});
@@ -55,21 +55,22 @@ describe(SharedLinkService.name, () => {
},
});
mocks.sharedLink.get.mockResolvedValue(sharedLinkStub.readonlyNoExif);
const response = await sut.getMine(authDto, {});
const response = await sut.getMine(authDto, []);
expect(response.assets[0]).toMatchObject({ hasMetadata: false });
expect(mocks.sharedLink.get).toHaveBeenCalledWith(authDto.user.id, authDto.sharedLink?.id);
});
it('should throw an error for an invalid password protected shared link', async () => {
it('should throw an error for a request without a shared link auth token', async () => {
const authDto = authStub.adminSharedLink;
mocks.sharedLink.get.mockResolvedValue(sharedLinkStub.passwordRequired);
await expect(sut.getMine(authDto, {})).rejects.toBeInstanceOf(UnauthorizedException);
await expect(sut.getMine(authDto, [])).rejects.toBeInstanceOf(UnauthorizedException);
expect(mocks.sharedLink.get).toHaveBeenCalledWith(authDto.user.id, authDto.sharedLink?.id);
});
it('should allow a correct password on a password protected shared link', async () => {
it('should accept a valid shared link auth token', async () => {
mocks.sharedLink.get.mockResolvedValue({ ...sharedLinkStub.individual, password: '123' });
await expect(sut.getMine(authStub.adminSharedLink, { password: '123' })).resolves.toBeDefined();
mocks.crypto.hashSha256.mockReturnValue('hashed-auth-token');
await expect(sut.getMine(authStub.adminSharedLink, ['hashed-auth-token'])).resolves.toBeDefined();
expect(mocks.sharedLink.get).toHaveBeenCalledWith(
authStub.adminSharedLink.user.id,
authStub.adminSharedLink.sharedLink?.id,
@@ -120,19 +121,17 @@ describe(SharedLinkService.name, () => {
});
it('should create an album shared link', async () => {
mocks.access.album.checkOwnerAccess.mockResolvedValue(new Set([albumStub.oneAsset.id]));
const album = AlbumFactory.from().asset().build();
mocks.access.album.checkOwnerAccess.mockResolvedValue(new Set([album.id]));
mocks.sharedLink.create.mockResolvedValue(sharedLinkStub.valid);
await sut.create(authStub.admin, { type: SharedLinkType.Album, albumId: albumStub.oneAsset.id });
await sut.create(authStub.admin, { type: SharedLinkType.Album, albumId: album.id });
expect(mocks.access.album.checkOwnerAccess).toHaveBeenCalledWith(
authStub.admin.user.id,
new Set([albumStub.oneAsset.id]),
);
expect(mocks.access.album.checkOwnerAccess).toHaveBeenCalledWith(authStub.admin.user.id, new Set([album.id]));
expect(mocks.sharedLink.create).toHaveBeenCalledWith({
type: SharedLinkType.Album,
userId: authStub.admin.user.id,
albumId: albumStub.oneAsset.id,
albumId: album.id,
allowDownload: true,
allowUpload: true,
description: null,
@@ -144,12 +143,13 @@ describe(SharedLinkService.name, () => {
});
it('should create an individual shared link', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.sharedLink.create.mockResolvedValue(sharedLinkStub.individual);
await sut.create(authStub.admin, {
type: SharedLinkType.Individual,
assetIds: [assetStub.image.id],
assetIds: [asset.id],
showMetadata: true,
allowDownload: true,
allowUpload: true,
@@ -157,7 +157,7 @@ describe(SharedLinkService.name, () => {
expect(mocks.access.asset.checkOwnerAccess).toHaveBeenCalledWith(
authStub.admin.user.id,
new Set([assetStub.image.id]),
new Set([asset.id]),
false,
);
expect(mocks.sharedLink.create).toHaveBeenCalledWith({
@@ -167,7 +167,7 @@ describe(SharedLinkService.name, () => {
allowDownload: true,
slug: null,
allowUpload: true,
assetIds: [assetStub.image.id],
assetIds: [asset.id],
description: null,
expiresAt: null,
showExif: true,
@@ -176,12 +176,13 @@ describe(SharedLinkService.name, () => {
});
it('should create a shared link with allowDownload set to false when showMetadata is false', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id]));
const asset = AssetFactory.create();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([asset.id]));
mocks.sharedLink.create.mockResolvedValue(sharedLinkStub.individual);
await sut.create(authStub.admin, {
type: SharedLinkType.Individual,
assetIds: [assetStub.image.id],
assetIds: [asset.id],
showMetadata: false,
allowDownload: true,
allowUpload: true,
@@ -189,7 +190,7 @@ describe(SharedLinkService.name, () => {
expect(mocks.access.asset.checkOwnerAccess).toHaveBeenCalledWith(
authStub.admin.user.id,
new Set([assetStub.image.id]),
new Set([asset.id]),
false,
);
expect(mocks.sharedLink.create).toHaveBeenCalledWith({
@@ -198,7 +199,7 @@ describe(SharedLinkService.name, () => {
albumId: null,
allowDownload: false,
allowUpload: true,
assetIds: [assetStub.image.id],
assetIds: [asset.id],
description: null,
expiresAt: null,
showExif: false,
@@ -265,25 +266,28 @@ describe(SharedLinkService.name, () => {
});
it('should add assets to a shared link', async () => {
mocks.sharedLink.get.mockResolvedValue(_.cloneDeep(sharedLinkStub.individual));
mocks.sharedLink.create.mockResolvedValue(sharedLinkStub.individual);
mocks.sharedLink.update.mockResolvedValue(sharedLinkStub.individual);
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set(['asset-3']));
const asset = AssetFactory.create();
const sharedLink = SharedLinkFactory.from().asset(asset).build();
const newAsset = AssetFactory.create();
mocks.sharedLink.get.mockResolvedValue(sharedLink);
mocks.sharedLink.create.mockResolvedValue(sharedLink);
mocks.sharedLink.update.mockResolvedValue(sharedLink);
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([newAsset.id]));
await expect(
sut.addAssets(authStub.admin, 'link-1', { assetIds: [assetStub.image.id, 'asset-2', 'asset-3'] }),
sut.addAssets(authStub.admin, sharedLink.id, { assetIds: [asset.id, 'asset-2', newAsset.id] }),
).resolves.toEqual([
{ assetId: assetStub.image.id, success: false, error: AssetIdErrorReason.DUPLICATE },
{ assetId: asset.id, success: false, error: AssetIdErrorReason.DUPLICATE },
{ assetId: 'asset-2', success: false, error: AssetIdErrorReason.NO_PERMISSION },
{ assetId: 'asset-3', success: true },
{ assetId: newAsset.id, success: true },
]);
expect(mocks.access.asset.checkOwnerAccess).toHaveBeenCalledTimes(1);
expect(mocks.sharedLink.update).toHaveBeenCalled();
expect(mocks.sharedLink.update).toHaveBeenCalledWith({
...sharedLinkStub.individual,
...sharedLink,
slug: null,
assetIds: ['asset-3'],
assetIds: [newAsset.id],
});
});
});
@@ -298,20 +302,22 @@ describe(SharedLinkService.name, () => {
});
it('should remove assets from a shared link', async () => {
mocks.sharedLink.get.mockResolvedValue(_.cloneDeep(sharedLinkStub.individual));
mocks.sharedLink.create.mockResolvedValue(sharedLinkStub.individual);
mocks.sharedLink.update.mockResolvedValue(sharedLinkStub.individual);
mocks.sharedLinkAsset.remove.mockResolvedValue([assetStub.image.id]);
const asset = AssetFactory.create();
const sharedLink = SharedLinkFactory.from().asset(asset).build();
mocks.sharedLink.get.mockResolvedValue(sharedLink);
mocks.sharedLink.create.mockResolvedValue(sharedLink);
mocks.sharedLink.update.mockResolvedValue(sharedLink);
mocks.sharedLinkAsset.remove.mockResolvedValue([asset.id]);
await expect(
sut.removeAssets(authStub.admin, 'link-1', { assetIds: [assetStub.image.id, 'asset-2'] }),
sut.removeAssets(authStub.admin, sharedLink.id, { assetIds: [asset.id, 'asset-2'] }),
).resolves.toEqual([
{ assetId: assetStub.image.id, success: true },
{ assetId: asset.id, success: true },
{ assetId: 'asset-2', success: false, error: AssetIdErrorReason.NOT_FOUND },
]);
expect(mocks.sharedLinkAsset.remove).toHaveBeenCalledWith('link-1', [assetStub.image.id, 'asset-2']);
expect(mocks.sharedLink.update).toHaveBeenCalledWith({ ...sharedLinkStub.individual, assets: [] });
expect(mocks.sharedLinkAsset.remove).toHaveBeenCalledWith(sharedLink.id, [asset.id, 'asset-2']);
expect(mocks.sharedLink.update).toHaveBeenCalledWith(expect.objectContaining({ assets: [] }));
});
});
@@ -335,7 +341,7 @@ describe(SharedLinkService.name, () => {
await expect(sut.getMetadataTags(authStub.adminSharedLink)).resolves.toEqual({
description: '1 shared photos & videos',
imageUrl: `https://my.immich.app/api/assets/asset-id/thumbnail?key=LCtkaJX4R1O_9D-2lq0STzsPryoL1UdAbyb6Sna1xxmQCSuqU2J1ZUsqt6GR-yGm1s0`,
imageUrl: `https://my.immich.app/api/assets/${sharedLinkStub.individual.assets[0].id}/thumbnail?key=LCtkaJX4R1O_9D-2lq0STzsPryoL1UdAbyb6Sna1xxmQCSuqU2J1ZUsqt6GR-yGm1s0`,
title: 'Public Share',
});
+31 -18
View File
@@ -1,6 +1,5 @@
import { BadRequestException, ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
import { PostgresError } from 'postgres';
import { SharedLink } from 'src/database';
import { AssetIdErrorReason, AssetIdsResponseDto } from 'src/dtos/asset-ids.response.dto';
import { AssetIdsDto } from 'src/dtos/asset.dto';
import { AuthDto } from 'src/dtos/auth.dto';
@@ -8,7 +7,7 @@ import {
mapSharedLink,
SharedLinkCreateDto,
SharedLinkEditDto,
SharedLinkPasswordDto,
SharedLinkLoginDto,
SharedLinkResponseDto,
SharedLinkSearchDto,
} from 'src/dtos/shared-link.dto';
@@ -24,18 +23,41 @@ export class SharedLinkService extends BaseService {
.then((links) => links.map((link) => mapSharedLink(link, { stripAssetMetadata: false })));
}
async getMine(auth: AuthDto, dto: SharedLinkPasswordDto): Promise<SharedLinkResponseDto> {
async login(auth: AuthDto, dto: SharedLinkLoginDto) {
if (!auth.sharedLink) {
throw new ForbiddenException();
}
const sharedLink = await this.findOrFail(auth.user.id, auth.sharedLink.id);
const response = mapSharedLink(sharedLink, { stripAssetMetadata: !sharedLink.showExif });
if (sharedLink.password) {
response.token = this.validateAndRefreshToken(sharedLink, dto);
const { id, password } = sharedLink;
if (!password) {
throw new BadRequestException('Shared link is not password protected');
}
return response;
if (password !== dto.password) {
throw new UnauthorizedException('Invalid password');
}
return {
sharedLink: mapSharedLink(sharedLink, { stripAssetMetadata: !sharedLink.showExif }),
token: this.asToken({ id, password }),
};
}
async getMine(auth: AuthDto, authTokens: string[]) {
if (!auth.sharedLink) {
throw new ForbiddenException();
}
const sharedLink = await this.findOrFail(auth.user.id, auth.sharedLink.id);
const { id, password } = sharedLink;
if (password && !authTokens.includes(this.asToken({ id, password }))) {
throw new UnauthorizedException('Password required');
}
return mapSharedLink(sharedLink, { stripAssetMetadata: !sharedLink.showExif });
}
async get(auth: AuthDto, id: string): Promise<SharedLinkResponseDto> {
@@ -213,16 +235,7 @@ export class SharedLinkService extends BaseService {
};
}
private validateAndRefreshToken(sharedLink: SharedLink, dto: SharedLinkPasswordDto): string {
const token = this.cryptoRepository.hashSha256(`${sharedLink.id}-${sharedLink.password}`);
const sharedLinkTokens = dto.token?.split(',') || [];
if (sharedLink.password !== dto.password && !sharedLinkTokens.includes(token)) {
throw new UnauthorizedException('Invalid password');
}
if (!sharedLinkTokens.includes(token)) {
sharedLinkTokens.push(token);
}
return sharedLinkTokens.join(',');
private asToken(sharedLink: { id: string; password: string }) {
return this.cryptoRepository.hashSha256(`${sharedLink.id}-${sharedLink.password}`);
}
}
+28 -27
View File
@@ -1,8 +1,8 @@
import { SystemConfig } from 'src/config';
import { ImmichWorker, JobName, JobStatus } from 'src/enum';
import { AssetFileType, AssetVisibility, ImmichWorker, JobName, JobStatus } from 'src/enum';
import { SmartInfoService } from 'src/services/smart-info.service';
import { getCLIPModelInfo } from 'src/utils/misc';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { systemConfigStub } from 'test/fixtures/system-config.stub';
import { makeStream, newTestService, ServiceMocks } from 'test/utils';
@@ -13,7 +13,7 @@ describe(SmartInfoService.name, () => {
beforeEach(() => {
({ sut, mocks } = newTestService(SmartInfoService));
mocks.asset.getByIds.mockResolvedValue([assetStub.image]);
mocks.asset.getByIds.mockResolvedValue([AssetFactory.create()]);
mocks.config.getWorker.mockReturnValue(ImmichWorker.Microservices);
});
@@ -155,25 +155,23 @@ describe(SmartInfoService.name, () => {
});
it('should queue the assets without clip embeddings', async () => {
mocks.assetJob.streamForEncodeClip.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForEncodeClip.mockReturnValue(makeStream([asset]));
await sut.handleQueueEncodeClip({ force: false });
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{ name: JobName.SmartSearch, data: { id: assetStub.image.id } },
]);
expect(mocks.job.queueAll).toHaveBeenCalledWith([{ name: JobName.SmartSearch, data: { id: asset.id } }]);
expect(mocks.assetJob.streamForEncodeClip).toHaveBeenCalledWith(false);
expect(mocks.database.setDimensionSize).not.toHaveBeenCalled();
});
it('should queue all the assets', async () => {
mocks.assetJob.streamForEncodeClip.mockReturnValue(makeStream([assetStub.image]));
const asset = AssetFactory.create();
mocks.assetJob.streamForEncodeClip.mockReturnValue(makeStream([asset]));
await sut.handleQueueEncodeClip({ force: true });
expect(mocks.job.queueAll).toHaveBeenCalledWith([
{ name: JobName.SmartSearch, data: { id: assetStub.image.id } },
]);
expect(mocks.job.queueAll).toHaveBeenCalledWith([{ name: JobName.SmartSearch, data: { id: asset.id } }]);
expect(mocks.assetJob.streamForEncodeClip).toHaveBeenCalledWith(true);
expect(mocks.database.setDimensionSize).toHaveBeenCalledExactlyOnceWith(512);
});
@@ -190,34 +188,36 @@ describe(SmartInfoService.name, () => {
});
it('should skip assets without a resize path', async () => {
mocks.assetJob.getForClipEncoding.mockResolvedValue({ ...assetStub.noResizePath, files: [] });
const asset = AssetFactory.create();
mocks.assetJob.getForClipEncoding.mockResolvedValue(asset);
expect(await sut.handleEncodeClip({ id: assetStub.noResizePath.id })).toEqual(JobStatus.Failed);
expect(await sut.handleEncodeClip({ id: asset.id })).toEqual(JobStatus.Failed);
expect(mocks.search.upsert).not.toHaveBeenCalled();
expect(mocks.machineLearning.encodeImage).not.toHaveBeenCalled();
});
it('should save the returned objects', async () => {
const asset = AssetFactory.from().file({ type: AssetFileType.Preview }).build();
mocks.machineLearning.encodeImage.mockResolvedValue('[0.01, 0.02, 0.03]');
mocks.assetJob.getForClipEncoding.mockResolvedValue({ ...assetStub.image, files: [assetStub.image.files[1]] });
mocks.assetJob.getForClipEncoding.mockResolvedValue(asset);
expect(await sut.handleEncodeClip({ id: assetStub.image.id })).toEqual(JobStatus.Success);
expect(await sut.handleEncodeClip({ id: asset.id })).toEqual(JobStatus.Success);
expect(mocks.machineLearning.encodeImage).toHaveBeenCalledWith(
'/uploads/user-id/thumbs/path.jpg',
asset.files[0].path,
expect.objectContaining({ modelName: 'ViT-B-32__openai' }),
);
expect(mocks.search.upsert).toHaveBeenCalledWith(assetStub.image.id, '[0.01, 0.02, 0.03]');
expect(mocks.search.upsert).toHaveBeenCalledWith(asset.id, '[0.01, 0.02, 0.03]');
});
it('should skip invisible assets', async () => {
mocks.assetJob.getForClipEncoding.mockResolvedValue({
...assetStub.livePhotoMotionAsset,
files: [assetStub.image.files[1]],
});
const asset = AssetFactory.from({ visibility: AssetVisibility.Hidden })
.file({ type: AssetFileType.Preview })
.build();
mocks.assetJob.getForClipEncoding.mockResolvedValue(asset);
expect(await sut.handleEncodeClip({ id: assetStub.livePhotoMotionAsset.id })).toEqual(JobStatus.Skipped);
expect(await sut.handleEncodeClip({ id: asset.id })).toEqual(JobStatus.Skipped);
expect(mocks.machineLearning.encodeImage).not.toHaveBeenCalled();
expect(mocks.search.upsert).not.toHaveBeenCalled();
@@ -226,25 +226,26 @@ describe(SmartInfoService.name, () => {
it('should fail if asset could not be found', async () => {
mocks.assetJob.getForClipEncoding.mockResolvedValue(void 0);
expect(await sut.handleEncodeClip({ id: assetStub.image.id })).toEqual(JobStatus.Failed);
expect(await sut.handleEncodeClip({ id: 'non-existent' })).toEqual(JobStatus.Failed);
expect(mocks.machineLearning.encodeImage).not.toHaveBeenCalled();
expect(mocks.search.upsert).not.toHaveBeenCalled();
});
it('should wait for database', async () => {
const asset = AssetFactory.from().file({ type: AssetFileType.Preview }).build();
mocks.machineLearning.encodeImage.mockResolvedValue('[0.01, 0.02, 0.03]');
mocks.database.isBusy.mockReturnValue(true);
mocks.assetJob.getForClipEncoding.mockResolvedValue({ ...assetStub.image, files: [assetStub.image.files[1]] });
mocks.assetJob.getForClipEncoding.mockResolvedValue(asset);
expect(await sut.handleEncodeClip({ id: assetStub.image.id })).toEqual(JobStatus.Success);
expect(await sut.handleEncodeClip({ id: asset.id })).toEqual(JobStatus.Success);
expect(mocks.database.wait).toHaveBeenCalledWith(512);
expect(mocks.machineLearning.encodeImage).toHaveBeenCalledWith(
'/uploads/user-id/thumbs/path.jpg',
asset.files[0].path,
expect.objectContaining({ modelName: 'ViT-B-32__openai' }),
);
expect(mocks.search.upsert).toHaveBeenCalledWith(assetStub.image.id, '[0.01, 0.02, 0.03]');
expect(mocks.search.upsert).toHaveBeenCalledWith(asset.id, '[0.01, 0.02, 0.03]');
});
});
+77 -57
View File
@@ -1,6 +1,8 @@
import { BadRequestException } from '@nestjs/common';
import { StackService } from 'src/services/stack.service';
import { assetStub, stackStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { AuthFactory } from 'test/factories/auth.factory';
import { StackFactory } from 'test/factories/stack.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { newUuid } from 'test/small.factory';
import { newTestService, ServiceMocks } from 'test/utils';
@@ -19,43 +21,49 @@ describe(StackService.name, () => {
describe('search', () => {
it('should search stacks', async () => {
mocks.stack.search.mockResolvedValue([stackStub('stack-id', [assetStub.image])]);
const auth = AuthFactory.create();
const asset = AssetFactory.create();
const stack = StackFactory.from().primaryAsset(asset).build();
mocks.stack.search.mockResolvedValue([stack]);
await sut.search(authStub.admin, { primaryAssetId: assetStub.image.id });
await sut.search(auth, { primaryAssetId: asset.id });
expect(mocks.stack.search).toHaveBeenCalledWith({
ownerId: authStub.admin.user.id,
primaryAssetId: assetStub.image.id,
ownerId: auth.user.id,
primaryAssetId: asset.id,
});
});
});
describe('create', () => {
it('should require asset.update permissions', async () => {
await expect(
sut.create(authStub.admin, { assetIds: [assetStub.image.id, assetStub.image1.id] }),
).rejects.toBeInstanceOf(BadRequestException);
const auth = AuthFactory.create();
const [primaryAsset, asset] = [AssetFactory.create(), AssetFactory.create()];
await expect(sut.create(auth, { assetIds: [primaryAsset.id, asset.id] })).rejects.toBeInstanceOf(
BadRequestException,
);
expect(mocks.access.asset.checkOwnerAccess).toHaveBeenCalled();
expect(mocks.stack.create).not.toHaveBeenCalled();
});
it('should create a stack', async () => {
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([assetStub.image.id, assetStub.image1.id]));
mocks.stack.create.mockResolvedValue(stackStub('stack-id', [assetStub.image, assetStub.image1]));
await expect(
sut.create(authStub.admin, { assetIds: [assetStub.image.id, assetStub.image1.id] }),
).resolves.toEqual({
id: 'stack-id',
primaryAssetId: assetStub.image.id,
assets: [
expect.objectContaining({ id: assetStub.image.id }),
expect.objectContaining({ id: assetStub.image1.id }),
],
const auth = AuthFactory.create();
const [primaryAsset, asset] = [AssetFactory.create(), AssetFactory.create()];
const stack = StackFactory.from().primaryAsset(primaryAsset).asset(asset).build();
mocks.access.asset.checkOwnerAccess.mockResolvedValue(new Set([primaryAsset.id, asset.id]));
mocks.stack.create.mockResolvedValue(stack);
await expect(sut.create(auth, { assetIds: [primaryAsset.id, asset.id] })).resolves.toEqual({
id: stack.id,
primaryAssetId: primaryAsset.id,
assets: [expect.objectContaining({ id: primaryAsset.id }), expect.objectContaining({ id: asset.id })],
});
expect(mocks.event.emit).toHaveBeenCalledWith('StackCreate', {
stackId: 'stack-id',
userId: authStub.admin.user.id,
stackId: stack.id,
userId: auth.user.id,
});
expect(mocks.access.asset.checkOwnerAccess).toHaveBeenCalled();
});
@@ -79,25 +87,26 @@ describe(StackService.name, () => {
});
it('should get stack', async () => {
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set(['stack-id']));
mocks.stack.getById.mockResolvedValue(stackStub('stack-id', [assetStub.image, assetStub.image1]));
const auth = AuthFactory.create();
const [primaryAsset, asset] = [AssetFactory.create(), AssetFactory.create()];
const stack = StackFactory.from().primaryAsset(primaryAsset).asset(asset).build();
await expect(sut.get(authStub.admin, 'stack-id')).resolves.toEqual({
id: 'stack-id',
primaryAssetId: assetStub.image.id,
assets: [
expect.objectContaining({ id: assetStub.image.id }),
expect.objectContaining({ id: assetStub.image1.id }),
],
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set([stack.id]));
mocks.stack.getById.mockResolvedValue(stack);
await expect(sut.get(auth, stack.id)).resolves.toEqual({
id: stack.id,
primaryAssetId: primaryAsset.id,
assets: [expect.objectContaining({ id: primaryAsset.id }), expect.objectContaining({ id: asset.id })],
});
expect(mocks.access.stack.checkOwnerAccess).toHaveBeenCalled();
expect(mocks.stack.getById).toHaveBeenCalledWith('stack-id');
expect(mocks.stack.getById).toHaveBeenCalledWith(stack.id);
});
});
describe('update', () => {
it('should require stack.update permissions', async () => {
await expect(sut.update(authStub.admin, 'stack-id', {})).rejects.toBeInstanceOf(BadRequestException);
await expect(sut.update(AuthFactory.create(), 'stack-id', {})).rejects.toBeInstanceOf(BadRequestException);
expect(mocks.stack.getById).not.toHaveBeenCalled();
expect(mocks.stack.update).not.toHaveBeenCalled();
@@ -107,7 +116,7 @@ describe(StackService.name, () => {
it('should fail if stack could not be found', async () => {
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set(['stack-id']));
await expect(sut.update(authStub.admin, 'stack-id', {})).rejects.toBeInstanceOf(Error);
await expect(sut.update(AuthFactory.create(), 'stack-id', {})).rejects.toBeInstanceOf(Error);
expect(mocks.stack.getById).toHaveBeenCalledWith('stack-id');
expect(mocks.stack.update).not.toHaveBeenCalled();
@@ -115,55 +124,64 @@ describe(StackService.name, () => {
});
it('should fail if the provided primary asset id is not in the stack', async () => {
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set(['stack-id']));
mocks.stack.getById.mockResolvedValue(stackStub('stack-id', [assetStub.image, assetStub.image1]));
const auth = AuthFactory.create();
const stack = StackFactory.from().primaryAsset().asset().build();
await expect(sut.update(authStub.admin, 'stack-id', { primaryAssetId: 'unknown-asset' })).rejects.toBeInstanceOf(
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set([stack.id]));
mocks.stack.getById.mockResolvedValue(stack);
await expect(sut.update(auth, stack.id, { primaryAssetId: 'unknown-asset' })).rejects.toBeInstanceOf(
BadRequestException,
);
expect(mocks.stack.getById).toHaveBeenCalledWith('stack-id');
expect(mocks.stack.getById).toHaveBeenCalledWith(stack.id);
expect(mocks.stack.update).not.toHaveBeenCalled();
expect(mocks.event.emit).not.toHaveBeenCalled();
});
it('should update stack', async () => {
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set(['stack-id']));
mocks.stack.getById.mockResolvedValue(stackStub('stack-id', [assetStub.image, assetStub.image1]));
mocks.stack.update.mockResolvedValue(stackStub('stack-id', [assetStub.image, assetStub.image1]));
const auth = AuthFactory.create();
const [primaryAsset, asset] = [AssetFactory.create(), AssetFactory.create()];
const stack = StackFactory.from().primaryAsset(primaryAsset).asset(asset).build();
await sut.update(authStub.admin, 'stack-id', { primaryAssetId: assetStub.image1.id });
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set([stack.id]));
mocks.stack.getById.mockResolvedValue(stack);
mocks.stack.update.mockResolvedValue(stack);
expect(mocks.stack.getById).toHaveBeenCalledWith('stack-id');
expect(mocks.stack.update).toHaveBeenCalledWith('stack-id', {
id: 'stack-id',
primaryAssetId: assetStub.image1.id,
await sut.update(auth, stack.id, { primaryAssetId: asset.id });
expect(mocks.stack.getById).toHaveBeenCalledWith(stack.id);
expect(mocks.stack.update).toHaveBeenCalledWith(stack.id, {
id: stack.id,
primaryAssetId: asset.id,
});
expect(mocks.event.emit).toHaveBeenCalledWith('StackUpdate', {
stackId: 'stack-id',
userId: authStub.admin.user.id,
stackId: stack.id,
userId: auth.user.id,
});
});
});
describe('delete', () => {
it('should require stack.delete permissions', async () => {
await expect(sut.delete(authStub.admin, 'stack-id')).rejects.toBeInstanceOf(BadRequestException);
await expect(sut.delete(AuthFactory.create(), 'stack-id')).rejects.toBeInstanceOf(BadRequestException);
expect(mocks.stack.delete).not.toHaveBeenCalled();
expect(mocks.event.emit).not.toHaveBeenCalled();
});
it('should delete stack', async () => {
const auth = AuthFactory.create();
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set(['stack-id']));
mocks.stack.delete.mockResolvedValue();
await sut.delete(authStub.admin, 'stack-id');
await sut.delete(auth, 'stack-id');
expect(mocks.stack.delete).toHaveBeenCalledWith('stack-id');
expect(mocks.event.emit).toHaveBeenCalledWith('StackDelete', {
stackId: 'stack-id',
userId: authStub.admin.user.id,
userId: auth.user.id,
});
});
});
@@ -214,24 +232,26 @@ describe(StackService.name, () => {
});
it('should fail if the assetId is the primaryAssetId', async () => {
const asset = AssetFactory.create();
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set(['stack-id']));
mocks.stack.getForAssetRemoval.mockResolvedValue({ id: 'stack-id', primaryAssetId: assetStub.image.id });
mocks.stack.getForAssetRemoval.mockResolvedValue({ id: 'stack-id', primaryAssetId: asset.id });
await expect(
sut.removeAsset(authStub.admin, { id: 'stack-id', assetId: assetStub.image.id }),
).rejects.toBeInstanceOf(BadRequestException);
await expect(sut.removeAsset(authStub.admin, { id: 'stack-id', assetId: asset.id })).rejects.toBeInstanceOf(
BadRequestException,
);
expect(mocks.asset.update).not.toHaveBeenCalled();
expect(mocks.event.emit).not.toHaveBeenCalled();
});
it("should update the asset to nullify it's stack-id", async () => {
const [primaryAsset, asset] = [AssetFactory.create(), AssetFactory.create()];
mocks.access.stack.checkOwnerAccess.mockResolvedValue(new Set(['stack-id']));
mocks.stack.getForAssetRemoval.mockResolvedValue({ id: 'stack-id', primaryAssetId: assetStub.image.id });
mocks.stack.getForAssetRemoval.mockResolvedValue({ id: 'stack-id', primaryAssetId: primaryAsset.id });
await sut.removeAsset(authStub.admin, { id: 'stack-id', assetId: assetStub.image1.id });
await sut.removeAsset(authStub.admin, { id: 'stack-id', assetId: asset.id });
expect(mocks.asset.update).toHaveBeenCalledWith({ id: assetStub.image1.id, stackId: null });
expect(mocks.asset.update).toHaveBeenCalledWith({ id: asset.id, stackId: null });
expect(mocks.event.emit).toHaveBeenCalledWith('StackUpdate', {
stackId: 'stack-id',
userId: authStub.admin.user.id,
@@ -1,16 +1,14 @@
import { Stats } from 'node:fs';
import { defaults, SystemConfig } from 'src/config';
import { AssetPathType, JobStatus } from 'src/enum';
import { AssetPathType, AssetType, JobStatus } from 'src/enum';
import { StorageTemplateService } from 'src/services/storage-template.service';
import { albumStub } from 'test/fixtures/album.stub';
import { assetStub } from 'test/fixtures/asset.stub';
import { AlbumFactory } from 'test/factories/album.factory';
import { AssetFactory } from 'test/factories/asset.factory';
import { UserFactory } from 'test/factories/user.factory';
import { userStub } from 'test/fixtures/user.stub';
import { factory } from 'test/small.factory';
import { getForStorageTemplate } from 'test/mappers';
import { makeStream, newTestService, ServiceMocks } from 'test/utils';
const motionAsset = assetStub.storageAsset({});
const stillAsset = assetStub.storageAsset({ livePhotoVideoId: motionAsset.id });
describe(StorageTemplateService.name, () => {
let sut: StorageTemplateService;
let mocks: ServiceMocks;
@@ -110,12 +108,27 @@ describe(StorageTemplateService.name, () => {
});
it('should migrate single moving picture', async () => {
const motionAsset = AssetFactory.from({
type: AssetType.Video,
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.exif()
.build();
const stillAsset = AssetFactory.from({
livePhotoVideoId: motionAsset.id,
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.exif()
.build();
mocks.user.get.mockResolvedValue(userStub.user1);
const newMotionPicturePath = `/data/library/${motionAsset.ownerId}/2022/2022-06-19/${motionAsset.originalFileName}`;
const newMotionPicturePath = `/data/library/${motionAsset.ownerId}/2022/2022-06-19/${stillAsset.originalFileName.slice(0, -4)}.mp4`;
const newStillPicturePath = `/data/library/${stillAsset.ownerId}/2022/2022-06-19/${stillAsset.originalFileName}`;
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(stillAsset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(motionAsset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(getForStorageTemplate(stillAsset));
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(getForStorageTemplate(motionAsset));
mocks.move.create.mockResolvedValueOnce({
id: '123',
@@ -141,16 +154,16 @@ describe(StorageTemplateService.name, () => {
});
it('should use handlebar if condition for album', async () => {
const asset = assetStub.storageAsset();
const user = userStub.user1;
const album = albumStub.oneAsset;
const user = UserFactory.create();
const asset = AssetFactory.from().owner(user).exif().build();
const album = AlbumFactory.from().asset().build();
const config = structuredClone(defaults);
config.storageTemplate.template = '{{y}}/{{#if album}}{{album}}{{else}}other/{{MM}}{{/if}}/{{filename}}';
sut.onConfigInit({ newConfig: config });
mocks.user.get.mockResolvedValue(user);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(asset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(getForStorageTemplate(asset));
mocks.album.getByAssetId.mockResolvedValueOnce([album]);
expect(await sut.handleMigrationSingle({ id: asset.id })).toBe(JobStatus.Success);
@@ -166,14 +179,14 @@ describe(StorageTemplateService.name, () => {
});
it('should use handlebar else condition for album', async () => {
const asset = assetStub.storageAsset();
const user = userStub.user1;
const user = UserFactory.create();
const asset = AssetFactory.from().owner(user).exif().build();
const config = structuredClone(defaults);
config.storageTemplate.template = '{{y}}/{{#if album}}{{album}}{{else}}other//{{MM}}{{/if}}/{{filename}}';
sut.onConfigInit({ newConfig: config });
mocks.user.get.mockResolvedValue(user);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(asset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(getForStorageTemplate(asset));
expect(await sut.handleMigrationSingle({ id: asset.id })).toBe(JobStatus.Success);
@@ -189,9 +202,9 @@ describe(StorageTemplateService.name, () => {
});
it('should handle album startDate', async () => {
const asset = assetStub.storageAsset();
const user = userStub.user1;
const album = albumStub.oneAsset;
const user = UserFactory.create();
const asset = AssetFactory.from().owner(user).exif().build();
const album = AlbumFactory.from().asset().build();
const config = structuredClone(defaults);
config.storageTemplate.template =
'{{#if album}}{{album-startDate-y}}/{{album-startDate-MM}} - {{album}}{{else}}{{y}}/{{MM}}/{{/if}}/{{filename}}';
@@ -199,7 +212,7 @@ describe(StorageTemplateService.name, () => {
sut.onConfigInit({ newConfig: config });
mocks.user.get.mockResolvedValue(user);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(asset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(getForStorageTemplate(asset));
mocks.album.getByAssetId.mockResolvedValueOnce([album]);
mocks.album.getMetadataForIds.mockResolvedValueOnce([
{
@@ -225,8 +238,8 @@ describe(StorageTemplateService.name, () => {
});
it('should handle else condition from album startDate', async () => {
const asset = assetStub.storageAsset();
const user = userStub.user1;
const user = UserFactory.create();
const asset = AssetFactory.from().owner(user).exif().build();
const config = structuredClone(defaults);
config.storageTemplate.template =
'{{#if album}}{{album-startDate-y}}/{{album-startDate-MM}} - {{album}}{{else}}{{y}}/{{MM}}/{{/if}}/{{filename}}';
@@ -234,7 +247,7 @@ describe(StorageTemplateService.name, () => {
sut.onConfigInit({ newConfig: config });
mocks.user.get.mockResolvedValue(user);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(asset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(getForStorageTemplate(asset));
expect(await sut.handleMigrationSingle({ id: asset.id })).toBe(JobStatus.Success);
@@ -248,11 +261,18 @@ describe(StorageTemplateService.name, () => {
});
it('should migrate previously failed move from original path when it still exists', async () => {
mocks.user.get.mockResolvedValue(userStub.user1);
const user = UserFactory.create();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.owner(user)
.exif()
.build();
const asset = assetStub.storageAsset();
const previousFailedNewPath = `/data/library/${userStub.user1.id}/2023/Feb/${asset.originalFileName}`;
const newPath = `/data/library/${userStub.user1.id}/2022/2022-06-19/${asset.originalFileName}`;
mocks.user.get.mockResolvedValue(user);
const previousFailedNewPath = `/data/library/${user.id}/2023/Feb/${asset.originalFileName}`;
const newPath = `/data/library/${user.id}/2022/2022-06-19/${asset.originalFileName}`;
mocks.storage.checkFileExists.mockImplementation((path) => Promise.resolve(path === asset.originalPath));
mocks.move.getByEntity.mockResolvedValue({
@@ -262,7 +282,7 @@ describe(StorageTemplateService.name, () => {
oldPath: asset.originalPath,
newPath: previousFailedNewPath,
});
mocks.assetJob.getForStorageTemplateJob.mockResolvedValue(asset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValue(getForStorageTemplate(asset));
mocks.move.update.mockResolvedValue({
id: '123',
entityId: asset.id,
@@ -288,9 +308,16 @@ describe(StorageTemplateService.name, () => {
});
it('should migrate previously failed move from previous new path when old path no longer exists, should validate file size still matches before moving', async () => {
mocks.user.get.mockResolvedValue(userStub.user1);
const user = UserFactory.create();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.owner(user)
.exif({ fileSizeInByte: 5000 })
.build();
mocks.user.get.mockResolvedValue(user);
const asset = assetStub.storageAsset({ fileSizeInByte: 5000 });
const previousFailedNewPath = `/data/library/${asset.ownerId}/2022/June/${asset.originalFileName}`;
const newPath = `/data/library/${asset.ownerId}/2022/2022-06-19/${asset.originalFileName}`;
@@ -304,7 +331,7 @@ describe(StorageTemplateService.name, () => {
oldPath: asset.originalPath,
newPath: previousFailedNewPath,
});
mocks.assetJob.getForStorageTemplateJob.mockResolvedValue(asset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValue(getForStorageTemplate(asset));
mocks.move.update.mockResolvedValue({
id: '123',
entityId: asset.id,
@@ -325,45 +352,53 @@ describe(StorageTemplateService.name, () => {
});
it('should fail move if copying and hash of asset and the new file do not match', async () => {
mocks.user.get.mockResolvedValue(userStub.user1);
const newPath = `/data/library/${userStub.user1.id}/2022/2022-06-19/${testAsset.originalFileName}`;
const user = UserFactory.create();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.owner(user)
.exif()
.build();
mocks.user.get.mockResolvedValue(user);
const newPath = `/data/library/${user.id}/2022/2022-06-19/${asset.originalFileName}`;
mocks.storage.rename.mockRejectedValue({ code: 'EXDEV' });
mocks.storage.stat.mockResolvedValue({ size: 5000 } as Stats);
mocks.crypto.hashFile.mockResolvedValue(Buffer.from('different-hash', 'utf8'));
mocks.assetJob.getForStorageTemplateJob.mockResolvedValue(testAsset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValue(getForStorageTemplate(asset));
mocks.move.create.mockResolvedValue({
id: '123',
entityId: testAsset.id,
entityId: asset.id,
pathType: AssetPathType.Original,
oldPath: testAsset.originalPath,
oldPath: asset.originalPath,
newPath,
});
await expect(sut.handleMigrationSingle({ id: testAsset.id })).resolves.toBe(JobStatus.Success);
await expect(sut.handleMigrationSingle({ id: asset.id })).resolves.toBe(JobStatus.Success);
expect(mocks.assetJob.getForStorageTemplateJob).toHaveBeenCalledWith(testAsset.id);
expect(mocks.assetJob.getForStorageTemplateJob).toHaveBeenCalledWith(asset.id);
expect(mocks.storage.checkFileExists).toHaveBeenCalledTimes(1);
expect(mocks.storage.stat).toHaveBeenCalledWith(newPath);
expect(mocks.move.create).toHaveBeenCalledWith({
entityId: testAsset.id,
entityId: asset.id,
pathType: AssetPathType.Original,
oldPath: testAsset.originalPath,
oldPath: asset.originalPath,
newPath,
});
expect(mocks.storage.rename).toHaveBeenCalledWith(testAsset.originalPath, newPath);
expect(mocks.storage.copyFile).toHaveBeenCalledWith(testAsset.originalPath, newPath);
expect(mocks.storage.rename).toHaveBeenCalledWith(asset.originalPath, newPath);
expect(mocks.storage.copyFile).toHaveBeenCalledWith(asset.originalPath, newPath);
expect(mocks.storage.unlink).toHaveBeenCalledWith(newPath);
expect(mocks.storage.unlink).toHaveBeenCalledTimes(1);
expect(mocks.asset.update).not.toHaveBeenCalled();
});
const testAsset = assetStub.storageAsset();
const testAsset = AssetFactory.from().exif({ fileSizeInByte: 12_345 }).build();
it.each`
failedPathChecksum | failedPathSize | reason
${testAsset.checksum} | ${500} | ${'file size'}
${Buffer.from('bad checksum', 'utf8')} | ${testAsset.fileSizeInByte} | ${'checksum'}
failedPathChecksum | failedPathSize | reason
${testAsset.checksum} | ${500} | ${'file size'}
${Buffer.from('bad checksum', 'utf8')} | ${testAsset.exifInfo.fileSizeInByte} | ${'checksum'}
`(
'should fail to migrate previously failed move from previous new path when old path no longer exists if $reason validation fails',
async ({ failedPathChecksum, failedPathSize }) => {
@@ -381,7 +416,7 @@ describe(StorageTemplateService.name, () => {
oldPath: testAsset.originalPath,
newPath: previousFailedNewPath,
});
mocks.assetJob.getForStorageTemplateJob.mockResolvedValue(testAsset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValue(getForStorageTemplate(testAsset));
mocks.move.update.mockResolvedValue({
id: '123',
entityId: testAsset.id,
@@ -414,12 +449,17 @@ describe(StorageTemplateService.name, () => {
});
it('should handle an asset with a duplicate destination', async () => {
const asset = assetStub.storageAsset();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.exif()
.build();
const oldPath = asset.originalPath;
const newPath = `/data/library/user-id/2022/2022-06-19/${asset.originalFileName}`;
const newPath = `/data/library/${asset.ownerId}/2022/2022-06-19/${asset.originalFileName}`;
const newPath2 = newPath.replace('.jpg', '+1.jpg');
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([userStub.user1]);
mocks.move.create.mockResolvedValue({
id: '123',
@@ -441,9 +481,13 @@ describe(StorageTemplateService.name, () => {
});
it('should skip when an asset already matches the template', async () => {
const asset = assetStub.storageAsset({ originalPath: '/data/library/user-id/2023/2023-02-23/asset-id.jpg' });
const asset = AssetFactory.from({
originalPath: '/data/library/user-id/2023/2023-02-23/asset-id.jpg',
})
.exif()
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([userStub.user1]);
await sut.handleMigration();
@@ -456,9 +500,13 @@ describe(StorageTemplateService.name, () => {
});
it('should skip when an asset is probably a duplicate', async () => {
const asset = assetStub.storageAsset({ originalPath: '/data/library/user-id/2023/2023-02-23/asset-id+1.jpg' });
const asset = AssetFactory.from({
originalPath: '/data/library/user-id/2023/2023-02-23/asset-id+1.jpg',
})
.exif()
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([userStub.user1]);
await sut.handleMigration();
@@ -471,16 +519,21 @@ describe(StorageTemplateService.name, () => {
});
it('should move an asset', async () => {
const asset = assetStub.storageAsset();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.exif()
.build();
const oldPath = asset.originalPath;
const newPath = `/data/library/user-id/2022/2022-06-19/${asset.originalFileName}`;
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
const newPath = `/data/library/${asset.ownerId}/2022/2022-06-19/${asset.originalFileName}`;
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([userStub.user1]);
mocks.move.create.mockResolvedValue({
id: '123',
entityId: assetStub.image.id,
entityId: asset.id,
pathType: AssetPathType.Original,
oldPath: assetStub.image.originalPath,
oldPath: asset.originalPath,
newPath,
});
@@ -492,9 +545,15 @@ describe(StorageTemplateService.name, () => {
});
it('should use the user storage label', async () => {
const user = factory.userAdmin({ storageLabel: 'label-1' });
const asset = assetStub.storageAsset({ ownerId: user.id });
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
const user = UserFactory.create({ storageLabel: 'label-1' });
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.owner(user)
.exif()
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([user]);
mocks.move.create.mockResolvedValue({
id: '123',
@@ -508,7 +567,7 @@ describe(StorageTemplateService.name, () => {
expect(mocks.assetJob.streamForStorageTemplateJob).toHaveBeenCalled();
expect(mocks.storage.rename).toHaveBeenCalledWith(
'/original/path.jpg',
asset.originalPath,
expect.stringContaining(`/data/library/${user.storageLabel}/2022/2022-06-19/${asset.originalFileName}`),
);
expect(mocks.asset.update).toHaveBeenCalledWith({
@@ -520,10 +579,16 @@ describe(StorageTemplateService.name, () => {
});
it('should copy the file if rename fails due to EXDEV (rename across filesystems)', async () => {
const asset = assetStub.storageAsset({ originalPath: '/path/to/original.jpg', fileSizeInByte: 5000 });
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
originalPath: '/path/to/original.jpg',
})
.exif({ fileSizeInByte: 5000 })
.build();
const oldPath = asset.originalPath;
const newPath = `/data/library/user-id/2022/2022-06-19/${asset.originalFileName}`;
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
const newPath = `/data/library/${asset.ownerId}/2022/2022-06-19/${asset.originalFileName}`;
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.storage.rename.mockRejectedValue({ code: 'EXDEV' });
mocks.user.getList.mockResolvedValue([userStub.user1]);
mocks.move.create.mockResolvedValue({
@@ -561,10 +626,17 @@ describe(StorageTemplateService.name, () => {
});
it('should not update the database if the move fails due to incorrect newPath filesize', async () => {
const asset = assetStub.storageAsset();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
const user = UserFactory.create();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.owner(user)
.exif()
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.storage.rename.mockRejectedValue({ code: 'EXDEV' });
mocks.user.getList.mockResolvedValue([userStub.user1]);
mocks.user.getList.mockResolvedValue([user]);
mocks.move.create.mockResolvedValue({
id: '123',
entityId: asset.id,
@@ -580,22 +652,29 @@ describe(StorageTemplateService.name, () => {
expect(mocks.assetJob.streamForStorageTemplateJob).toHaveBeenCalled();
expect(mocks.storage.rename).toHaveBeenCalledWith(
'/original/path.jpg',
expect.stringContaining(`/data/library/user-id/2022/2022-06-19/${asset.originalFileName}`),
asset.originalPath,
expect.stringContaining(`/data/library/${user.id}/2022/2022-06-19/${asset.originalFileName}`),
);
expect(mocks.storage.copyFile).toHaveBeenCalledWith(
'/original/path.jpg',
expect.stringContaining(`/data/library/user-id/2022/2022-06-19/${asset.originalFileName}`),
asset.originalPath,
expect.stringContaining(`/data/library/${user.id}/2022/2022-06-19/${asset.originalFileName}`),
);
expect(mocks.storage.stat).toHaveBeenCalledWith(
expect.stringContaining(`/data/library/user-id/2022/2022-06-19/${asset.originalFileName}`),
expect.stringContaining(`/data/library/${user.id}/2022/2022-06-19/${asset.originalFileName}`),
);
expect(mocks.asset.update).not.toHaveBeenCalled();
});
it('should not update the database if the move fails', async () => {
const asset = assetStub.storageAsset();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
const user = UserFactory.create();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.owner(user)
.exif()
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.storage.rename.mockRejectedValue(new Error('Read only system'));
mocks.storage.copyFile.mockRejectedValue(new Error('Read only system'));
mocks.move.create.mockResolvedValue({
@@ -605,25 +684,37 @@ describe(StorageTemplateService.name, () => {
oldPath: asset.originalPath,
newPath: '',
});
mocks.user.getList.mockResolvedValue([userStub.user1]);
mocks.user.getList.mockResolvedValue([user]);
await sut.handleMigration();
expect(mocks.assetJob.streamForStorageTemplateJob).toHaveBeenCalled();
expect(mocks.storage.rename).toHaveBeenCalledWith(
'/original/path.jpg',
expect.stringContaining(`/data/library/user-id/2022/2022-06-19/${asset.originalFileName}`),
asset.originalPath,
expect.stringContaining(`/data/library/${user.id}/2022/2022-06-19/${asset.originalFileName}`),
);
expect(mocks.asset.update).not.toHaveBeenCalled();
});
it('should migrate live photo motion video alongside the still image', async () => {
const newMotionPicturePath = `/data/library/${motionAsset.ownerId}/2022/2022-06-19/${motionAsset.originalFileName}`;
const motionAsset = AssetFactory.from({
type: AssetType.Video,
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.exif()
.build();
const stillAsset = AssetFactory.from({
livePhotoVideoId: motionAsset.id,
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
})
.exif()
.build();
const newMotionPicturePath = `/data/library/${motionAsset.ownerId}/2022/2022-06-19/${stillAsset.originalFileName.slice(0, -4)}.mp4`;
const newStillPicturePath = `/data/library/${stillAsset.ownerId}/2022/2022-06-19/${stillAsset.originalFileName}`;
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([stillAsset]));
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(stillAsset)]));
mocks.user.getList.mockResolvedValue([userStub.user1]);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(motionAsset);
mocks.assetJob.getForStorageTemplateJob.mockResolvedValueOnce(getForStorageTemplate(motionAsset));
mocks.move.create.mockResolvedValueOnce({
id: '123',
@@ -653,13 +744,17 @@ describe(StorageTemplateService.name, () => {
describe('file rename correctness', () => {
it('should not create double extensions when filename has lower extension', async () => {
const user = factory.userAdmin({ storageLabel: 'label-1' });
const asset = assetStub.storageAsset({
ownerId: user.id,
const user = UserFactory.create({ storageLabel: 'label-1' });
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
originalPath: `/data/library/${user.id}/2022/2022-06-19/IMG_7065.heic`,
originalFileName: 'IMG_7065.HEIC',
});
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
})
.owner(user)
.exif()
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([user]);
mocks.move.create.mockResolvedValue({
id: '123',
@@ -679,13 +774,17 @@ describe(StorageTemplateService.name, () => {
});
it('should not create double extensions when filename has uppercase extension', async () => {
const user = factory.userAdmin();
const asset = assetStub.storageAsset({
ownerId: user.id,
const user = UserFactory.create();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
originalPath: `/data/library/${user.id}/2022/2022-06-19/IMG_7065.HEIC`,
originalFileName: 'IMG_7065.HEIC',
});
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
})
.owner(user)
.exif({ fileSizeInByte: 12_345 })
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([user]);
mocks.move.create.mockResolvedValue({
id: '123',
@@ -705,13 +804,17 @@ describe(StorageTemplateService.name, () => {
});
it('should normalize the filename to lowercase (JPEG > jpg)', async () => {
const user = factory.userAdmin();
const asset = assetStub.storageAsset({
ownerId: user.id,
const user = UserFactory.create();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
originalPath: `/data/library/${user.id}/2022/2022-06-19/IMG_7065.JPEG`,
originalFileName: 'IMG_7065.JPEG',
});
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
})
.owner(user)
.exif()
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([user]);
mocks.move.create.mockResolvedValue({
id: '123',
@@ -731,13 +834,17 @@ describe(StorageTemplateService.name, () => {
});
it('should normalize the filename to lowercase (JPG > jpg)', async () => {
const user = factory.userAdmin();
const asset = assetStub.storageAsset({
ownerId: user.id,
const user = UserFactory.create();
const asset = AssetFactory.from({
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
originalPath: '/data/library/user-id/2022/2022-06-19/IMG_7065.JPG',
originalFileName: 'IMG_7065.JPG',
});
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([asset]));
})
.owner(user)
.exif()
.build();
mocks.assetJob.streamForStorageTemplateJob.mockReturnValue(makeStream([getForStorageTemplate(asset)]));
mocks.user.getList.mockResolvedValue([user]);
mocks.move.create.mockResolvedValue({
id: '123',
+2 -3
View File
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
import { join } from 'node:path';
import { ErrorMessages } from 'src/constants';
import { StorageCore } from 'src/cores/storage.core';
import { OnEvent, OnJob } from 'src/decorators';
import {
@@ -114,9 +115,7 @@ export class StorageService extends BaseService {
this.logger.log(`Media location changed (from=${previous}, to=${current})`);
if (!path.startsWith(previous)) {
throw new Error(
'Detected an inconsistent media location. For more information, see https://docs.immich.app/errors#inconsistent-media-location',
);
throw new Error(ErrorMessages.InconsistentMediaLocation);
}
this.logger.warn(
+16 -11
View File
@@ -1,6 +1,6 @@
import { mapAsset } from 'src/dtos/asset-response.dto';
import { SyncService } from 'src/services/sync.service';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { factory } from 'test/small.factory';
import { newTestService, ServiceMocks } from 'test/utils';
@@ -22,10 +22,14 @@ describe(SyncService.name, () => {
describe('getAllAssetsForUserFullSync', () => {
it('should return a list of all assets owned by the user', async () => {
mocks.asset.getAllForUserFullSync.mockResolvedValue([assetStub.external, assetStub.hasEncodedVideo]);
const [asset1, asset2] = [
AssetFactory.from({ libraryId: 'library-id', isExternal: true }).owner(authStub.user1.user).build(),
AssetFactory.from().owner(authStub.user1.user).build(),
];
mocks.asset.getAllForUserFullSync.mockResolvedValue([asset1, asset2]);
await expect(sut.getFullSync(authStub.user1, { limit: 2, updatedUntil: untilDate })).resolves.toEqual([
mapAsset(assetStub.external, mapAssetOpts),
mapAsset(assetStub.hasEncodedVideo, mapAssetOpts),
mapAsset(asset1, mapAssetOpts),
mapAsset(asset2, mapAssetOpts),
]);
expect(mocks.asset.getAllForUserFullSync).toHaveBeenCalledWith({
ownerId: authStub.user1.user.id,
@@ -60,10 +64,9 @@ describe(SyncService.name, () => {
});
it('should return a response requiring a full sync when there are too many changes', async () => {
const asset = AssetFactory.create();
mocks.partner.getAll.mockResolvedValue([]);
mocks.asset.getChangedDeltaSync.mockResolvedValue(
Array.from<typeof assetStub.image>({ length: 10_000 }).fill(assetStub.image),
);
mocks.asset.getChangedDeltaSync.mockResolvedValue(Array.from<typeof asset>({ length: 10_000 }).fill(asset));
await expect(
sut.getDeltaSync(authStub.user1, { updatedAfter: new Date(), userIds: [authStub.user1.user.id] }),
).resolves.toEqual({ needsFullSync: true, upserted: [], deleted: [] });
@@ -72,15 +75,17 @@ describe(SyncService.name, () => {
});
it('should return a response with changes and deletions', async () => {
const asset = AssetFactory.create({ ownerId: authStub.user1.user.id });
const deletedAsset = AssetFactory.create({ libraryId: 'library-id', isExternal: true });
mocks.partner.getAll.mockResolvedValue([]);
mocks.asset.getChangedDeltaSync.mockResolvedValue([assetStub.image1]);
mocks.audit.getAfter.mockResolvedValue([assetStub.external.id]);
mocks.asset.getChangedDeltaSync.mockResolvedValue([asset]);
mocks.audit.getAfter.mockResolvedValue([deletedAsset.id]);
await expect(
sut.getDeltaSync(authStub.user1, { updatedAfter: new Date(), userIds: [authStub.user1.user.id] }),
).resolves.toEqual({
needsFullSync: false,
upserted: [mapAsset(assetStub.image1, mapAssetOpts)],
deleted: [assetStub.external.id],
upserted: [mapAsset(asset, mapAssetOpts)],
deleted: [deletedAsset.id],
});
expect(mocks.asset.getChangedDeltaSync).toHaveBeenCalledTimes(1);
expect(mocks.audit.getAfter).toHaveBeenCalledTimes(1);
+3 -3
View File
@@ -1,6 +1,6 @@
import { mapAsset } from 'src/dtos/asset-response.dto';
import { ViewService } from 'src/services/view.service';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { newTestService, ServiceMocks } from 'test/utils';
@@ -32,8 +32,8 @@ describe(ViewService.name, () => {
it('should return assets by original path', async () => {
const path = '/asset';
const asset1 = { ...assetStub.image, originalPath: '/asset/path1' };
const asset2 = { ...assetStub.image, originalPath: '/asset/path2' };
const asset1 = AssetFactory.create({ originalPath: '/asset/path1' });
const asset2 = AssetFactory.create({ originalPath: '/asset/path2' });
const mockAssets = [asset1, asset2];
@@ -15,7 +15,7 @@ const testColumn: DatabaseColumn = {
describe('compareColumns', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareColumns.onExtra(testColumn)).toEqual([
expect(compareColumns().onExtra(testColumn)).toEqual([
{
tableName: 'table1',
columnName: 'test',
@@ -28,7 +28,7 @@ describe('compareColumns', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareColumns.onMissing(testColumn)).toEqual([
expect(compareColumns().onMissing(testColumn)).toEqual([
{
type: 'ColumnAdd',
column: testColumn,
@@ -40,14 +40,14 @@ describe('compareColumns', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareColumns.onCompare(testColumn, testColumn)).toEqual([]);
expect(compareColumns().onCompare(testColumn, testColumn)).toEqual([]);
});
it('should detect a change in type', () => {
const source: DatabaseColumn = { ...testColumn };
const target: DatabaseColumn = { ...testColumn, type: 'text' };
const reason = 'column type is different (character varying vs text)';
expect(compareColumns.onCompare(source, target)).toEqual([
expect(compareColumns().onCompare(source, target)).toEqual([
{
columnName: 'test',
tableName: 'table1',
@@ -66,7 +66,7 @@ describe('compareColumns', () => {
const source: DatabaseColumn = { ...testColumn, nullable: true };
const target: DatabaseColumn = { ...testColumn, nullable: true, default: "''" };
const reason = `default is different (null vs '')`;
expect(compareColumns.onCompare(source, target)).toEqual([
expect(compareColumns().onCompare(source, target)).toEqual([
{
columnName: 'test',
tableName: 'table1',
@@ -83,7 +83,7 @@ describe('compareColumns', () => {
const source: DatabaseColumn = { ...testColumn, comment: 'new comment' };
const target: DatabaseColumn = { ...testColumn, comment: 'old comment' };
const reason = 'comment is different (new comment vs old comment)';
expect(compareColumns.onCompare(source, target)).toEqual([
expect(compareColumns().onCompare(source, target)).toEqual([
{
columnName: 'test',
tableName: 'table1',
@@ -1,98 +1,99 @@
import { asRenameKey, getColumnType, isDefaultEqual } from 'src/sql-tools/helpers';
import { Comparer, DatabaseColumn, Reason, SchemaDiff } from 'src/sql-tools/types';
export const compareColumns = {
getRenameKey: (column) => {
return asRenameKey([
column.tableName,
column.type,
column.nullable,
column.default,
column.storage,
column.primary,
column.isArray,
column.length,
column.identity,
column.enumName,
column.numericPrecision,
column.numericScale,
]);
},
onRename: (source, target) => [
{
type: 'ColumnRename',
tableName: source.tableName,
oldName: target.name,
newName: source.name,
reason: Reason.Rename,
export const compareColumns = () =>
({
getRenameKey: (column) => {
return asRenameKey([
column.tableName,
column.type,
column.nullable,
column.default,
column.storage,
column.primary,
column.isArray,
column.length,
column.identity,
column.enumName,
column.numericPrecision,
column.numericScale,
]);
},
],
onMissing: (source) => [
{
type: 'ColumnAdd',
column: source,
reason: Reason.MissingInTarget,
onRename: (source, target) => [
{
type: 'ColumnRename',
tableName: source.tableName,
oldName: target.name,
newName: source.name,
reason: Reason.Rename,
},
],
onMissing: (source) => [
{
type: 'ColumnAdd',
column: source,
reason: Reason.MissingInTarget,
},
],
onExtra: (target) => [
{
type: 'ColumnDrop',
tableName: target.tableName,
columnName: target.name,
reason: Reason.MissingInSource,
},
],
onCompare: (source, target) => {
const sourceType = getColumnType(source);
const targetType = getColumnType(target);
const isTypeChanged = sourceType !== targetType;
if (isTypeChanged) {
// TODO: convert between types via UPDATE when possible
return dropAndRecreateColumn(source, target, `column type is different (${sourceType} vs ${targetType})`);
}
const items: SchemaDiff[] = [];
if (source.nullable !== target.nullable) {
items.push({
type: 'ColumnAlter',
tableName: source.tableName,
columnName: source.name,
changes: {
nullable: source.nullable,
},
reason: `nullable is different (${source.nullable} vs ${target.nullable})`,
});
}
if (!isDefaultEqual(source, target)) {
items.push({
type: 'ColumnAlter',
tableName: source.tableName,
columnName: source.name,
changes: {
default: String(source.default ?? 'NULL'),
},
reason: `default is different (${source.default ?? 'null'} vs ${target.default})`,
});
}
if (source.comment !== target.comment) {
items.push({
type: 'ColumnAlter',
tableName: source.tableName,
columnName: source.name,
changes: {
comment: String(source.comment),
},
reason: `comment is different (${source.comment} vs ${target.comment})`,
});
}
return items;
},
],
onExtra: (target) => [
{
type: 'ColumnDrop',
tableName: target.tableName,
columnName: target.name,
reason: Reason.MissingInSource,
},
],
onCompare: (source, target) => {
const sourceType = getColumnType(source);
const targetType = getColumnType(target);
const isTypeChanged = sourceType !== targetType;
if (isTypeChanged) {
// TODO: convert between types via UPDATE when possible
return dropAndRecreateColumn(source, target, `column type is different (${sourceType} vs ${targetType})`);
}
const items: SchemaDiff[] = [];
if (source.nullable !== target.nullable) {
items.push({
type: 'ColumnAlter',
tableName: source.tableName,
columnName: source.name,
changes: {
nullable: source.nullable,
},
reason: `nullable is different (${source.nullable} vs ${target.nullable})`,
});
}
if (!isDefaultEqual(source, target)) {
items.push({
type: 'ColumnAlter',
tableName: source.tableName,
columnName: source.name,
changes: {
default: String(source.default ?? 'NULL'),
},
reason: `default is different (${source.default ?? 'null'} vs ${target.default})`,
});
}
if (source.comment !== target.comment) {
items.push({
type: 'ColumnAlter',
tableName: source.tableName,
columnName: source.name,
changes: {
comment: String(source.comment),
},
reason: `comment is different (${source.comment} vs ${target.comment})`,
});
}
return items;
},
} satisfies Comparer<DatabaseColumn>;
}) satisfies Comparer<DatabaseColumn>;
const dropAndRecreateColumn = (source: DatabaseColumn, target: DatabaseColumn, reason: string): SchemaDiff[] => {
return [
@@ -13,7 +13,7 @@ const testConstraint: DatabaseConstraint = {
describe('compareConstraints', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareConstraints.onExtra(testConstraint)).toEqual([
expect(compareConstraints().onExtra(testConstraint)).toEqual([
{
type: 'ConstraintDrop',
constraintName: 'test',
@@ -26,7 +26,7 @@ describe('compareConstraints', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareConstraints.onMissing(testConstraint)).toEqual([
expect(compareConstraints().onMissing(testConstraint)).toEqual([
{
type: 'ConstraintAdd',
constraint: testConstraint,
@@ -38,14 +38,14 @@ describe('compareConstraints', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareConstraints.onCompare(testConstraint, testConstraint)).toEqual([]);
expect(compareConstraints().onCompare(testConstraint, testConstraint)).toEqual([]);
});
it('should detect a change in type', () => {
const source: DatabaseConstraint = { ...testConstraint };
const target: DatabaseConstraint = { ...testConstraint, columnNames: ['column1', 'column2'] };
const reason = 'Primary key columns are different: (column1 vs column1,column2)';
expect(compareConstraints.onCompare(source, target)).toEqual([
expect(compareConstraints().onCompare(source, target)).toEqual([
{
constraintName: 'test',
tableName: 'table1',
@@ -12,7 +12,7 @@ import {
SchemaDiff,
} from 'src/sql-tools/types';
export const compareConstraints: Comparer<DatabaseConstraint> = {
export const compareConstraints = (): Comparer<DatabaseConstraint> => ({
getRenameKey: (constraint) => {
switch (constraint.type) {
case ConstraintType.PRIMARY_KEY:
@@ -83,7 +83,7 @@ export const compareConstraints: Comparer<DatabaseConstraint> = {
}
}
},
};
});
const comparePrimaryKeyConstraint: CompareFunction<DatabasePrimaryKeyConstraint> = (source, target) => {
if (!haveEqualColumns(source.columnNames, target.columnNames)) {
@@ -7,7 +7,7 @@ const testEnum: DatabaseEnum = { name: 'test', values: ['foo', 'bar'], synchroni
describe('compareEnums', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareEnums.onExtra(testEnum)).toEqual([
expect(compareEnums().onExtra(testEnum)).toEqual([
{
enumName: 'test',
type: 'EnumDrop',
@@ -19,7 +19,7 @@ describe('compareEnums', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareEnums.onMissing(testEnum)).toEqual([
expect(compareEnums().onMissing(testEnum)).toEqual([
{
type: 'EnumCreate',
enum: testEnum,
@@ -31,13 +31,13 @@ describe('compareEnums', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareEnums.onCompare(testEnum, testEnum)).toEqual([]);
expect(compareEnums().onCompare(testEnum, testEnum)).toEqual([]);
});
it('should drop and recreate when values list is different', () => {
const source = { name: 'test', values: ['foo', 'bar'], synchronize: true };
const target = { name: 'test', values: ['foo', 'bar', 'world'], synchronize: true };
expect(compareEnums.onCompare(source, target)).toEqual([
expect(compareEnums().onCompare(source, target)).toEqual([
{
enumName: 'test',
type: 'EnumDrop',
@@ -1,6 +1,6 @@
import { Comparer, DatabaseEnum, Reason } from 'src/sql-tools/types';
export const compareEnums: Comparer<DatabaseEnum> = {
export const compareEnums = (): Comparer<DatabaseEnum> => ({
onMissing: (source) => [
{
type: 'EnumCreate',
@@ -35,4 +35,4 @@ export const compareEnums: Comparer<DatabaseEnum> = {
return [];
},
};
});
@@ -7,7 +7,7 @@ const testExtension = { name: 'test', synchronize: true };
describe('compareExtensions', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareExtensions.onExtra(testExtension)).toEqual([
expect(compareExtensions().onExtra(testExtension)).toEqual([
{
extensionName: 'test',
type: 'ExtensionDrop',
@@ -19,7 +19,7 @@ describe('compareExtensions', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareExtensions.onMissing(testExtension)).toEqual([
expect(compareExtensions().onMissing(testExtension)).toEqual([
{
type: 'ExtensionCreate',
extension: testExtension,
@@ -31,7 +31,7 @@ describe('compareExtensions', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareExtensions.onCompare(testExtension, testExtension)).toEqual([]);
expect(compareExtensions().onCompare(testExtension, testExtension)).toEqual([]);
});
});
});
@@ -1,6 +1,6 @@
import { Comparer, DatabaseExtension, Reason } from 'src/sql-tools/types';
export const compareExtensions: Comparer<DatabaseExtension> = {
export const compareExtensions = (): Comparer<DatabaseExtension> => ({
onMissing: (source) => [
{
type: 'ExtensionCreate',
@@ -19,4 +19,4 @@ export const compareExtensions: Comparer<DatabaseExtension> = {
// if the name matches they are the same
return [];
},
};
});
@@ -11,7 +11,7 @@ const testFunction: DatabaseFunction = {
describe('compareFunctions', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareFunctions.onExtra(testFunction)).toEqual([
expect(compareFunctions().onExtra(testFunction)).toEqual([
{
functionName: 'test',
type: 'FunctionDrop',
@@ -23,7 +23,7 @@ describe('compareFunctions', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareFunctions.onMissing(testFunction)).toEqual([
expect(compareFunctions().onMissing(testFunction)).toEqual([
{
type: 'FunctionCreate',
function: testFunction,
@@ -35,13 +35,13 @@ describe('compareFunctions', () => {
describe('onCompare', () => {
it('should ignore functions with the same hash', () => {
expect(compareFunctions.onCompare(testFunction, testFunction)).toEqual([]);
expect(compareFunctions().onCompare(testFunction, testFunction)).toEqual([]);
});
it('should report differences if functions have different hashes', () => {
const source: DatabaseFunction = { ...testFunction, expression: 'SELECT 1' };
const target: DatabaseFunction = { ...testFunction, expression: 'SELECT 2' };
expect(compareFunctions.onCompare(source, target)).toEqual([
expect(compareFunctions().onCompare(source, target)).toEqual([
{
type: 'FunctionCreate',
reason: 'function expression has changed (SELECT 1 vs SELECT 2)',
@@ -1,6 +1,6 @@
import { Comparer, DatabaseFunction, Reason } from 'src/sql-tools/types';
export const compareFunctions: Comparer<DatabaseFunction> = {
export const compareFunctions = (): Comparer<DatabaseFunction> => ({
onMissing: (source) => [
{
type: 'FunctionCreate',
@@ -29,4 +29,4 @@ export const compareFunctions: Comparer<DatabaseFunction> = {
return [];
},
};
});
@@ -13,7 +13,7 @@ const testIndex: DatabaseIndex = {
describe('compareIndexes', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareIndexes.onExtra(testIndex)).toEqual([
expect(compareIndexes().onExtra(testIndex)).toEqual([
{
type: 'IndexDrop',
indexName: 'test',
@@ -25,7 +25,7 @@ describe('compareIndexes', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareIndexes.onMissing(testIndex)).toEqual([
expect(compareIndexes().onMissing(testIndex)).toEqual([
{
type: 'IndexCreate',
index: testIndex,
@@ -37,7 +37,7 @@ describe('compareIndexes', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareIndexes.onCompare(testIndex, testIndex)).toEqual([]);
expect(compareIndexes().onCompare(testIndex, testIndex)).toEqual([]);
});
it('should drop and recreate when column list is different', () => {
@@ -55,7 +55,7 @@ describe('compareIndexes', () => {
unique: true,
synchronize: true,
};
expect(compareIndexes.onCompare(source, target)).toEqual([
expect(compareIndexes().onCompare(source, target)).toEqual([
{
indexName: 'test',
type: 'IndexDrop',
@@ -1,7 +1,7 @@
import { asRenameKey, haveEqualColumns } from 'src/sql-tools/helpers';
import { Comparer, DatabaseIndex, Reason } from 'src/sql-tools/types';
export const compareIndexes: Comparer<DatabaseIndex> = {
export const compareIndexes = (): Comparer<DatabaseIndex> => ({
getRenameKey: (index) => {
if (index.override) {
return index.override.value.sql.replace(index.name, 'INDEX_NAME');
@@ -59,4 +59,4 @@ export const compareIndexes: Comparer<DatabaseIndex> = {
return [];
},
};
});
@@ -11,7 +11,7 @@ const testOverride: DatabaseOverride = {
describe('compareOverrides', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareOverrides.onExtra(testOverride)).toEqual([
expect(compareOverrides().onExtra(testOverride)).toEqual([
{
type: 'OverrideDrop',
overrideName: 'test',
@@ -23,7 +23,7 @@ describe('compareOverrides', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareOverrides.onMissing(testOverride)).toEqual([
expect(compareOverrides().onMissing(testOverride)).toEqual([
{
type: 'OverrideCreate',
override: testOverride,
@@ -35,7 +35,7 @@ describe('compareOverrides', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareOverrides.onCompare(testOverride, testOverride)).toEqual([]);
expect(compareOverrides().onCompare(testOverride, testOverride)).toEqual([]);
});
it('should drop and recreate when the value changes', () => {
@@ -57,7 +57,7 @@ describe('compareOverrides', () => {
},
synchronize: true,
};
expect(compareOverrides.onCompare(source, target)).toEqual([
expect(compareOverrides().onCompare(source, target)).toEqual([
{
override: source,
type: 'OverrideUpdate',
@@ -1,6 +1,6 @@
import { Comparer, DatabaseOverride, Reason } from 'src/sql-tools/types';
export const compareOverrides: Comparer<DatabaseOverride> = {
export const compareOverrides = (): Comparer<DatabaseOverride> => ({
onMissing: (source) => [
{
type: 'OverrideCreate',
@@ -26,4 +26,4 @@ export const compareOverrides: Comparer<DatabaseOverride> = {
return [];
},
};
});
@@ -13,7 +13,7 @@ const testParameter: DatabaseParameter = {
describe('compareParameters', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareParameters.onExtra(testParameter)).toEqual([
expect(compareParameters().onExtra(testParameter)).toEqual([
{
type: 'ParameterReset',
databaseName: 'immich',
@@ -26,7 +26,7 @@ describe('compareParameters', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareParameters.onMissing(testParameter)).toEqual([
expect(compareParameters().onMissing(testParameter)).toEqual([
{
type: 'ParameterSet',
parameter: testParameter,
@@ -38,7 +38,7 @@ describe('compareParameters', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareParameters.onCompare(testParameter, testParameter)).toEqual([]);
expect(compareParameters().onCompare(testParameter, testParameter)).toEqual([]);
});
});
});
@@ -1,6 +1,6 @@
import { Comparer, DatabaseParameter, Reason } from 'src/sql-tools/types';
export const compareParameters: Comparer<DatabaseParameter> = {
export const compareParameters = (): Comparer<DatabaseParameter> => ({
onMissing: (source) => [
{
type: 'ParameterSet',
@@ -20,4 +20,4 @@ export const compareParameters: Comparer<DatabaseParameter> = {
// TODO
return [];
},
};
});
@@ -14,7 +14,7 @@ const testTable: DatabaseTable = {
describe('compareParameters', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareTables.onExtra(testTable)).toEqual([
expect(compareTables({}).onExtra(testTable)).toEqual([
{
type: 'TableDrop',
tableName: 'test',
@@ -26,7 +26,7 @@ describe('compareParameters', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareTables.onMissing(testTable)).toEqual([
expect(compareTables({}).onMissing(testTable)).toEqual([
{
type: 'TableCreate',
table: testTable,
@@ -38,7 +38,7 @@ describe('compareParameters', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareTables.onCompare(testTable, testTable)).toEqual([]);
expect(compareTables({}).onCompare(testTable, testTable)).toEqual([]);
});
});
});
@@ -3,9 +3,9 @@ import { compareConstraints } from 'src/sql-tools/comparers/constraint.comparer'
import { compareIndexes } from 'src/sql-tools/comparers/index.comparer';
import { compareTriggers } from 'src/sql-tools/comparers/trigger.comparer';
import { compare } from 'src/sql-tools/helpers';
import { Comparer, DatabaseTable, Reason, SchemaDiff } from 'src/sql-tools/types';
import { Comparer, DatabaseTable, Reason, SchemaDiffOptions } from 'src/sql-tools/types';
export const compareTables: Comparer<DatabaseTable> = {
export const compareTables = (options: SchemaDiffOptions): Comparer<DatabaseTable> => ({
onMissing: (source) => [
{
type: 'TableCreate',
@@ -20,14 +20,12 @@ export const compareTables: Comparer<DatabaseTable> = {
reason: Reason.MissingInSource,
},
],
onCompare: (source, target) => compareTable(source, target),
};
const compareTable = (source: DatabaseTable, target: DatabaseTable): SchemaDiff[] => {
return [
...compare(source.columns, target.columns, {}, compareColumns),
...compare(source.indexes, target.indexes, {}, compareIndexes),
...compare(source.constraints, target.constraints, {}, compareConstraints),
...compare(source.triggers, target.triggers, {}, compareTriggers),
];
};
onCompare: (source, target) => {
return [
...compare(source.columns, target.columns, options.columns, compareColumns()),
...compare(source.indexes, target.indexes, options.indexes, compareIndexes()),
...compare(source.constraints, target.constraints, options.constraints, compareConstraints()),
...compare(source.triggers, target.triggers, options.triggers, compareTriggers()),
];
},
});
@@ -15,7 +15,7 @@ const testTrigger: DatabaseTrigger = {
describe('compareTriggers', () => {
describe('onExtra', () => {
it('should work', () => {
expect(compareTriggers.onExtra(testTrigger)).toEqual([
expect(compareTriggers().onExtra(testTrigger)).toEqual([
{
type: 'TriggerDrop',
tableName: 'table1',
@@ -28,7 +28,7 @@ describe('compareTriggers', () => {
describe('onMissing', () => {
it('should work', () => {
expect(compareTriggers.onMissing(testTrigger)).toEqual([
expect(compareTriggers().onMissing(testTrigger)).toEqual([
{
type: 'TriggerCreate',
trigger: testTrigger,
@@ -40,49 +40,49 @@ describe('compareTriggers', () => {
describe('onCompare', () => {
it('should work', () => {
expect(compareTriggers.onCompare(testTrigger, testTrigger)).toEqual([]);
expect(compareTriggers().onCompare(testTrigger, testTrigger)).toEqual([]);
});
it('should detect a change in function name', () => {
const source: DatabaseTrigger = { ...testTrigger, functionName: 'my_new_name' };
const target: DatabaseTrigger = { ...testTrigger, functionName: 'my_old_name' };
const reason = `function is different (my_new_name vs my_old_name)`;
expect(compareTriggers.onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
expect(compareTriggers().onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
});
it('should detect a change in actions', () => {
const source: DatabaseTrigger = { ...testTrigger, actions: ['delete'] };
const target: DatabaseTrigger = { ...testTrigger, actions: ['delete', 'insert'] };
const reason = `action is different (delete vs delete,insert)`;
expect(compareTriggers.onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
expect(compareTriggers().onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
});
it('should detect a change in timing', () => {
const source: DatabaseTrigger = { ...testTrigger, timing: 'before' };
const target: DatabaseTrigger = { ...testTrigger, timing: 'after' };
const reason = `timing method is different (before vs after)`;
expect(compareTriggers.onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
expect(compareTriggers().onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
});
it('should detect a change in scope', () => {
const source: DatabaseTrigger = { ...testTrigger, scope: 'row' };
const target: DatabaseTrigger = { ...testTrigger, scope: 'statement' };
const reason = `scope is different (row vs statement)`;
expect(compareTriggers.onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
expect(compareTriggers().onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
});
it('should detect a change in new table reference', () => {
const source: DatabaseTrigger = { ...testTrigger, referencingNewTableAs: 'new_table' };
const target: DatabaseTrigger = { ...testTrigger, referencingNewTableAs: undefined };
const reason = `new table reference is different (new_table vs undefined)`;
expect(compareTriggers.onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
expect(compareTriggers().onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
});
it('should detect a change in old table reference', () => {
const source: DatabaseTrigger = { ...testTrigger, referencingOldTableAs: 'old_table' };
const target: DatabaseTrigger = { ...testTrigger, referencingOldTableAs: undefined };
const reason = `old table reference is different (old_table vs undefined)`;
expect(compareTriggers.onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
expect(compareTriggers().onCompare(source, target)).toEqual([{ type: 'TriggerCreate', trigger: source, reason }]);
});
});
});
@@ -1,6 +1,6 @@
import { Comparer, DatabaseTrigger, Reason } from 'src/sql-tools/types';
export const compareTriggers: Comparer<DatabaseTrigger> = {
export const compareTriggers = (): Comparer<DatabaseTrigger> => ({
onMissing: (source) => [
{
type: 'TriggerCreate',
@@ -38,4 +38,4 @@ export const compareTriggers: Comparer<DatabaseTrigger> = {
return [];
},
};
});
+97 -7
View File
@@ -20,12 +20,12 @@ import {
*/
export const schemaDiff = (source: DatabaseSchema, target: DatabaseSchema, options: SchemaDiffOptions = {}) => {
const items = [
...compare(source.parameters, target.parameters, options.parameters, compareParameters),
...compare(source.extensions, target.extensions, options.extensions, compareExtensions),
...compare(source.functions, target.functions, options.functions, compareFunctions),
...compare(source.enums, target.enums, options.enums, compareEnums),
...compare(source.tables, target.tables, options.tables, compareTables),
...compare(source.overrides, target.overrides, options.overrides, compareOverrides),
...compare(source.parameters, target.parameters, options.parameters, compareParameters()),
...compare(source.extensions, target.extensions, options.extensions, compareExtensions()),
...compare(source.functions, target.functions, options.functions, compareFunctions()),
...compare(source.enums, target.enums, options.enums, compareEnums()),
...compare(source.tables, target.tables, options.tables, compareTables(options)),
...compare(source.overrides, target.overrides, options.overrides, compareOverrides()),
];
type SchemaName = SchemaDiff['type'];
@@ -103,6 +103,7 @@ export const schemaDiff = (source: DatabaseSchema, target: DatabaseSchema, optio
return {
items: orderedItems,
asSql: (options?: SchemaDiffToSqlOptions) => schemaDiffToSql(orderedItems, options),
asHuman: () => schemaDiffToHuman(orderedItems),
};
};
@@ -113,7 +114,14 @@ export const schemaDiffToSql = (items: SchemaDiff[], options: SchemaDiffToSqlOpt
return items.flatMap((item) => asSql(item, options));
};
const asSql = (item: SchemaDiff, options: SchemaDiffToSqlOptions): string[] => {
/**
* Convert schema diff into human readable statements
*/
export const schemaDiffToHuman = (items: SchemaDiff[]): string[] => {
return items.flatMap((item) => asHuman(item));
};
export const asSql = (item: SchemaDiff, options: SchemaDiffToSqlOptions): string[] => {
const ctx = new BaseContext(options);
for (const transform of transformers) {
const result = transform(ctx, item);
@@ -127,6 +135,88 @@ const asSql = (item: SchemaDiff, options: SchemaDiffToSqlOptions): string[] => {
throw new Error(`Unhandled schema diff type: ${item.type}`);
};
export const asHuman = (item: SchemaDiff): string => {
switch (item.type) {
case 'ExtensionCreate': {
return `The extension "${item.extension.name}" is missing and needs to be created`;
}
case 'ExtensionDrop': {
return `The extension "${item.extensionName}" exists but is no longer needed`;
}
case 'FunctionCreate': {
return `The function "${item.function.name}" is missing and needs to be created`;
}
case 'FunctionDrop': {
return `The function "${item.functionName}" exists but should be removed`;
}
case 'TableCreate': {
return `The table "${item.table.name}" is missing and needs to be created`;
}
case 'TableDrop': {
return `The table "${item.tableName}" exists but should be removed`;
}
case 'ColumnAdd': {
return `The column "${item.column.tableName}"."${item.column.name}" is missing and needs to be created`;
}
case 'ColumnRename': {
return `The column "${item.tableName}"."${item.oldName}" was renamed to "${item.tableName}"."${item.newName}"`;
}
case 'ColumnAlter': {
return `The column "${item.tableName}"."${item.columnName}" has changes that need to be applied ${JSON.stringify(
item.changes,
)}`;
}
case 'ColumnDrop': {
return `The column "${item.tableName}"."${item.columnName}" exists but should be removed`;
}
case 'ConstraintAdd': {
return `The constraint "${item.constraint.tableName}"."${item.constraint.name}" (${item.constraint.type}) is missing and needs to be created`;
}
case 'ConstraintRename': {
return `The constraint "${item.tableName}"."${item.oldName}" was renamed to "${item.tableName}"."${item.newName}"`;
}
case 'ConstraintDrop': {
return `The constraint "${item.tableName}"."${item.constraintName}" exists but should be removed`;
}
case 'IndexCreate': {
return `The index "${item.index.tableName}"."${item.index.name}" is missing and needs to be created`;
}
case 'IndexRename': {
return `The index "${item.tableName}"."${item.oldName}" was renamed to "${item.tableName}"."${item.newName}"`;
}
case 'IndexDrop': {
return `The index "${item.indexName}" exists but is no longer needed`;
}
case 'TriggerCreate': {
return `The trigger "${item.trigger.tableName}"."${item.trigger.name}" is missing and needs to be created`;
}
case 'TriggerDrop': {
return `The trigger "${item.tableName}"."${item.triggerName}" exists but is no longer needed`;
}
case 'ParameterSet': {
return `The configuration parameter "${item.parameter.name}" has a different value and needs to be updated to "${item.parameter.value}"`;
}
case 'ParameterReset': {
return `The configuration parameter "${item.parameterName}" is set, but should be reset to the default value`;
}
case 'EnumCreate': {
return `The enum "${item.enum.name}" is missing and needs to be created`;
}
case 'EnumDrop': {
return `The enum "${item.enumName}" exists but is no longer needed`;
}
case 'OverrideCreate': {
return `The override "${item.override.name}" is missing and needs to be created`;
}
case 'OverrideUpdate': {
return `The override "${item.override.name}" needs to be updated`;
}
case 'OverrideDrop': {
return `The override "${item.overrideName}" exists but is no longer needed`;
}
}
};
const withComments = (comments: boolean | undefined, item: SchemaDiff): string => {
if (!comments) {
return '';
+12 -3
View File
@@ -5,14 +5,20 @@ import { ReaderContext } from 'src/sql-tools/contexts/reader-context';
import { readers } from 'src/sql-tools/readers';
import { DatabaseSchema, PostgresDB, SchemaFromDatabaseOptions } from 'src/sql-tools/types';
export type DatabaseLike = Sql | Kysely<any>;
const isKysely = (db: DatabaseLike): db is Kysely<any> => db instanceof Kysely;
/**
* Load schema from a database url
*/
export const schemaFromDatabase = async (
postgres: Sql,
database: DatabaseLike,
options: SchemaFromDatabaseOptions = {},
): Promise<DatabaseSchema> => {
const db = new Kysely<PostgresDB>({ dialect: new PostgresJSDialect({ postgres }) });
const db = isKysely(database)
? (database as Kysely<PostgresDB>)
: new Kysely<PostgresDB>({ dialect: new PostgresJSDialect({ postgres: database }) });
const ctx = new ReaderContext(options);
try {
@@ -22,6 +28,9 @@ export const schemaFromDatabase = async (
return ctx.build();
} finally {
await db.destroy();
// only close the connection it we created it
if (!isKysely(database)) {
await db.destroy();
}
}
};
+4
View File
@@ -30,6 +30,10 @@ export type SchemaDiffToSqlOptions = BaseContextOptions & {
export type SchemaDiffOptions = BaseContextOptions & {
tables?: IgnoreOptions;
columns?: IgnoreOptions;
indexes?: IgnoreOptions;
triggers?: IgnoreOptions;
constraints?: IgnoreOptions;
functions?: IgnoreOptions;
enums?: IgnoreOptions;
extensions?: IgnoreOptions;
@@ -0,0 +1,47 @@
import { Selectable } from 'kysely';
import { SourceType } from 'src/enum';
import { AssetFaceTable } from 'src/schema/tables/asset-face.table';
import { build } from 'test/factories/builder.factory';
import { PersonFactory } from 'test/factories/person.factory';
import { AssetFaceLike, FactoryBuilder, PersonLike } from 'test/factories/types';
import { newDate, newUuid, newUuidV7 } from 'test/small.factory';
export class AssetFaceFactory {
#person: PersonFactory | null = null;
private constructor(private readonly value: Selectable<AssetFaceTable>) {}
static create(dto: AssetFaceLike = {}) {
return AssetFaceFactory.from(dto).build();
}
static from(dto: AssetFaceLike = {}) {
return new AssetFaceFactory({
assetId: newUuid(),
boundingBoxX1: 11,
boundingBoxX2: 12,
boundingBoxY1: 21,
boundingBoxY2: 22,
deletedAt: null,
id: newUuid(),
imageHeight: 42,
imageWidth: 420,
isVisible: true,
personId: null,
sourceType: SourceType.MachineLearning,
updatedAt: newDate(),
updateId: newUuidV7(),
...dto,
});
}
person(dto: PersonLike = {}, builder?: FactoryBuilder<PersonFactory>) {
this.#person = build(PersonFactory.from(dto), builder);
this.value.personId = this.#person.build().id;
return this;
}
build() {
return { ...this.value, person: this.#person?.build() ?? null };
}
}
+30 -4
View File
@@ -1,12 +1,23 @@
import { Selectable } from 'kysely';
import { AssetFileType, AssetStatus, AssetType, AssetVisibility } from 'src/enum';
import { AssetFaceTable } from 'src/schema/tables/asset-face.table';
import { AssetTable } from 'src/schema/tables/asset.table';
import { StackTable } from 'src/schema/tables/stack.table';
import { AssetEditFactory } from 'test/factories/asset-edit.factory';
import { AssetExifFactory } from 'test/factories/asset-exif.factory';
import { AssetFaceFactory } from 'test/factories/asset-face.factory';
import { AssetFileFactory } from 'test/factories/asset-file.factory';
import { build } from 'test/factories/builder.factory';
import { AssetEditLike, AssetExifLike, AssetFileLike, AssetLike, FactoryBuilder, UserLike } from 'test/factories/types';
import { StackFactory } from 'test/factories/stack.factory';
import {
AssetEditLike,
AssetExifLike,
AssetFaceLike,
AssetFileLike,
AssetLike,
FactoryBuilder,
StackLike,
UserLike,
} from 'test/factories/types';
import { UserFactory } from 'test/factories/user.factory';
import { newDate, newSha1, newUuid, newUuidV7 } from 'test/small.factory';
@@ -15,6 +26,8 @@ export class AssetFactory {
#assetExif?: AssetExifFactory;
#files: AssetFileFactory[] = [];
#edits: AssetEditFactory[] = [];
#faces: AssetFaceFactory[] = [];
#stack?: Selectable<StackTable> & { assets: Selectable<AssetTable>[]; primaryAsset: Selectable<AssetTable> };
private constructor(private readonly value: Selectable<AssetTable>) {
value.ownerId ??= newUuid();
@@ -28,7 +41,7 @@ export class AssetFactory {
static from(dto: AssetLike = {}) {
const id = dto.id ?? newUuid();
const originalFileName = dto.originalFileName ?? `IMG_${id}.jpg`;
const originalFileName = dto.originalFileName ?? (dto.type === AssetType.Video ? `MOV_${id}.mp4` : `IMG_${id}.jpg`);
return new AssetFactory({
id,
@@ -82,6 +95,11 @@ export class AssetFactory {
return this;
}
face(dto: AssetFaceLike = {}, builder?: FactoryBuilder<AssetFaceFactory>) {
this.#faces.push(build(AssetFaceFactory.from(dto), builder));
return this;
}
file(dto: AssetFileLike = {}, builder?: FactoryBuilder<AssetFileFactory>) {
this.#files.push(build(AssetFileFactory.from(dto).asset(this.value), builder));
return this;
@@ -111,6 +129,12 @@ export class AssetFactory {
return this;
}
stack(dto: StackLike = {}, builder?: FactoryBuilder<StackFactory>) {
this.#stack = build(StackFactory.from(dto).primaryAsset(this.value), builder).build();
this.value.stackId = this.#stack.id;
return this;
}
build() {
const exif = this.#assetExif?.build();
@@ -120,7 +144,9 @@ export class AssetFactory {
exifInfo: exif as NonNullable<typeof exif>,
files: this.#files.map((file) => file.build()),
edits: this.#edits.map((edit) => edit.build()),
faces: [] as Selectable<AssetFaceTable>[],
faces: this.#faces.map((face) => face.build()),
stack: this.#stack ?? null,
tags: [],
};
}
}
+34
View File
@@ -0,0 +1,34 @@
import { Selectable } from 'kysely';
import { PersonTable } from 'src/schema/tables/person.table';
import { PersonLike } from 'test/factories/types';
import { newDate, newUuid, newUuidV7 } from 'test/small.factory';
export class PersonFactory {
private constructor(private readonly value: Selectable<PersonTable>) {}
static create(dto: PersonLike = {}) {
return PersonFactory.from(dto).build();
}
static from(dto: PersonLike = {}) {
return new PersonFactory({
birthDate: null,
color: null,
createdAt: newDate(),
faceAssetId: null,
id: newUuid(),
isFavorite: false,
isHidden: false,
name: 'person',
ownerId: newUuid(),
thumbnailPath: '/data/thumbs/person-thumbnail.jpg',
updatedAt: newDate(),
updateId: newUuidV7(),
...dto,
});
}
build() {
return { ...this.value };
}
}
+11 -3
View File
@@ -2,14 +2,16 @@ import { Selectable } from 'kysely';
import { SharedLinkType } from 'src/enum';
import { SharedLinkTable } from 'src/schema/tables/shared-link.table';
import { AlbumFactory } from 'test/factories/album.factory';
import { AssetFactory } from 'test/factories/asset.factory';
import { build } from 'test/factories/builder.factory';
import { AlbumLike, FactoryBuilder, SharedLinkLike, UserLike } from 'test/factories/types';
import { AlbumLike, AssetLike, FactoryBuilder, SharedLinkLike, UserLike } from 'test/factories/types';
import { UserFactory } from 'test/factories/user.factory';
import { factory, newDate, newUuid } from 'test/small.factory';
export class SharedLinkFactory {
#owner: UserFactory;
#album?: AlbumFactory;
#assets: AssetFactory[] = [];
private constructor(private readonly value: Selectable<SharedLinkTable>) {
value.userId ??= newUuid();
@@ -52,12 +54,18 @@ export class SharedLinkFactory {
return this;
}
asset(dto: AssetLike = {}, builder?: FactoryBuilder<AssetFactory>) {
const asset = build(AssetFactory.from(dto), builder);
this.#assets.push(asset);
return this;
}
build() {
return {
...this.value,
owner: this.#owner.build(),
album: this.#album?.build(),
assets: [],
album: this.#album?.build() ?? null,
assets: this.#assets.map((asset) => asset.build()),
};
}
}
+52
View File
@@ -0,0 +1,52 @@
import { Selectable } from 'kysely';
import { StackTable } from 'src/schema/tables/stack.table';
import { AssetFactory } from 'test/factories/asset.factory';
import { build } from 'test/factories/builder.factory';
import { AssetLike, FactoryBuilder, StackLike } from 'test/factories/types';
import { newDate, newUuid, newUuidV7 } from 'test/small.factory';
export class StackFactory {
#assets: AssetFactory[] = [];
#primaryAsset: AssetFactory;
private constructor(private readonly value: Selectable<StackTable>) {
this.#primaryAsset = AssetFactory.from();
this.value.primaryAssetId = this.#primaryAsset.build().id;
}
static create(dto: StackLike = {}) {
return StackFactory.from(dto).build();
}
static from(dto: StackLike = {}) {
return new StackFactory({
createdAt: newDate(),
id: newUuid(),
ownerId: newUuid(),
primaryAssetId: newUuid(),
updatedAt: newDate(),
updateId: newUuidV7(),
...dto,
});
}
asset(dto: AssetLike = {}, builder?: FactoryBuilder<AssetFactory>) {
this.#assets.push(build(AssetFactory.from(dto), builder));
return this;
}
primaryAsset(dto: AssetLike = {}, builder?: FactoryBuilder<AssetFactory>) {
this.#primaryAsset = build(AssetFactory.from(dto), builder);
this.value.primaryAssetId = this.#primaryAsset.build().id;
this.#assets.push(this.#primaryAsset);
return this;
}
build() {
return {
...this.value,
assets: this.#assets.map((asset) => asset.build()),
primaryAsset: this.#primaryAsset.build(),
};
}
}
+6
View File
@@ -3,9 +3,12 @@ import { AlbumUserTable } from 'src/schema/tables/album-user.table';
import { AlbumTable } from 'src/schema/tables/album.table';
import { AssetEditTable } from 'src/schema/tables/asset-edit.table';
import { AssetExifTable } from 'src/schema/tables/asset-exif.table';
import { AssetFaceTable } from 'src/schema/tables/asset-face.table';
import { AssetFileTable } from 'src/schema/tables/asset-file.table';
import { AssetTable } from 'src/schema/tables/asset.table';
import { PersonTable } from 'src/schema/tables/person.table';
import { SharedLinkTable } from 'src/schema/tables/shared-link.table';
import { StackTable } from 'src/schema/tables/stack.table';
import { UserTable } from 'src/schema/tables/user.table';
export type FactoryBuilder<T, R extends T = T> = (builder: T) => R;
@@ -18,3 +21,6 @@ export type AlbumLike = Partial<Selectable<AlbumTable>>;
export type AlbumUserLike = Partial<Selectable<AlbumUserTable>>;
export type SharedLinkLike = Partial<Selectable<SharedLinkTable>>;
export type UserLike = Partial<Selectable<UserTable>>;
export type AssetFaceLike = Partial<Selectable<AssetFaceTable>>;
export type PersonLike = Partial<Selectable<PersonTable>>;
export type StackLike = Partial<Selectable<StackTable>>;
+14 -1
View File
@@ -6,6 +6,8 @@ import { UserLike } from 'test/factories/types';
import { newDate, newUuid, newUuidV7 } from 'test/small.factory';
export class UserFactory {
#metadata: Selectable<UserMetadataTable>[] = [];
private constructor(private value: Selectable<UserTable>) {}
static create(dto: UserLike = {}) {
@@ -37,10 +39,21 @@ export class UserFactory {
});
}
metadata(dto: Partial<Selectable<UserMetadataTable>> & Pick<Selectable<UserMetadataTable>, 'key' | 'value'>) {
this.#metadata.push({
updatedAt: newDate(),
updateId: newUuid(),
userId: newUuid(),
...dto,
});
return this;
}
build() {
return {
...this.value,
metadata: [] as UserMetadataTable[],
metadata: this.#metadata,
};
}
}
-84
View File
@@ -1,84 +0,0 @@
import { AlbumUserRole, AssetOrder } from 'src/enum';
import { assetStub } from 'test/fixtures/asset.stub';
import { authStub } from 'test/fixtures/auth.stub';
import { userStub } from 'test/fixtures/user.stub';
export const albumStub = {
empty: Object.freeze({
id: 'album-1',
albumName: 'Empty album',
description: '',
ownerId: authStub.admin.user.id,
owner: userStub.admin,
assets: [],
albumThumbnailAsset: null,
albumThumbnailAssetId: null,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null,
sharedLinks: [],
albumUsers: [],
isActivityEnabled: true,
order: AssetOrder.Desc,
updateId: '42',
}),
sharedWithUser: Object.freeze({
id: 'album-2',
albumName: 'Empty album shared with user',
description: '',
ownerId: authStub.admin.user.id,
owner: userStub.admin,
assets: [],
albumThumbnailAsset: null,
albumThumbnailAssetId: null,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null,
sharedLinks: [],
albumUsers: [
{
user: userStub.user1,
role: AlbumUserRole.Editor,
},
],
isActivityEnabled: true,
order: AssetOrder.Desc,
updateId: '42',
}),
oneAsset: Object.freeze({
id: 'album-4',
albumName: 'Album with one asset',
description: '',
ownerId: authStub.admin.user.id,
owner: userStub.admin,
assets: [assetStub.image],
albumThumbnailAsset: null,
albumThumbnailAssetId: null,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null,
sharedLinks: [],
albumUsers: [],
isActivityEnabled: true,
order: AssetOrder.Desc,
updateId: '42',
}),
emptyWithValidThumbnail: Object.freeze({
id: 'album-5',
albumName: 'Empty album with valid thumbnail',
description: '',
ownerId: authStub.admin.user.id,
owner: userStub.admin,
assets: [],
albumThumbnailAsset: assetStub.image,
albumThumbnailAssetId: assetStub.image.id,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null,
sharedLinks: [],
albumUsers: [],
isActivityEnabled: true,
order: AssetOrder.Desc,
updateId: '42',
}),
};
-723
View File
@@ -1,723 +0,0 @@
import { AssetFace, AssetFile, Exif } from 'src/database';
import { MapAsset } from 'src/dtos/asset-response.dto';
import { AssetEditAction, AssetEditActionItem } from 'src/dtos/editing.dto';
import { AssetFileType, AssetStatus, AssetType, AssetVisibility } from 'src/enum';
import { StorageAsset } from 'src/types';
import { authStub } from 'test/fixtures/auth.stub';
import { fileStub } from 'test/fixtures/file.stub';
import { userStub } from 'test/fixtures/user.stub';
import { factory } from 'test/small.factory';
export const previewFile = factory.assetFile({ type: AssetFileType.Preview });
const thumbnailFile = factory.assetFile({
type: AssetFileType.Thumbnail,
path: '/uploads/user-id/webp/path.ext',
});
const fullsizeFile = factory.assetFile({
type: AssetFileType.FullSize,
path: '/uploads/user-id/fullsize/path.webp',
});
const files = [fullsizeFile, previewFile, thumbnailFile];
export const stackStub = (stackId: string, assets: (MapAsset & { exifInfo: Exif })[]) => {
return {
id: stackId,
assets,
ownerId: assets[0].ownerId,
primaryAsset: assets[0],
primaryAssetId: assets[0].id,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
updateId: expect.any(String),
};
};
export const assetStub = {
storageAsset: (asset: Partial<StorageAsset> = {}) => ({
id: 'asset-id',
ownerId: 'user-id',
livePhotoVideoId: null,
type: AssetType.Image,
isExternal: false,
checksum: Buffer.from('file hash'),
timeZone: null,
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
originalPath: '/original/path.jpg',
originalFileName: 'IMG_123.jpg',
fileSizeInByte: 12_345,
files: [],
make: 'FUJIFILM',
model: 'X-T50',
lensModel: 'XF27mm F2.8 R WR',
isEdited: false,
...asset,
}),
noResizePath: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
originalFileName: 'IMG_123.jpg',
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/data/library/IMG_123.jpg',
files: [thumbnailFile],
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Image,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: true,
duration: null,
livePhotoVideo: null,
livePhotoVideoId: null,
sharedLinks: [],
faces: [],
exifInfo: {} as Exif,
deletedAt: null,
isExternal: false,
duplicateId: null,
isOffline: false,
libraryId: null,
stackId: null,
updateId: '42',
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
primaryImage: Object.freeze({
id: 'primary-asset-id',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.admin,
ownerId: 'admin-id',
deviceId: 'device-id',
originalPath: '/original/path.jpg',
checksum: Buffer.from('file hash', 'utf8'),
files,
type: AssetType.Image,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: true,
duration: null,
isExternal: false,
livePhotoVideo: null,
livePhotoVideoId: null,
sharedLinks: [],
originalFileName: 'asset-id.jpg',
faces: [],
deletedAt: null,
exifInfo: {
fileSizeInByte: 5000,
exifImageHeight: 1000,
exifImageWidth: 1000,
} as Exif,
stackId: 'stack-1',
stack: stackStub('stack-1', [
{ id: 'primary-asset-id' } as MapAsset & { exifInfo: Exif },
{ id: 'stack-child-asset-1' } as MapAsset & { exifInfo: Exif },
{ id: 'stack-child-asset-2' } as MapAsset & { exifInfo: Exif },
]),
duplicateId: null,
isOffline: false,
updateId: '42',
libraryId: null,
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
image: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.jpg',
files,
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Image,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2025-01-01T01:02:03.456Z'),
isFavorite: true,
duration: null,
isExternal: false,
livePhotoVideo: null,
livePhotoVideoId: null,
updateId: 'foo',
libraryId: null,
stackId: null,
sharedLinks: [],
originalFileName: 'asset-id.jpg',
faces: [],
deletedAt: null,
exifInfo: {
fileSizeInByte: 5000,
exifImageHeight: 3840,
exifImageWidth: 2160,
} as Exif,
duplicateId: null,
isOffline: false,
stack: null,
orientation: '',
projectionType: null,
height: null,
width: null,
visibility: AssetVisibility.Timeline,
edits: [],
isEdited: false,
}),
trashed: Object.freeze({
id: 'asset-id',
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.jpg',
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Image,
files,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
deletedAt: new Date('2023-02-24T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: false,
duration: null,
isExternal: false,
livePhotoVideo: null,
livePhotoVideoId: null,
sharedLinks: [],
originalFileName: 'asset-id.jpg',
faces: [],
exifInfo: {
fileSizeInByte: 5000,
exifImageHeight: 3840,
exifImageWidth: 2160,
} as Exif,
duplicateId: null,
isOffline: false,
status: AssetStatus.Trashed,
libraryId: null,
stackId: null,
updateId: '42',
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
trashedOffline: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.jpg',
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Image,
files,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
deletedAt: new Date('2023-02-24T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: false,
duration: null,
libraryId: 'library-id',
isExternal: false,
livePhotoVideo: null,
livePhotoVideoId: null,
sharedLinks: [],
originalFileName: 'asset-id.jpg',
faces: [],
exifInfo: {
fileSizeInByte: 5000,
exifImageHeight: 3840,
exifImageWidth: 2160,
} as Exif,
duplicateId: null,
isOffline: true,
stackId: null,
updateId: '42',
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
archived: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.jpg',
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Image,
files,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: true,
duration: null,
isExternal: false,
livePhotoVideo: null,
livePhotoVideoId: null,
sharedLinks: [],
originalFileName: 'asset-id.jpg',
faces: [],
deletedAt: null,
exifInfo: {
fileSizeInByte: 5000,
exifImageHeight: 3840,
exifImageWidth: 2160,
} as Exif,
duplicateId: null,
isOffline: false,
libraryId: null,
stackId: null,
updateId: '42',
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
external: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/data/user1/photo.jpg',
checksum: Buffer.from('path hash', 'utf8'),
type: AssetType.Image,
files,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: true,
isExternal: true,
duration: null,
livePhotoVideo: null,
livePhotoVideoId: null,
libraryId: 'library-id',
sharedLinks: [],
originalFileName: 'asset-id.jpg',
faces: [],
deletedAt: null,
exifInfo: {
fileSizeInByte: 5000,
} as Exif,
duplicateId: null,
isOffline: false,
updateId: '42',
stackId: null,
stack: null,
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
image1: Object.freeze({
id: 'asset-id-1',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.ext',
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Image,
files,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
deletedAt: null,
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: true,
duration: null,
livePhotoVideo: null,
livePhotoVideoId: null,
isExternal: false,
sharedLinks: [],
originalFileName: 'asset-id.ext',
faces: [],
exifInfo: {
fileSizeInByte: 5000,
} as Exif,
duplicateId: null,
isOffline: false,
updateId: '42',
stackId: null,
libraryId: null,
stack: null,
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
video: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
originalFileName: 'asset-id.ext',
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.ext',
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Video,
files: [previewFile],
thumbhash: null,
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: true,
isExternal: false,
duration: null,
livePhotoVideo: null,
livePhotoVideoId: null,
sharedLinks: [],
faces: [],
exifInfo: {
fileSizeInByte: 100_000,
exifImageHeight: 2160,
exifImageWidth: 3840,
} as Exif,
deletedAt: null,
duplicateId: null,
isOffline: false,
updateId: '42',
libraryId: null,
stackId: null,
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
livePhotoMotionAsset: Object.freeze({
status: AssetStatus.Active,
id: fileStub.livePhotoMotion.uuid,
originalPath: fileStub.livePhotoMotion.originalPath,
ownerId: authStub.user1.user.id,
type: AssetType.Video,
fileModifiedAt: new Date('2022-06-19T23:41:36.910Z'),
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
exifInfo: {
fileSizeInByte: 100_000,
timeZone: `America/New_York`,
},
files: [],
libraryId: null,
visibility: AssetVisibility.Hidden,
width: null,
height: null,
edits: [] as AssetEditActionItem[],
isEdited: false,
} as unknown as MapAsset & {
faces: AssetFace[];
files: (AssetFile & { isProgressive: boolean })[];
exifInfo: Exif;
edits: AssetEditActionItem[];
}),
livePhotoStillAsset: Object.freeze({
id: 'live-photo-still-asset',
status: AssetStatus.Active,
originalPath: fileStub.livePhotoStill.originalPath,
ownerId: authStub.user1.user.id,
type: AssetType.Image,
livePhotoVideoId: 'live-photo-motion-asset',
fileModifiedAt: new Date('2022-06-19T23:41:36.910Z'),
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
exifInfo: {
fileSizeInByte: 25_000,
timeZone: `America/New_York`,
},
files,
faces: [] as AssetFace[],
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [] as AssetEditActionItem[],
isEdited: false,
} as unknown as MapAsset & {
faces: AssetFace[];
files: (AssetFile & { isProgressive: boolean })[];
edits: AssetEditActionItem[];
}),
livePhotoWithOriginalFileName: Object.freeze({
id: 'live-photo-still-asset',
status: AssetStatus.Active,
originalPath: fileStub.livePhotoStill.originalPath,
originalFileName: fileStub.livePhotoStill.originalName,
ownerId: authStub.user1.user.id,
type: AssetType.Image,
livePhotoVideoId: 'live-photo-motion-asset',
fileModifiedAt: new Date('2022-06-19T23:41:36.910Z'),
fileCreatedAt: new Date('2022-06-19T23:41:36.910Z'),
exifInfo: {
fileSizeInByte: 25_000,
timeZone: `America/New_York`,
},
files: [] as AssetFile[],
libraryId: null,
faces: [] as AssetFace[],
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [] as AssetEditActionItem[],
isEdited: false,
} as MapAsset & { faces: AssetFace[]; files: AssetFile[]; edits: AssetEditActionItem[] }),
withLocation: Object.freeze({
id: 'asset-with-favorite-id',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-22T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-22T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
checksum: Buffer.from('file hash', 'utf8'),
originalPath: '/original/path.ext',
type: AssetType.Image,
files: [previewFile],
thumbhash: null,
encodedVideoPath: null,
createdAt: new Date('2023-02-22T05:06:29.716Z'),
updatedAt: new Date('2023-02-22T05:06:29.716Z'),
localDateTime: new Date('2020-12-31T23:59:00.000Z'),
isFavorite: false,
isExternal: false,
duration: null,
livePhotoVideo: null,
livePhotoVideoId: null,
updateId: 'foo',
libraryId: null,
stackId: null,
sharedLinks: [],
originalFileName: 'asset-id.ext',
faces: [],
exifInfo: {
latitude: 100,
longitude: 100,
fileSizeInByte: 23_456,
city: 'test-city',
state: 'test-state',
country: 'test-country',
} as Exif,
deletedAt: null,
duplicateId: null,
isOffline: false,
tags: [],
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
hasEncodedVideo: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
originalFileName: 'asset-id.ext',
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.ext',
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Video,
files: [previewFile],
thumbhash: null,
encodedVideoPath: '/encoded/video/path.mp4',
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: true,
isExternal: false,
duration: null,
livePhotoVideo: null,
livePhotoVideoId: null,
sharedLinks: [],
faces: [],
exifInfo: {
fileSizeInByte: 100_000,
} as Exif,
deletedAt: null,
duplicateId: null,
isOffline: false,
updateId: '42',
libraryId: null,
stackId: null,
stack: null,
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
imageDng: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.dng',
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Image,
files,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2023-02-23T05:06:29.716Z'),
isFavorite: true,
duration: null,
isExternal: false,
livePhotoVideo: null,
livePhotoVideoId: null,
sharedLinks: [],
originalFileName: 'asset-id.dng',
faces: [],
deletedAt: null,
exifInfo: {
fileSizeInByte: 5000,
profileDescription: 'Adobe RGB',
bitsPerSample: 14,
} as Exif,
duplicateId: null,
isOffline: false,
updateId: '42',
libraryId: null,
stackId: null,
visibility: AssetVisibility.Timeline,
width: null,
height: null,
edits: [],
isEdited: false,
}),
withCropEdit: Object.freeze({
id: 'asset-id',
status: AssetStatus.Active,
deviceAssetId: 'device-asset-id',
fileModifiedAt: new Date('2023-02-23T05:06:29.716Z'),
fileCreatedAt: new Date('2023-02-23T05:06:29.716Z'),
owner: userStub.user1,
ownerId: 'user-id',
deviceId: 'device-id',
originalPath: '/original/path.jpg',
files,
checksum: Buffer.from('file hash', 'utf8'),
type: AssetType.Image,
thumbhash: Buffer.from('blablabla', 'base64'),
encodedVideoPath: null,
createdAt: new Date('2023-02-23T05:06:29.716Z'),
updatedAt: new Date('2023-02-23T05:06:29.716Z'),
localDateTime: new Date('2025-01-01T01:02:03.456Z'),
isFavorite: true,
duration: null,
isExternal: false,
livePhotoVideo: null,
livePhotoVideoId: null,
updateId: 'foo',
libraryId: null,
stackId: null,
sharedLinks: [],
originalFileName: 'asset-id.jpg',
faces: [],
deletedAt: null,
sidecarPath: null,
exifInfo: {
fileSizeInByte: 5000,
exifImageHeight: 3840,
exifImageWidth: 2160,
} as Exif,
duplicateId: null,
isOffline: false,
stack: null,
orientation: '',
projectionType: null,
height: 3840,
width: 2160,
visibility: AssetVisibility.Timeline,
edits: [
{
action: AssetEditAction.Crop,
parameters: {
width: 1512,
height: 1152,
x: 216,
y: 1512,
},
},
] as AssetEditActionItem[],
isEdited: true,
}),
};
+17 -17
View File
@@ -1,13 +1,13 @@
import { SourceType } from 'src/enum';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { personStub } from 'test/fixtures/person.stub';
export const faceStub = {
face1: Object.freeze({
id: 'assetFaceId1',
assetId: assetStub.image.id,
assetId: 'asset-id',
asset: {
...assetStub.image,
...AssetFactory.create({ id: 'asset-id' }),
libraryId: null,
updateId: '0d1173e3-4d80-4d76-b41e-57d56de21125',
stackId: null,
@@ -29,8 +29,8 @@ export const faceStub = {
}),
primaryFace1: Object.freeze({
id: 'assetFaceId2',
assetId: assetStub.image.id,
asset: assetStub.image,
assetId: 'asset-id',
asset: AssetFactory.create({ id: 'asset-id' }),
personId: personStub.primaryPerson.id,
person: personStub.primaryPerson,
boundingBoxX1: 0,
@@ -48,8 +48,8 @@ export const faceStub = {
}),
mergeFace1: Object.freeze({
id: 'assetFaceId3',
assetId: assetStub.image.id,
asset: assetStub.image,
assetId: 'asset-id',
asset: AssetFactory.create({ id: 'asset-id' }),
personId: personStub.mergePerson.id,
person: personStub.mergePerson,
boundingBoxX1: 0,
@@ -67,8 +67,8 @@ export const faceStub = {
}),
noPerson1: Object.freeze({
id: 'assetFaceId8',
assetId: assetStub.image.id,
asset: assetStub.image,
assetId: 'asset-id',
asset: AssetFactory.create({ id: 'asset-id' }),
personId: null,
person: null,
boundingBoxX1: 0,
@@ -86,8 +86,8 @@ export const faceStub = {
}),
noPerson2: Object.freeze({
id: 'assetFaceId9',
assetId: assetStub.image.id,
asset: assetStub.image,
assetId: 'asset-id',
asset: AssetFactory.create({ id: 'asset-id' }),
personId: null,
person: null,
boundingBoxX1: 0,
@@ -105,8 +105,8 @@ export const faceStub = {
}),
fromExif1: Object.freeze({
id: 'assetFaceId9',
assetId: assetStub.image.id,
asset: assetStub.image,
assetId: 'asset-id',
asset: AssetFactory.create({ id: 'asset-id' }),
personId: personStub.randomPerson.id,
person: personStub.randomPerson,
boundingBoxX1: 100,
@@ -123,8 +123,8 @@ export const faceStub = {
}),
fromExif2: Object.freeze({
id: 'assetFaceId9',
assetId: assetStub.image.id,
asset: assetStub.image,
assetId: 'asset-id',
asset: AssetFactory.create({ id: 'asset-id' }),
personId: personStub.randomPerson.id,
person: personStub.randomPerson,
boundingBoxX1: 0,
@@ -141,8 +141,8 @@ export const faceStub = {
}),
withBirthDate: Object.freeze({
id: 'assetFaceId10',
assetId: assetStub.image.id,
asset: assetStub.image,
assetId: 'asset-id',
asset: AssetFactory.create({ id: 'asset-id' }),
personId: personStub.withBirthDate.id,
person: personStub.withBirthDate,
boundingBoxX1: 0,
+9 -9
View File
@@ -1,5 +1,5 @@
import { AssetType } from 'src/enum';
import { previewFile } from 'test/fixtures/asset.stub';
import { AssetFileType, AssetType } from 'src/enum';
import { AssetFileFactory } from 'test/factories/asset-file.factory';
import { userStub } from 'test/fixtures/user.stub';
const updateId = '0d1173e3-4d80-4d76-b41e-57d56de21125';
@@ -179,7 +179,7 @@ export const personThumbnailStub = {
type: AssetType.Image,
originalPath: '/original/path.jpg',
exifOrientation: '1',
previewPath: previewFile.path,
previewPath: AssetFileFactory.create({ type: AssetFileType.Preview }).path,
}),
newThumbnailMiddle: Object.freeze({
ownerId: userStub.admin.id,
@@ -192,7 +192,7 @@ export const personThumbnailStub = {
type: AssetType.Image,
originalPath: '/original/path.jpg',
exifOrientation: '1',
previewPath: previewFile.path,
previewPath: AssetFileFactory.create({ type: AssetFileType.Preview }).path,
}),
newThumbnailEnd: Object.freeze({
ownerId: userStub.admin.id,
@@ -205,7 +205,7 @@ export const personThumbnailStub = {
type: AssetType.Image,
originalPath: '/original/path.jpg',
exifOrientation: '1',
previewPath: previewFile.path,
previewPath: AssetFileFactory.create({ type: AssetFileType.Preview }).path,
}),
rawEmbeddedThumbnail: Object.freeze({
ownerId: userStub.admin.id,
@@ -218,7 +218,7 @@ export const personThumbnailStub = {
type: AssetType.Image,
originalPath: '/original/path.dng',
exifOrientation: '1',
previewPath: previewFile.path,
previewPath: AssetFileFactory.create({ type: AssetFileType.Preview }).path,
}),
negativeCoordinate: Object.freeze({
ownerId: userStub.admin.id,
@@ -231,7 +231,7 @@ export const personThumbnailStub = {
type: AssetType.Image,
originalPath: '/original/path.jpg',
exifOrientation: '1',
previewPath: previewFile.path,
previewPath: AssetFileFactory.create({ type: AssetFileType.Preview }).path,
}),
overflowingCoordinate: Object.freeze({
ownerId: userStub.admin.id,
@@ -244,7 +244,7 @@ export const personThumbnailStub = {
type: AssetType.Image,
originalPath: '/original/path.jpg',
exifOrientation: '1',
previewPath: previewFile.path,
previewPath: AssetFileFactory.create({ type: AssetFileType.Preview }).path,
}),
videoThumbnail: Object.freeze({
ownerId: userStub.admin.id,
@@ -257,6 +257,6 @@ export const personThumbnailStub = {
type: AssetType.Video,
originalPath: '/original/path.mp4',
exifOrientation: '1',
previewPath: previewFile.path,
previewPath: AssetFileFactory.create({ type: AssetFileType.Preview }).path,
}),
};
+2 -2
View File
@@ -2,7 +2,7 @@ import { UserAdmin } from 'src/database';
import { MapAsset } from 'src/dtos/asset-response.dto';
import { SharedLinkResponseDto } from 'src/dtos/shared-link.dto';
import { AssetStatus, AssetType, AssetVisibility, SharedLinkType } from 'src/enum';
import { assetStub } from 'test/fixtures/asset.stub';
import { AssetFactory } from 'test/factories/asset.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { userStub } from 'test/fixtures/user.stub';
@@ -31,7 +31,7 @@ export const sharedLinkStub = {
albumId: null,
album: null,
description: null,
assets: [assetStub.image],
assets: [AssetFactory.create()],
password: 'password',
slug: null,
}),
+22
View File
@@ -0,0 +1,22 @@
import { AssetFactory } from 'test/factories/asset.factory';
export const getForStorageTemplate = (asset: ReturnType<AssetFactory['build']>) => {
return {
id: asset.id,
ownerId: asset.ownerId,
livePhotoVideoId: asset.livePhotoVideoId,
type: asset.type,
isExternal: asset.isExternal,
checksum: asset.checksum,
timeZone: asset.exifInfo.timeZone,
fileCreatedAt: asset.fileCreatedAt,
originalPath: asset.originalPath,
originalFileName: asset.originalFileName,
fileSizeInByte: asset.exifInfo.fileSizeInByte,
files: asset.files,
make: asset.exifInfo.make,
model: asset.exifInfo.model,
lensModel: asset.exifInfo.lensModel,
isEdited: asset.isEdited,
};
};
@@ -90,7 +90,7 @@ describe(SharedLinkService.name, () => {
assetIds: assets.map(({ asset }) => asset.id),
});
await expect(sut.getMine({ user, sharedLink }, {})).resolves.toMatchObject({
await expect(sut.getMine({ user, sharedLink }, [])).resolves.toMatchObject({
assets: assets.map(({ asset }) => expect.objectContaining({ id: asset.id })),
});
});
@@ -114,7 +114,7 @@ describe(SharedLinkService.name, () => {
assetIds: [asset.id],
});
await expect(sut.getMine({ user, sharedLink }, {})).resolves.toMatchObject({
await expect(sut.getMine({ user, sharedLink }, [])).resolves.toMatchObject({
assets: [expect.objectContaining({ id: asset.id })],
});
@@ -122,6 +122,6 @@ describe(SharedLinkService.name, () => {
assetIds: [asset.id],
});
await expect(sut.getMine({ user, sharedLink }, {})).resolves.toHaveProperty('assets', []);
await expect(sut.getMine({ user, sharedLink }, [])).resolves.toHaveProperty('assets', []);
});
});
@@ -1,29 +0,0 @@
import { DatabaseRepository } from 'src/repositories/database.repository';
import { RepositoryInterface } from 'src/types';
import { Mocked, vitest } from 'vitest';
export const newDatabaseRepositoryMock = (): Mocked<RepositoryInterface<DatabaseRepository>> => {
return {
shutdown: vitest.fn(),
getExtensionVersions: vitest.fn(),
getVectorExtension: vitest.fn(),
getExtensionVersionRange: vitest.fn(),
getPostgresVersion: vitest.fn().mockResolvedValue('14.10 (Debian 14.10-1.pgdg120+1)'),
getPostgresVersionRange: vitest.fn().mockReturnValue('>=14.0.0'),
createExtension: vitest.fn().mockResolvedValue(void 0),
dropExtension: vitest.fn(),
updateVectorExtension: vitest.fn(),
reindexVectorsIfNeeded: vitest.fn(),
getDimensionSize: vitest.fn(),
setDimensionSize: vitest.fn(),
deleteAllSearchEmbeddings: vitest.fn(),
prewarm: vitest.fn(),
runMigrations: vitest.fn(),
revertLastMigration: vitest.fn(),
withLock: vitest.fn().mockImplementation((_, function_: <R>() => Promise<R>) => function_()),
tryLock: vitest.fn(),
isBusy: vitest.fn(),
wait: vitest.fn(),
migrateFilePaths: vitest.fn(),
};
};
+9 -2
View File
@@ -75,7 +75,6 @@ import { IAccessRepositoryMock, newAccessRepositoryMock } from 'test/repositorie
import { newAssetRepositoryMock } from 'test/repositories/asset.repository.mock';
import { newConfigRepositoryMock } from 'test/repositories/config.repository.mock';
import { newCryptoRepositoryMock } from 'test/repositories/crypto.repository.mock';
import { newDatabaseRepositoryMock } from 'test/repositories/database.repository.mock';
import { newJobRepositoryMock } from 'test/repositories/job.repository.mock';
import { newMediaRepositoryMock } from 'test/repositories/media.repository.mock';
import { newMetadataRepositoryMock } from 'test/repositories/metadata.repository.mock';
@@ -279,6 +278,14 @@ export const getMocks = () => {
const loggerMock = { setContext: () => {} };
const configMock = { getEnv: () => ({}) };
// eslint-disable-next-line no-sparse-arrays
const databaseMock = automock(DatabaseRepository, { args: [, loggerMock], strict: false });
databaseMock.withLock.mockImplementation((_type, fn) => fn());
databaseMock.getPostgresVersion = vitest.fn().mockResolvedValue('14.10 (Debian 14.10-1.pgdg120+1)');
databaseMock.getPostgresVersionRange = vitest.fn().mockReturnValue('>=14.0.0');
databaseMock.createExtension = vitest.fn().mockResolvedValue(void 0);
const mocks: ServiceMocks = {
access: newAccessRepositoryMock(),
// eslint-disable-next-line no-sparse-arrays
@@ -295,7 +302,7 @@ export const getMocks = () => {
assetJob: automock(AssetJobRepository),
app: automock(AppRepository, { strict: false }),
config: newConfigRepositoryMock(),
database: newDatabaseRepositoryMock(),
database: databaseMock,
downloadRepository: automock(DownloadRepository, { strict: false }),
duplicateRepository: automock(DuplicateRepository),
email: automock(EmailRepository, { args: [loggerMock] }),