Merge remote-tracking branch 'origin/main' into feat/integrity-checks-izzy

Signed-off-by: izzy <me@insrt.uk>
This commit is contained in:
izzy
2026-02-06 16:28:53 +00:00
958 changed files with 36912 additions and 7752 deletions
@@ -25,14 +25,13 @@ export class AlbumUserRepository {
}
@GenerateSql({ params: [{ userId: DummyValue.UUID, albumId: DummyValue.UUID }, { role: AlbumUserRole.Viewer }] })
update({ userId, albumId }: AlbumPermissionId, dto: Updateable<AlbumUserTable>) {
return this.db
async update({ userId, albumId }: AlbumPermissionId, dto: Updateable<AlbumUserTable>) {
await this.db
.updateTable('album_user')
.set(dto)
.where('userId', '=', userId)
.where('albumId', '=', albumId)
.returningAll()
.executeTakeFirstOrThrow();
.execute();
}
@GenerateSql({ params: [{ userId: DummyValue.UUID, albumId: DummyValue.UUID }] })
@@ -12,14 +12,14 @@ export class AssetEditRepository {
@GenerateSql({
params: [DummyValue.UUID],
})
async replaceAll(assetId: string, edits: AssetEditActionItem[]): Promise<AssetEditActionItem[]> {
return await this.db.transaction().execute(async (trx) => {
replaceAll(assetId: string, edits: AssetEditActionItem[]): Promise<AssetEditActionItem[]> {
return this.db.transaction().execute(async (trx) => {
await trx.deleteFrom('asset_edit').where('assetId', '=', assetId).execute();
if (edits.length > 0) {
return trx
.insertInto('asset_edit')
.values(edits.map((edit) => ({ assetId, ...edit })))
.values(edits.map((edit, i) => ({ assetId, sequence: i, ...edit })))
.returning(['action', 'parameters'])
.execute() as Promise<AssetEditActionItem[]>;
}
@@ -31,11 +31,12 @@ export class AssetEditRepository {
@GenerateSql({
params: [DummyValue.UUID],
})
async getAll(assetId: string): Promise<AssetEditActionItem[]> {
getAll(assetId: string): Promise<AssetEditActionItem[]> {
return this.db
.selectFrom('asset_edit')
.select(['action', 'parameters'])
.where('assetId', '=', assetId)
.orderBy('sequence', 'asc')
.execute() as Promise<AssetEditActionItem[]>;
}
}
+79 -28
View File
@@ -1,9 +1,10 @@
import { Injectable } from '@nestjs/common';
import { Kysely } from 'kysely';
import { Kysely, sql } from 'kysely';
import { jsonArrayFrom } from 'kysely/helpers/postgres';
import { InjectKysely } from 'nestjs-kysely';
import { Asset, columns } from 'src/database';
import { columns } from 'src/database';
import { DummyValue, GenerateSql } from 'src/decorators';
import { AssetFileType, AssetType, AssetVisibility } from 'src/enum';
import { AssetFileType, AssetStatus, AssetType, AssetVisibility } from 'src/enum';
import { DB } from 'src/schema';
import {
anyUuid,
@@ -14,7 +15,6 @@ import {
withExif,
withExifInner,
withFaces,
withFacesAndPeople,
withFilePath,
withFiles,
} from 'src/utils/database';
@@ -57,8 +57,8 @@ export class AssetJobRepository {
.executeTakeFirst();
}
@GenerateSql({ params: [false], stream: true })
streamForThumbnailJob(force: boolean) {
@GenerateSql({ params: [{ force: false, fullsizeEnabled: true }], stream: true })
streamForThumbnailJob(options: { force: boolean | undefined; fullsizeEnabled: boolean }) {
return this.db
.selectFrom('asset')
.select(['asset.id', 'asset.thumbhash'])
@@ -66,17 +66,47 @@ export class AssetJobRepository {
.select(withEdits)
.where('asset.deletedAt', 'is', null)
.where('asset.visibility', '!=', AssetVisibility.Hidden)
.$if(!force, (qb) =>
.$if(!options.force, (qb) =>
qb
// If there aren't any entries, metadata extraction hasn't run yet which is required for thumbnails
.innerJoin('asset_job_status', 'asset_job_status.assetId', 'asset.id')
.where((eb) =>
eb.or([
eb('asset_job_status.previewAt', 'is', null),
eb('asset_job_status.thumbnailAt', 'is', null),
eb('asset.thumbhash', 'is', null),
]),
),
.where((eb) => {
const conditions = [
eb.not((eb) =>
eb.exists((qb) =>
qb
.selectFrom('asset_file')
.whereRef('assetId', '=', 'asset.id')
.where('asset_file.type', '=', AssetFileType.Preview),
),
),
eb.not((eb) =>
eb.exists((qb) =>
qb
.selectFrom('asset_file')
.whereRef('assetId', '=', 'asset.id')
.where('asset_file.type', '=', AssetFileType.Thumbnail),
),
),
];
if (options.fullsizeEnabled) {
conditions.push(
eb.not((eb) =>
eb.exists((qb) =>
qb
.selectFrom('asset_file')
.whereRef('assetId', '=', 'asset.id')
.where('asset_file.type', '=', AssetFileType.FullSize),
),
),
);
}
conditions.push(eb('asset.thumbhash', 'is', null));
return eb.or(conditions);
}),
)
.stream();
}
@@ -104,7 +134,15 @@ export class AssetJobRepository {
'asset.thumbhash',
'asset.type',
])
.select(withFiles)
.select((eb) =>
jsonArrayFrom(
eb
.selectFrom('asset_file')
.select(columns.assetFilesForThumbnail)
.whereRef('asset_file.assetId', '=', 'asset.id')
.where('asset_file.type', 'in', [AssetFileType.Thumbnail, AssetFileType.Preview, AssetFileType.FullSize]),
).as('files'),
)
.select(withEdits)
.$call(withExifInner)
.where('asset.id', '=', id)
@@ -148,7 +186,14 @@ export class AssetJobRepository {
.where('asset.visibility', '!=', AssetVisibility.Hidden)
.where('asset.deletedAt', 'is', null)
.innerJoin('asset_job_status as job_status', 'assetId', 'asset.id')
.where('job_status.previewAt', 'is not', null);
.where((eb) =>
eb.exists((qb) =>
qb
.selectFrom('asset_file')
.whereRef('assetId', '=', 'asset.id')
.where('asset_file.type', '=', AssetFileType.Preview),
),
);
}
@GenerateSql({ params: [], stream: true })
@@ -239,23 +284,29 @@ export class AssetJobRepository {
'asset.isOffline',
])
.$call(withExif)
.select(withFacesAndPeople)
.select(withFiles)
.leftJoin('stack', 'stack.id', 'asset.stackId')
.leftJoinLateral(
(eb) =>
eb
.selectFrom('asset as stacked')
.select(['stack.id', 'stack.primaryAssetId'])
.select((eb) => eb.fn<Asset[]>('array_agg', [eb.table('stacked')]).as('assets'))
.where('stacked.deletedAt', 'is not', null)
.where('stacked.visibility', '=', AssetVisibility.Timeline)
.whereRef('stacked.stackId', '=', 'stack.id')
.groupBy('stack.id')
.as('stacked_assets'),
(join) => join.on('stack.id', 'is not', null),
.selectFrom('stack')
.whereRef('stack.id', '=', 'asset.stackId')
.select((eb) => [
'stack.id',
'stack.primaryAssetId',
jsonArrayFrom(
eb
.selectFrom('asset as stack_asset')
.select(['stack_asset.id'])
.whereRef('stack_asset.stackId', '=', 'stack.id')
.whereRef('stack_asset.id', '!=', 'stack.primaryAssetId')
.where('stack_asset.visibility', '=', sql.val(AssetVisibility.Timeline))
.where('stack_asset.status', '!=', sql.val(AssetStatus.Deleted)),
).as('assets'),
])
.as('stack_result'),
(join) => join.onTrue(),
)
.select((eb) => toJson(eb, 'stacked_assets').as('stack'))
.select((eb) => toJson(eb, 'stack_result').as('stack'))
.where('asset.id', '=', id)
.executeTakeFirst();
}
+50 -9
View File
@@ -251,8 +251,6 @@ export class AssetRepository {
duplicatesDetectedAt: eb.ref('excluded.duplicatesDetectedAt'),
facesRecognizedAt: eb.ref('excluded.facesRecognizedAt'),
metadataExtractedAt: eb.ref('excluded.metadataExtractedAt'),
previewAt: eb.ref('excluded.previewAt'),
thumbnailAt: eb.ref('excluded.thumbnailAt'),
ocrAt: eb.ref('excluded.ocrAt'),
},
values[0],
@@ -361,7 +359,6 @@ export class AssetRepository {
.selectFrom('asset')
.selectAll('asset')
.innerJoin('asset_job_status', 'asset.id', 'asset_job_status.assetId')
.where('asset_job_status.previewAt', 'is not', null)
.where(sql`(asset."localDateTime" at time zone 'UTC')::date`, '=', sql`today.date`)
.where('asset.ownerId', '=', anyUuid(ownerIds))
.where('asset.visibility', '=', AssetVisibility.Timeline)
@@ -904,11 +901,12 @@ export class AssetRepository {
.execute();
}
async upsertFile(file: Pick<Insertable<AssetFileTable>, 'assetId' | 'path' | 'type' | 'isEdited'>): Promise<void> {
const value = { ...file, assetId: asUuid(file.assetId) };
async upsertFile(
file: Pick<Insertable<AssetFileTable>, 'assetId' | 'path' | 'type' | 'isEdited' | 'isProgressive'>,
): Promise<void> {
await this.db
.insertInto('asset_file')
.values(value)
.values(file)
.onConflict((oc) =>
oc.columns(['assetId', 'type', 'isEdited']).doUpdateSet((eb) => ({
path: eb.ref('excluded.path'),
@@ -918,19 +916,19 @@ export class AssetRepository {
}
async upsertFiles(
files: Pick<Insertable<AssetFileTable>, 'assetId' | 'path' | 'type' | 'isEdited'>[],
files: Pick<Insertable<AssetFileTable>, 'assetId' | 'path' | 'type' | 'isEdited' | 'isProgressive'>[],
): Promise<void> {
if (files.length === 0) {
return;
}
const values = files.map((row) => ({ ...row, assetId: asUuid(row.assetId) }));
await this.db
.insertInto('asset_file')
.values(values)
.values(files)
.onConflict((oc) =>
oc.columns(['assetId', 'type', 'isEdited']).doUpdateSet((eb) => ({
path: eb.ref('excluded.path'),
isProgressive: eb.ref('excluded.isProgressive'),
})),
)
.execute();
@@ -1009,4 +1007,47 @@ export class AssetRepository {
return count;
}
@GenerateSql({ params: [DummyValue.UUID, true] })
async getForOriginal(id: string, isEdited: boolean) {
return this.db
.selectFrom('asset')
.select('originalFileName')
.where('asset.id', '=', id)
.$if(isEdited, (qb) =>
qb
.leftJoin('asset_file', (join) =>
join
.onRef('asset.id', '=', 'asset_file.assetId')
.on('asset_file.isEdited', '=', true)
.on('asset_file.type', '=', AssetFileType.FullSize),
)
.select('asset_file.path as editedPath'),
)
.select('originalPath')
.executeTakeFirstOrThrow();
}
@GenerateSql({ params: [DummyValue.UUID, AssetFileType.Preview, true] })
async getForThumbnail(id: string, type: AssetFileType, isEdited: boolean) {
return this.db
.selectFrom('asset')
.where('asset.id', '=', id)
.leftJoin('asset_file', (join) =>
join.onRef('asset.id', '=', 'asset_file.assetId').on('asset_file.type', '=', type),
)
.select(['asset.originalPath', 'asset.originalFileName', 'asset_file.path as path'])
.orderBy('asset_file.isEdited', isEdited ? 'desc' : 'asc')
.executeTakeFirstOrThrow();
}
@GenerateSql({ params: [DummyValue.UUID] })
async getForVideo(id: string) {
return this.db
.selectFrom('asset')
.select(['asset.encodedVideoPath', 'asset.originalPath'])
.where('asset.id', '=', id)
.where('asset.type', '=', AssetType.Video)
.executeTakeFirst();
}
}
@@ -176,6 +176,7 @@ export class MediaRepository {
quality: options.quality,
// this is default in libvips (except the threshold is 90), but we need to set it manually in sharp
chromaSubsampling: options.quality >= 80 ? '4:4:4' : '4:2:0',
progressive: options.progressive,
});
await decoded.toFile(output);
@@ -152,7 +152,7 @@ export class StorageRepository {
}
async unlinkDir(folder: string, options: { recursive?: boolean; force?: boolean }) {
await fs.rm(folder, options);
await fs.rm(folder, { ...options, maxRetries: 5, retryDelay: 100 });
}
async removeEmptyDirs(directory: string, self: boolean = false) {
@@ -168,7 +168,13 @@ export class StorageRepository {
if (self) {
const updated = await fs.readdir(directory);
if (updated.length === 0) {
await fs.rmdir(directory);
try {
await fs.rmdir(directory);
} catch (error: Error | any) {
if (error.code !== 'ENOTEMPTY') {
this.logger.warn(`Attempted to remove directory, but failed: ${error}`);
}
}
}
}
}