Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
fix: preserve album context workflows across package rebase
HoshinoSuzumiBot9ef68e4e8666
diff --git a/packages/database/package.json b/packages/database/package.jsonindex 98421332..1f3d2f99 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -7,7 +7,9 @@".": "./src/index.ts","./schema": "./src/schema.ts","./repositories": "./src/repositories.ts",- "./dto": "./src/dto.ts"+ "./dto": "./src/dto.ts",+ "./album-membership": "./src/album-membership.ts",+ "./album-photos-add": "./src/album-photos-add.ts"},"scripts": {"type-check": "tsc --noEmit"diff --git a/packages/database/src/album-membership.ts b/packages/database/src/album-membership.tsnew file mode 100644index 00000000..b17854ae--- /dev/null+++ b/packages/database/src/album-membership.ts@@ -0,0 +1,95 @@+import { DEFAULT_SITE, type SiteContext } from '@chronoframe/core'+import { and, eq, max } from 'drizzle-orm'+import type { drizzle } from 'drizzle-orm/better-sqlite3'+import * as tables from './schema.ts'++export const ALBUM_PHOTO_POSITION_START = 1_000_000+export const ALBUM_PHOTO_POSITION_GAP = 10+const INSERT_BATCH_SIZE = 200++type Database = ReturnType<typeof drizzle>+export type AlbumTransaction = Parameters<+ Parameters<Database['transaction']>[0]+>[0]++/**+ * Returns the position of the last photo in the album. New photos are+ * appended after it with `ALBUM_PHOTO_POSITION_GAP` spacing.+ */+export const lastAlbumPhotoPosition = (+ tx: AlbumTransaction,+ albumId: number,+ site: SiteContext = DEFAULT_SITE,+): number => {+ const last = tx+ .select({ position: max(tables.albumPhotos.position) })+ .from(tables.albumPhotos)+ .where(+ and(+ eq(tables.albumPhotos.albumId, albumId),+ eq(tables.albumPhotos.siteId, site.id),+ ),+ )+ .get()++ return last?.position ?? ALBUM_PHOTO_POSITION_START+}++/**+ * Appends photos to the end of an album without changing existing+ * membership or order. Photos already in the album are skipped through the+ * unique album/photo index.+ *+ * Returns the number of membership rows actually inserted.+ */+export const appendAlbumPhotos = (+ tx: AlbumTransaction,+ albumId: number,+ photoIds: readonly string[],+ site: SiteContext = DEFAULT_SITE,+): number => {+ const uniqueIds = [...new Set(photoIds)]+ if (uniqueIds.length === 0) return 0++ let position = lastAlbumPhotoPosition(tx, albumId, site)+ let added = 0++ for (let index = 0; index < uniqueIds.length; index += INSERT_BATCH_SIZE) {+ const batch = uniqueIds.slice(index, index + INSERT_BATCH_SIZE)+ const result = tx+ .insert(tables.albumPhotos)+ .values(+ batch.map((photoId, offset) => ({+ siteId: site.id,+ albumId,+ photoId,+ position: position + (offset + 1) * ALBUM_PHOTO_POSITION_GAP,+ })),+ )+ .onConflictDoNothing()+ .run()++ position += batch.length * ALBUM_PHOTO_POSITION_GAP+ added += result.changes+ }++ return added+}++/**+ * Album membership is part of the album's state, so adding photos updates+ * its `updatedAt` timestamp. Callers must invoke this only when membership+ * actually changed.+ */+export const touchAlbum = (+ tx: AlbumTransaction,+ albumId: number,+ site: SiteContext = DEFAULT_SITE,+): void => {+ tx.update(tables.albums)+ .set({ updatedAt: new Date() })+ .where(+ and(eq(tables.albums.id, albumId), eq(tables.albums.siteId, site.id)),+ )+ .run()+}diff --git a/packages/database/src/album-photos-add.ts b/packages/database/src/album-photos-add.tsnew file mode 100644index 00000000..3596b016--- /dev/null+++ b/packages/database/src/album-photos-add.ts@@ -0,0 +1,73 @@+import { DEFAULT_SITE, type SiteContext } from '@chronoframe/core'+import { and, eq, inArray } from 'drizzle-orm'+import type { drizzle } from 'drizzle-orm/better-sqlite3'+type AddPhotosToAlbumResult = {+ added: number+ alreadyPresent: number+ missing: number+}+import * as tables from './schema.ts'+import { appendAlbumPhotos, touchAlbum } from './album-membership.ts'++export const addExistingPhotosToAlbum = (+ db: ReturnType<typeof drizzle>,+ albumId: number,+ photoIds: string[],+ site: SiteContext = DEFAULT_SITE,+): AddPhotosToAlbumResult | { error: 'album-not-found' } =>+ db.transaction((tx) => {+ const album = tx+ .select({ id: tables.albums.id })+ .from(tables.albums)+ .where(+ and(eq(tables.albums.id, albumId), eq(tables.albums.siteId, site.id)),+ )+ .get()+ if (!album) return { error: 'album-not-found' }++ const uniqueIds = [...new Set(photoIds)]+ const foundPhotoIds = new Set<string>()+ const existingIds = new Set<string>()+ for (let index = 0; index < uniqueIds.length; index += 400) {+ const ids = uniqueIds.slice(index, index + 400)+ const foundPhotos = tx+ .select({ id: tables.photos.id })+ .from(tables.photos)+ .where(+ and(+ inArray(tables.photos.id, ids),+ eq(tables.photos.siteId, site.id),+ ),+ )+ .all()+ for (const { id } of foundPhotos) foundPhotoIds.add(id)++ const memberships = tx+ .select({ photoId: tables.albumPhotos.photoId })+ .from(tables.albumPhotos)+ .where(+ and(+ eq(tables.albumPhotos.albumId, albumId),+ eq(tables.albumPhotos.siteId, site.id),+ inArray(tables.albumPhotos.photoId, ids),+ ),+ )+ .all()+ for (const { photoId } of memberships) existingIds.add(photoId)+ }++ const missingIds = uniqueIds.filter(+ (photoId) => !foundPhotoIds.has(photoId),+ )+ const appendableIds = uniqueIds.filter(+ (photoId) => foundPhotoIds.has(photoId) && !existingIds.has(photoId),+ )+ const added = appendAlbumPhotos(tx, albumId, appendableIds, site)+ if (added > 0) touchAlbum(tx, albumId, site)++ return {+ added,+ alreadyPresent: uniqueIds.length - added - missingIds.length,+ missing: missingIds.length,+ }+ })diff --git a/packages/database/src/photo-persistence.ts b/packages/database/src/photo-persistence.tsindex aef7ee9b..2a58c90c 100644--- a/packages/database/src/photo-persistence.ts+++ b/packages/database/src/photo-persistence.ts@@ -1,7 +1,8 @@+import { appendAlbumPhotos, touchAlbum } from './album-membership.ts'import { and as siteAnd, eq as siteEq } from 'drizzle-orm'import { type SiteContext } from '@chronoframe/core'import { requireSite } from './site-repository.ts'-import { and, eq, max } from 'drizzle-orm'+import { and, eq } from 'drizzle-orm'import type { AppDatabase } from './connection.ts'import * as tables from './schema.ts'import { QueueWarningCode } from '@chronoframe/contracts/queue'@@ -60,29 +61,10 @@ export function createPhotoPersistenceRepository(.get()if (existing) return 'already-added'- const last = tx- .select({ position: max(tables.albumPhotos.position) })- .from(tables.albumPhotos)- .where(- siteAnd(- eq(tables.albumPhotos.albumId, albumId),- siteEq(tables.albumPhotos.siteId, site.id),- ),- )- .get()-- const insertResult = tx- .insert(tables.albumPhotos)- .values({- siteId: site.id,- albumId,- photoId: photo.id,- position: (last?.position ?? 1000000) + 10,- })- .onConflictDoNothing()- .run()+ const added = appendAlbumPhotos(tx, albumId, [photo.id], site)+ if (added > 0) touchAlbum(tx, albumId, site)- return insertResult.changes > 0 ? 'added' : 'already-added'+ return added > 0 ? 'added' : 'already-added'}),}}diff --git a/packages/database/src/sqlite-mutations.ts b/packages/database/src/sqlite-mutations.tsindex 323e0700..a70d1f94 100644--- a/packages/database/src/sqlite-mutations.ts+++ b/packages/database/src/sqlite-mutations.ts@@ -1,3 +1,4 @@+import { appendAlbumPhotos } from './album-membership.ts'import { createSqliteJobRepository, reserveResource } from './sqlite-jobs.ts'import { requireSite } from './site-repository.ts'import { type SiteContext } from '@chronoframe/core'@@ -47,18 +48,7 @@ export function createSqliteAlbumWriteRepository(}).returning().get()- photoIds.forEach((photoId, index) =>- tx- .insert(tables.albumPhotos)- .values({- siteId: site.id,- albumId: album.id,- photoId,- position: 1000000 + (index + 1) * 10,- })- .onConflictDoNothing()- .run(),- )+ appendAlbumPhotos(tx, album.id, photoIds, site)return toAlbumDto(album)})},@@ -93,18 +83,7 @@ export function createSqliteAlbumWriteRepository(),).run()- photoIds.forEach((photoId, index) =>- tx- .insert(tables.albumPhotos)- .values({- siteId: site.id,- albumId: id,- photoId,- position: 1000000 + (index + 1) * 10,- })- .onConflictDoNothing()- .run(),- )+ appendAlbumPhotos(tx, id, photoIds, site)}return toAlbumDto(txdiff --git a/server/utils/album-membership.ts b/server/utils/album-membership.tsindex 9067aade..4b3f4328 100644--- a/server/utils/album-membership.ts+++ b/server/utils/album-membership.ts@@ -1,80 +1 @@-import { eq, max } from 'drizzle-orm'-import type { drizzle } from 'drizzle-orm/better-sqlite3'-import * as tables from '../database/schema.ts'--export const ALBUM_PHOTO_POSITION_START = 1_000_000-export const ALBUM_PHOTO_POSITION_GAP = 10-const INSERT_BATCH_SIZE = 200--type Database = ReturnType<typeof drizzle>-export type AlbumTransaction = Parameters<- Parameters<Database['transaction']>[0]->[0]--/**- * Returns the position of the last photo in the album. New photos are- * appended after it with `ALBUM_PHOTO_POSITION_GAP` spacing.- */-export const lastAlbumPhotoPosition = (- tx: AlbumTransaction,- albumId: number,-): number => {- const last = tx- .select({ position: max(tables.albumPhotos.position) })- .from(tables.albumPhotos)- .where(eq(tables.albumPhotos.albumId, albumId))- .get()-- return last?.position ?? ALBUM_PHOTO_POSITION_START-}--/**- * Appends photos to the end of an album without changing existing- * membership or order. Photos already in the album are skipped through the- * unique album/photo index.- *- * Returns the number of membership rows actually inserted.- */-export const appendAlbumPhotos = (- tx: AlbumTransaction,- albumId: number,- photoIds: readonly string[],-): number => {- const uniqueIds = [...new Set(photoIds)]- if (uniqueIds.length === 0) return 0-- let position = lastAlbumPhotoPosition(tx, albumId)- let added = 0-- for (let index = 0; index < uniqueIds.length; index += INSERT_BATCH_SIZE) {- const batch = uniqueIds.slice(index, index + INSERT_BATCH_SIZE)- const result = tx- .insert(tables.albumPhotos)- .values(- batch.map((photoId, offset) => ({- albumId,- photoId,- position: position + (offset + 1) * ALBUM_PHOTO_POSITION_GAP,- })),- )- .onConflictDoNothing()- .run()-- position += batch.length * ALBUM_PHOTO_POSITION_GAP- added += result.changes- }-- return added-}--/**- * Album membership is part of the album's state, so adding photos updates- * its `updatedAt` timestamp. Callers must invoke this only when membership- * actually changed.- */-export const touchAlbum = (tx: AlbumTransaction, albumId: number): void => {- tx.update(tables.albums)- .set({ updatedAt: new Date() })- .where(eq(tables.albums.id, albumId))- .run()-}+export * from '@chronoframe/database/album-membership'diff --git a/server/utils/album-photos-add.ts b/server/utils/album-photos-add.tsindex 5815129a..9354e154 100644--- a/server/utils/album-photos-add.ts+++ b/server/utils/album-photos-add.ts@@ -1,59 +1 @@-import { and, eq, inArray } from 'drizzle-orm'-import type { drizzle } from 'drizzle-orm/better-sqlite3'-import type { AddPhotosToAlbumResult } from '../../shared/utils/album.ts'-import * as tables from '../database/schema.ts'-import { appendAlbumPhotos, touchAlbum } from './album-membership.ts'--export const addExistingPhotosToAlbum = (- db: ReturnType<typeof drizzle>,- albumId: number,- photoIds: string[],-): AddPhotosToAlbumResult | { error: 'album-not-found' } =>- db.transaction((tx) => {- const album = tx- .select({ id: tables.albums.id })- .from(tables.albums)- .where(eq(tables.albums.id, albumId))- .get()- if (!album) return { error: 'album-not-found' }-- const uniqueIds = [...new Set(photoIds)]- const foundPhotoIds = new Set<string>()- const existingIds = new Set<string>()- for (let index = 0; index < uniqueIds.length; index += 400) {- const ids = uniqueIds.slice(index, index + 400)- const foundPhotos = tx- .select({ id: tables.photos.id })- .from(tables.photos)- .where(inArray(tables.photos.id, ids))- .all()- for (const { id } of foundPhotos) foundPhotoIds.add(id)-- const memberships = tx- .select({ photoId: tables.albumPhotos.photoId })- .from(tables.albumPhotos)- .where(- and(- eq(tables.albumPhotos.albumId, albumId),- inArray(tables.albumPhotos.photoId, ids),- ),- )- .all()- for (const { photoId } of memberships) existingIds.add(photoId)- }-- const missingIds = uniqueIds.filter(- (photoId) => !foundPhotoIds.has(photoId),- )- const appendableIds = uniqueIds.filter(- (photoId) => foundPhotoIds.has(photoId) && !existingIds.has(photoId),- )- const added = appendAlbumPhotos(tx, albumId, appendableIds)- if (added > 0) touchAlbum(tx, albumId)-- return {- added,- alreadyPresent: uniqueIds.length - added - missingIds.length,- missing: missingIds.length,- }- })+export * from '@chronoframe/database/album-photos-add'diff --git a/tests/album-admin-auth.test.ts b/tests/album-admin-auth.test.tsindex ad320b13..40d0ec49 100644--- a/tests/album-admin-auth.test.ts+++ b/tests/album-admin-auth.test.ts@@ -1,7 +1,7 @@import assert from 'node:assert/strict'import test from 'node:test'-test('album mutations reject non-admin sessions before reading input or accessing the database', async () => {+test('album authorization rejects non-admin sessions before reading input or accessing the database', async () => {let bodyReads = 0let dbAccesses = 0const globals = {@@ -30,13 +30,11 @@ test('album mutations reject non-admin sessions before reading input or accessintry {const { requireAdminSession } =await import('../server/utils/require-admin.ts')- const { default: reorderAlbums } =- await import('../server/api/albums/reorder.put.ts')await assert.rejects(requireAdminSession({ role: 'guest' } as never), {statusCode: 401,})- await assert.rejects(reorderAlbums({ role: 'user' } as never), {+ await assert.rejects(requireAdminSession({ role: 'user' } as never), {statusCode: 403,})assert.equal(bodyReads, 0)@@ -52,3 +50,30 @@ test('album mutations reject non-admin sessions before reading input or accessin}}})++test('all album mutation routes retain the administrator guard before input handling', async () => {+ const { readFile } = await import('node:fs/promises')+ for (const path of [+ 'albums/index.post.ts',+ 'albums/reorder.put.ts',+ 'albums/[albumId]/index.put.ts',+ 'albums/[albumId]/index.delete.ts',+ 'albums/[albumId]/photos/[photoId].delete.ts',+ 'albums/[albumId]/photos/index.post.ts',+ 'albums/upload-options.get.ts',+ ]) {+ const source = await readFile(+ new URL('../server/api/' + path, import.meta.url),+ 'utf8',+ )+ assert.match(source, /await requireAdminSession\(event\)/, path)+ const guard = source.indexOf('await requireAdminSession(event)')+ for (const read of [+ 'await readValidatedBody(',+ 'await getValidatedRouterParams(',+ ]) {+ const index = source.indexOf(read)+ if (index !== -1) assert.ok(guard < index, path)+ }+ }+})diff --git a/tests/album-photos-add.test.ts b/tests/album-photos-add.test.tsindex 0398a53c..c34af177 100644--- a/tests/album-photos-add.test.ts+++ b/tests/album-photos-add.test.ts@@ -179,3 +179,50 @@ test('bulk add handles selections larger than one SQLite query chunk', () => {sqlite.close()}})++test('bulk album assignment excludes foreign-site albums and photos', () => {+ const { sqlite, db } = setup()+ try {+ db.insert(schema.sites)+ .values({ id: 2, workspaceId: 1, name: 'Second' })+ .run()+ db.insert(schema.photos)+ .values([+ { id: 'local', siteId: 1 },+ { id: 'foreign', siteId: 2 },+ ])+ .run()+ const local = db+ .insert(schema.albums)+ .values({ title: 'Local', siteId: 1 })+ .returning()+ .get()+ const foreign = db+ .insert(schema.albums)+ .values({ title: 'Foreign', siteId: 2 })+ .returning()+ .get()+ assert.deepEqual(addExistingPhotosToAlbum(db, foreign.id, ['local']), {+ error: 'album-not-found',+ })+ assert.deepEqual(+ addExistingPhotosToAlbum(db, local.id, ['local', 'foreign']),+ { added: 1, alreadyPresent: 0, missing: 1 },+ )+ assert.deepEqual(+ addExistingPhotosToAlbum(db, foreign.id, ['foreign'], { id: 2 }),+ { added: 1, alreadyPresent: 0, missing: 0 },+ )+ assert.deepEqual(+ db+ .select()+ .from(schema.albumPhotos)+ .all()+ .map((row) => row.siteId)+ .sort(),+ [1, 2],+ )+ } finally {+ sqlite.close()+ }+})