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(cloud): address portal and gallery review findings
Timothy Yin1692ff41229b
diff --git a/apps/cloud/app/components/CloudUploadDrawer.vue b/apps/cloud/app/components/CloudUploadDrawer.vueindex 76540bae..ec782253 100644--- a/apps/cloud/app/components/CloudUploadDrawer.vue+++ b/apps/cloud/app/components/CloudUploadDrawer.vue@@ -89,7 +89,9 @@ async function dropFiles(event: DragEvent) {><span>Drop images here, or choose images and matching .MOV filestogether.</span- ><span>Up to 100 MB per photograph and paired video.</span>+ ><span+ >Up to 100 MiB per photograph, including its paired video.</span+ ></button><divv-if="uploading"diff --git a/apps/cloud/app/composables/useCloudSiteMedia.ts b/apps/cloud/app/composables/useCloudSiteMedia.tsindex ded98171..5fa77639 100644--- a/apps/cloud/app/composables/useCloudSiteMedia.ts+++ b/apps/cloud/app/composables/useCloudSiteMedia.ts@@ -326,13 +326,26 @@ export function useCloudMediaWorkspace(props: {const input = event.target as HTMLInputElement,files = Array.from(input.files ?? [])if (!files.length || uploading.value || !connectionId.value) return+ const isVideo = (file: File) => file.name.toLowerCase().endsWith('.mov')+ const companionFor = (photo: File) =>+ files.find(+ (file) =>+ isVideo(file) &&+ file.name.replace(/\.[^.]+$/, '').toLowerCase() ===+ photo.name.replace(/\.[^.]+$/, '').toLowerCase(),+ )if (files.some((f) => f.size > 100 * 1024 * 1024) ||- files.every((f) => f.name.toLowerCase().endsWith('.mov'))+ files.some(+ (file) =>+ !isVideo(file) &&+ file.size + (companionFor(file)?.size ?? 0) > 100 * 1024 * 1024,+ ) ||+ files.every(isVideo)) {failed.value = truemessage.value =- 'Choose photographs under 100 MB. A Live Photo MOV must accompany a photograph with the same filename.'+ 'Each photograph and its matching Live Photo MOV must total at most 100 MiB. A MOV must accompany a photograph with the same filename.'input.value = ''return}@@ -344,12 +357,7 @@ export function useCloudMediaWorkspace(props: {for (const file of files.filter((f) => !f.name.toLowerCase().endsWith('.mov'),)) {- const companion = files.find(- (f) =>- f.name.toLowerCase().endsWith('.mov') &&- f.name.replace(/\.[^.]+$/, '').toLowerCase() ===- file.name.replace(/\.[^.]+$/, '').toLowerCase(),- )+ const companion = companionFor(file)currentFile.value = file.nameprogress.value = 0await sendFile(file, companion)diff --git a/apps/cloud/app/composables/useCloudSiteSubscription.ts b/apps/cloud/app/composables/useCloudSiteSubscription.tsindex 76df7d2f..cc05eee9 100644--- a/apps/cloud/app/composables/useCloudSiteSubscription.ts+++ b/apps/cloud/app/composables/useCloudSiteSubscription.ts@@ -47,7 +47,10 @@ export function useCloudSiteSubscription() {stream.onerror = () => {void fetcher<EntrySiteContext>(`/api/sites/${snapshot.siteId}/context`).then(update)- .catch(invalidate)+ .catch((error: { statusCode?: number; status?: number } | null) => {+ const status = error?.statusCode ?? error?.status+ if (status === 401 || status === 403 || status === 404) invalidate()+ })}}watch(() => context.value?.scope, connect, { flush: 'sync' })diff --git a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts b/apps/cloud/server/api/sites/[siteId]/media/[...operation].tsindex 06c50b98..7dec9288 100644--- a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts+++ b/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts@@ -486,9 +486,9 @@ export default definePlatformHandler(async (event) => {.bind(siteId, albumId, ID(body.photoId)),raw.prepare(- 'UPDATE cloud_albums SET revision=revision+1,updated_at=? WHERE site_id=? AND id=?',+ 'UPDATE cloud_albums SET cover_photo_id=CASE WHEN cover_photo_id=? THEN NULL ELSE cover_photo_id END,revision=revision+1,updated_at=? WHERE site_id=? AND id=?',)- .bind(now, siteId, albumId),+ .bind(ID(body.photoId), now, siteId, albumId),])} else if (action === 'delete') {await raw.batch([diff --git a/apps/site/app/middleware/site.global.ts b/apps/site/app/middleware/site.global.tsindex 4e6dbcfc..714f1191 100644--- a/apps/site/app/middleware/site.global.ts+++ b/apps/site/app/middleware/site.global.ts@@ -19,7 +19,7 @@ export default defineNuxtRouteMiddleware(async (to) => {return navigateTo('https://app.chronoframe.art/signin', { external: true })if (!['/photos', '/globe'].includes(to.path) &&- !/^\/[a-z0-9_-]{1,128}$/.test(to.path) &&+ !/^\/[a-zA-Z0-9_-]{1,128}$/.test(to.path) &&to.path !== '/' &&to.path !== '/albums' &&!/^\/albums\/[1-9][0-9]*$/.test(to.path)diff --git a/packages/gallery/app/composables/usePhotoSort.ts b/packages/gallery/app/composables/usePhotoSort.tsindex eda3a14d..4557a9e4 100644--- a/packages/gallery/app/composables/usePhotoSort.ts+++ b/packages/gallery/app/composables/usePhotoSort.ts@@ -7,7 +7,7 @@ interface SortOption {}// 全局排序状态-const sortOptions: SortOption[] = [+const sortOptions: readonly SortOption[] = [{key: 'dateTaken-desc',labelI18n: 'ui.action.sort.options.dateTakenDesc',@@ -70,6 +70,14 @@ const sortOptions: SortOption[] = [},]+const shuffleOption: SortOption = {+ key: 'shuffle',+ labelI18n: 'ui.action.sort.options.shuffle',+ icon: 'tabler:dice-3',+ value: () => Math.random(),+ order: 'asc',+}+export function usePhotoSort() {const { photos } = usePhotos()const currentSort = useState<string>(@@ -77,10 +85,16 @@ export function usePhotoSort() {() => 'dateTaken-desc',)+ const availableSorts = computed(() =>+ currentSort.value === 'shuffle'+ ? [...sortOptions, shuffleOption]+ : sortOptions,+ )+// 当前排序选项const currentSortOption = computed(() => {return (- sortOptions.find((sort) => sort.key === currentSort.value) ||+ availableSorts.value.find((sort) => sort.key === currentSort.value) ||sortOptions[0])})@@ -122,7 +136,7 @@ export function usePhotoSort() {// 设置排序方式const setSortOption = (sortKey: string) => {- if (sortOptions.some((sort) => sort.key === sortKey)) {+ if (availableSorts.value.some((sort) => sort.key === sortKey)) {currentSort.value = sortKey}}@@ -137,9 +151,6 @@ export function usePhotoSort() {}}- // 获取可用的排序选项- const availableSorts = computed(() => sortOptions)-// 获取当前排序的显示标签const currentSortLabel = computed(() =>@@ -166,20 +177,6 @@ export function usePhotoSort() {const shufflePhotos = () => {// 创建一个特殊的排序方式用于打乱currentSort.value = 'shuffle'-- // 更新可用排序中的 shuffle 选项- const shuffleIndex = sortOptions.findIndex((sort) => sort.key === 'shuffle')-- if (shuffleIndex === -1) {- // 如果没有 shuffle 排序选项,则添加它- sortOptions.push({- key: 'shuffle',- labelI18n: 'ui.action.sort.options.shuffle',- icon: 'tabler:dice-3',- value: () => Math.random(),- order: 'asc',- })- }}return {diff --git a/tests/portal-review-regressions.test.ts b/tests/portal-review-regressions.test.tsnew file mode 100644index 00000000..92b79609--- /dev/null+++ b/tests/portal-review-regressions.test.ts@@ -0,0 +1,222 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import vm from 'node:vm'+import ts from 'typescript'+import { ref, reactive, computed, readonly, watch, effectScope } from 'vue'++function load(+ file: string,+ globals: Record<string, unknown>,+ imports: Record<string, unknown> = {},+) {+ const exports: Record<string, any> = {}+ const code = ts.transpileModule(readFileSync(file, 'utf8'), {+ compilerOptions: { module: ts.ModuleKind.CommonJS },+ }).outputText+ vm.runInNewContext(code, {+ exports,+ ref,+ reactive,+ computed,+ readonly,+ watch,+ ...globals,+ require: (name: string) => {+ assert.ok(name in imports, name)+ return imports[name]+ },+ })+ return exports+}++test('Live Photo validation rejects the combined size before reserving any upload, but accepts the exact boundary', async () => {+ const requests: { path: string; body?: any }[] = []+ const storage = new Map<string, string>()+ const module = load(+ 'apps/cloud/app/composables/useCloudSiteMedia.ts',+ {+ useEntryContext: () => ({ value: { scope: 'site:1:user:1', siteId: 1 } }),+ onMounted: () => {},+ onBeforeUnmount: () => {},+ AbortController,+ crypto,+ setTimeout,+ setInterval,+ clearInterval,+ localStorage: {+ getItem: (k: string) => storage.get(k),+ setItem: (k: string, v: string) => storage.set(k, v),+ removeItem: (k: string) => storage.delete(k),+ },+ $fetch: async (path: string, options?: { body?: unknown }) => {+ requests.push({ path, body: options?.body })+ if (path.endsWith('/plan')) return { state: 'completed' }+ if (path.endsWith('/storage')) return { connections: [] }+ if (path.endsWith('/photos')) return { photos: [], jobs: [] }+ if (path.endsWith('/albums')) return { albums: [] }+ if (path.endsWith('/usage'))+ return { usage: { photos: 0, pending: 0, bytes: 0 } }+ return {}+ },+ },+ {+ '@chronoframe/contracts/storage-diagnostics': {+ STORAGE_CONNECTION_MESSAGES: {},+ },+ },+ )+ const media = module.useCloudMediaWorkspace({ siteId: 1, role: 'admin' })+ media.connectionId.value = 'storage'+ const mib = 1024 * 1024+ for (const files of [+ [+ { name: 'IMG.HEIC', size: 60 * mib },+ { name: 'img.MOV', size: 50 * mib },+ ],+ [{ name: 'single.jpg', size: 100 * mib + 1 }],+ [{ name: 'only.MOV', size: mib }],+ ]) {+ const input = { files, value: 'chosen' }+ await media.upload({ target: input })+ assert.equal(media.failed.value, true)+ assert.match(media.message.value, /100 MiB/)+ assert.equal(input.value, '')+ assert.equal(requests.length, 0)+ }+ await media.upload({+ target: {+ files: [+ { name: 'IMG.HEIC', size: 60 * mib },+ { name: 'img.MOV', size: 40 * mib },+ ],+ value: 'chosen',+ },+ })+ assert.equal(media.failed.value, false)+ const reservation = requests.find((r) => r.path.endsWith('/uploads'))!+ assert.equal(reservation.body.bytes, 60 * mib)+ assert.equal(reservation.body.liveVideo.bytes, 40 * mib)+ assert.match(media.message.value, /Upload verified/)+})++test('subscription retains edits through network/503 failures and invalidates only authoritative denials', async () => {+ for (const failure of [+ new Error('offline'),+ { statusCode: 503 },+ { status: 500 },+ { statusCode: 401 },+ { status: 403 },+ { statusCode: 404 },+ ]) {+ const scope = effectScope(),+ context = ref<any>({+ scope: 'site:1:admin',+ siteId: 1,+ audience: 'portal',+ capabilities: { subscriptions: true },+ }),+ streams: any[] = [],+ navigation: string[] = []+ let mount = () => {},+ unmount = () => {}+ class Stream {+ closed = false+ onerror?: () => void+ constructor() {+ streams.push(this)+ }+ close() {+ this.closed = true+ }+ addEventListener() {}+ }+ const module = load(+ 'apps/cloud/app/composables/useCloudSiteSubscription.ts',+ {+ useEntryContext: () => context,+ useRequestFetch: () => async () => {+ throw failure+ },+ EventSource: Stream,+ onMounted: (fn: () => void) => {+ mount = fn+ },+ onBeforeUnmount: (fn: () => void) => {+ unmount = fn+ },+ navigateTo: (path: string) => {+ navigation.push(path)+ },+ },+ )+ scope.run(() => module.useCloudSiteSubscription())+ mount()+ streams[0].onerror()+ await new Promise((resolve) => setImmediate(resolve))+ const denied = [401, 403, 404].includes(+ (failure as any).statusCode ?? (failure as any).status,+ )+ assert.equal(context.value === null, denied)+ assert.deepEqual(navigation, denied ? ['/sites'] : [])+ unmount()+ scope.stop()+ }+})++test('shuffle options react to the scoped selection without mutating another entry or SSR request', () => {+ let entry = { scope: 'site:one' }+ const states = new Map<string, any>()+ const module = load('packages/gallery/app/composables/usePhotoSort.ts', {+ usePhotos: () => ({ photos: ref([{ id: 'one', title: 'One' }]) }),+ useEntryContext: () => ({ value: entry }),+ useState: (key: string, init: () => unknown) => {+ if (!states.has(key)) states.set(key, ref(init()))+ return states.get(key)+ },+ })+ const first = module.usePhotoSort()+ assert.equal(+ first.availableSorts.value.some((v: any) => v.key === 'shuffle'),+ false,+ )+ first.shufflePhotos()+ assert.equal(first.currentSortOption.value.key, 'shuffle')+ assert.equal(+ first.availableSorts.value.some((v: any) => v.key === 'shuffle'),+ true,+ )+ entry = { scope: 'site:two' }+ const second = module.usePhotoSort()+ assert.equal(+ second.availableSorts.value.some((v: any) => v.key === 'shuffle'),+ false,+ )+ first.setSortOption('title-asc')+ assert.equal(+ first.availableSorts.value.some((v: any) => v.key === 'shuffle'),+ false,+ )+ assert.equal(second.currentSortOption.value.key, 'dateTaken-desc')+})++test('public navigation accepts case-preserving photo IDs while rejecting invalid and oversized paths', async () => {+ let context: any = { value: null }+ const module = load('apps/site/app/middleware/site.global.ts', {+ defineNuxtRouteMiddleware: (fn: unknown) => fn,+ useEntryContext: () => context,+ useRequestFetch: () => async () => ({ scope: 'public:one' }),+ navigateTo: () => {},+ abortNavigation: (error: unknown) => error,+ createError: (error: unknown) => error,+ })+ for (const path of ['/IMG_1234', '/Mixed-Case_1', '/photos', '/albums/1'])+ assert.equal(await module.default({ path }), undefined, path)+ for (const path of [+ '/bad!',+ '/' + 'A'.repeat(129),+ '/nested/path',+ '/dashboard',+ ])+ assert.equal((await module.default({ path })).statusCode, 404, path)+})