diff --git a/components/ClipFrameThumbs.vue b/components/ClipFrameThumbs.vue index 53a7194..7e09b54 100644 --- a/components/ClipFrameThumbs.vue +++ b/components/ClipFrameThumbs.vue @@ -135,16 +135,16 @@ const visibleSlots = computed(() => { }) function frameThumb(key: SlotKey) { - if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}?thumb=1` - if (key === 'from' && props.fromClipId) return `/api/library/clips/${props.fromClipId}/last-frame?thumb=1&v=parent` - if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?thumb=1&v=join` + if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}?thumb=1&v=0` + if (key === 'from' && props.fromClipId) return `/api/library/clips/${props.fromClipId}/last-frame?thumb=1&v=parent&e=0` + if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?thumb=1&v=join&e=0` return '' } function frameFull(key: SlotKey) { - if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}` - if (key === 'from' && props.fromClipId) return `/api/library/clips/${props.fromClipId}/last-frame?v=parent` - if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?v=join` + if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}?v=0` + if (key === 'from' && props.fromClipId) return `/api/library/clips/${props.fromClipId}/last-frame?v=parent&e=0` + if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?v=join&e=0` return '' } diff --git a/components/ImagePickerModal.vue b/components/ImagePickerModal.vue index 4c0b4e4..86f4ffc 100644 --- a/components/ImagePickerModal.vue +++ b/components/ImagePickerModal.vue @@ -95,7 +95,7 @@ >
job.value ? queuedJobShots(currentPayload(), job.va const thumbUrl = computed(() => { const stillId = job.value?.payload?.stillId if (!stillId || job.value?.payload?.hideThumbnail || job.value?.payload?.folderLocked) return '' - return `/api/library/stills/${stillId}` + return `/api/library/stills/${stillId}?v=0` }) const loraLine = computed(() => loraStackLabel(draft.loraStack, loraAliases.value)) const loraEngine = computed(() => { diff --git a/components/studio2/AssetSlot.vue b/components/studio2/AssetSlot.vue index e156616..5859fff 100644 --- a/components/studio2/AssetSlot.vue +++ b/components/studio2/AssetSlot.vue @@ -44,17 +44,19 @@
diff --git a/components/studio2/Bench.vue b/components/studio2/Bench.vue index 6f8d529..061b1ca 100644 --- a/components/studio2/Bench.vue +++ b/components/studio2/Bench.vue @@ -96,6 +96,7 @@ v-for="(card, index) in form.photos" :key="'photo-'+index+'-'+card.stillId" :asset="stillById(card.stillId)" + :version="library.catalogEpoch || 0" :hidden="hideInputs" :role="card.role" :role-options="photoRoleOptions" @@ -316,7 +317,7 @@ v-show="!isHidden(selected)" ref="viewerVideo" :key="selected.id" - :src="`/api/library/clips/${selected.id}/video`" + :src="clipVideoUrl(selected.id)" :muted="viewerMuted" @timeupdate="onVideoTime" @loadedmetadata="onVideoTime" @@ -476,7 +477,7 @@
@@ -491,7 +492,7 @@ import {createLoraMemory,loraUse} from '~/shared/studio2/lora-memory.mjs' import {filterLorasForStudio,filterLorasForUse} from '~/utils/loras' import {sectionsFrom} from '~/shared/studio2/contracts.mjs' import {aspectOptions,resolveSize,bindClip,restoreAll,useAsSource,hydrateStudio2Job} from '~/shared/studio2/input.mjs' -import {folderAssets,newestOutput,assetLabel,reconcileSelection,previewHidden,folderImageCount,libraryAfterWipe} from '~/shared/studio2/viewer.mjs' +import {folderAssets,newestOutput,assetLabel,reconcileSelection,previewHidden,folderImageCount,libraryAfterWipe,libraryMediaUrl} from '~/shared/studio2/viewer.mjs' import {queueJobs,queueEngineLabel,jobStageLabel,jobProgressView,elapsedSeconds} from '~/shared/studio2/queue-view.mjs' import {gpuStatus} from '~/shared/studio2/status.mjs' import {CAPTION_STYLES} from '~/shared/caption.mjs' @@ -921,9 +922,12 @@ watch(()=>form.folderId,(id,prev)=>{ watch(()=>form.identityStillId,id=>{if(import.meta.client&&form.folderId&&form.engine!=='qwen21')localStorage.setItem(`studio2-hero:${form.folderId}`,id)}) const stills=computed(()=>library.value.stills.filter((s:any)=>s.folderId===form.folderId)) const clips=computed(()=>library.value.clips.filter((s:any)=>s.folderId===form.folderId)) -const stillUrl=(id:string)=>`/api/library/stills/${id}` -const stillThumbUrl=(id:string)=>`/api/library/stills/${id}/thumb` -const stillPreviewUrl=(id:string)=>`/api/library/stills/${id}/preview` +const mediaVersion=()=>library.value.catalogEpoch ?? 0 +const stillUrl=(id:string)=>libraryMediaUrl(`/api/library/stills/${id}`,mediaVersion()) +const stillThumbUrl=(id:string)=>libraryMediaUrl(`/api/library/stills/${id}/thumb`,mediaVersion()) +const stillPreviewUrl=(id:string)=>libraryMediaUrl(`/api/library/stills/${id}/preview`,mediaVersion()) +const clipThumbUrl=(id:string)=>libraryMediaUrl(`/api/library/clips/${id}/thumb`,mediaVersion()) +const clipVideoUrl=(id:string)=>libraryMediaUrl(`/api/library/clips/${id}/video`,mediaVersion()) /** Stage uses /preview (1600px). Tiles keep /thumb. Never auto-upgrade to the archive master. */ const stagePreviewNonce=ref(0) const stagePreviewRetries=ref(0) @@ -931,7 +935,7 @@ const stagePreviewSrc=computed(()=>{ const id=selected.value?.id if(!id || selected.value?.kind==='clip' || selected.value?.kind==='track') return '' const base=stillPreviewUrl(id) - return stagePreviewNonce.value?`${base}?t=${stagePreviewNonce.value}`:base + return stagePreviewNonce.value?`${base}&t=${stagePreviewNonce.value}`:base }) function onStagePreviewError(){ if(!selected.value?.id || stagePreviewRetries.value>=8) return @@ -982,10 +986,7 @@ const showSelectedStill=computed(()=>{ const item=selected.value if(!item?.id || item.kind==='clip' || item.kind==='track') return false if(forgottenStillIds.value.has(item.id)) return false - if((library.value.stills||[]).some((s:any)=>s.id===item.id)) return true - const folder=(library.value.folders||[]).find((f:any)=>f.id===(item.folderId||form.folderId)) - if(folder && typeof folder.imageCount==='number' && folder.imageCount===0) return false - return true + return (library.value.stills||[]).some((s:any)=>s.id===item.id) }) const sourceAsset=computed(()=>form.startClipId?clips.value.find((c:any)=>c.id===form.startClipId):stills.value.find((s:any)=>s.id===(form.imageAId||form.identityStillId||form.photos?.[0]?.stillId))) const sourceSize=computed(()=>measured[sourceAsset.value?.id] || sourceAsset.value) @@ -1133,6 +1134,30 @@ function clearFormSlots(ids:string[]){ selectionPinned.value=false } } +function clearRefsMissingFromLibrary(){ + const ids=new Set((library.value.stills||[]).map((s:any)=>s.id)) + const clipIds=new Set((library.value.clips||[]).map((c:any)=>c.id)) + const trackIds=new Set((library.value.tracks||[]).map((t:any)=>t.id)) + const missing=[ + form.imageAId,form.imageBId,form.identityStillId,form.maskId,form.endStillId, + ...(form.photos||[]).map((p:any)=>p?.stillId), + ...(form.guides||[]).map((g:any)=>g?.stillId) + ].filter((id:string)=>id&&!ids.has(id)) + clearFormSlots(missing) + if(form.startClipId&&!clipIds.has(form.startClipId))form.startClipId='' + if(form.identityStillId&&!ids.has(form.identityStillId)){ + form.identityStillId='' + try{localStorage.removeItem(`studio2-hero:${form.folderId}`)}catch{/* ignore */} + } + const sel=selected.value + if(sel?.id){ + const ok=sel.kind==='clip'?clipIds.has(sel.id):sel.kind==='track'?trackIds.has(sel.id):ids.has(sel.id) + if(!ok){ + selected.value=null + selectionPinned.value=false + } + } +} /** Photos array is source of truth — never resurrect cards from leftover imageAId. */ function syncPhotosBindings(){ const filled=(form.photos||[]).filter((p:any)=>p?.stillId) @@ -1495,6 +1520,7 @@ async function deleteOutput(explicit?:any){ return } } + seenOutputs.add(id) forgottenStillIds.value=new Set([...forgottenStillIds.value,id]) clearFormSlots([id]) library.value={ @@ -1503,9 +1529,13 @@ async function deleteOutput(explicit?:any){ clips:(library.value.clips||[]).filter((c:any)=>c.id!==id), tracks:(library.value.tracks||[]).filter((t:any)=>t.id!==id) } - if(selected.value?.id===id)selected.value=null + if(selected.value?.id===id){ + selected.value=null + selectionPinned.value=false + } libraryRefreshKey.value+=1 - try{await loadLibraryOnce()}catch{/* catalog write already landed */} + try{await loadLibraryOnce([id])}catch{/* local rows already dropped */ } + forgottenStillIds.value=new Set() await refreshJobs() } function stepFamily(delta:number){ @@ -1549,19 +1579,24 @@ function onLibraryDelete(item:any){ } function onLibraryWiped(result:any){ const folderId=String(result?.folderId||form.folderId||'') + const deleted=[ + ...(result?.deletedIds||[]), + ...(library.value.stills||[]).filter((s:any)=>String(s.folderId||'')===folderId).map((s:any)=>s.id), + ...(library.value.clips||[]).filter((s:any)=>String(s.folderId||'')===folderId).map((s:any)=>s.id), + ...(library.value.tracks||[]).filter((s:any)=>String(s.folderId||'')===folderId).map((s:any)=>s.id) + ] + for(const id of deleted) seenOutputs.add(id) const next=libraryAfterWipe({ folders:library.value.folders, stills:library.value.stills, clips:library.value.clips, tracks:library.value.tracks, - suppressedIds:[...forgottenStillIds.value] + suppressedIds:[] }, result, folderId) - forgottenStillIds.value=new Set(next.suppressedIds) - clearFormSlots(next.suppressedIds) - if(selected.value && (forgottenStillIds.value.has(selected.value.id) || String(selected.value.folderId||'')===folderId)){ - selected.value=null - selectionPinned.value=false - } + forgottenStillIds.value=new Set(deleted) + clearFormSlots(deleted) + selected.value=null + selectionPinned.value=false library.value={ ...library.value, folders:next.folders, @@ -1571,10 +1606,12 @@ function onLibraryWiped(result:any){ drafts:result?.drafts||[], loraAliases:result?.loraAliases||library.value.loraAliases||{}, loraTriggers:result?.loraTriggers||library.value.loraTriggers||{}, - keepPrompts:result?.keepPrompts||library.value.keepPrompts + keepPrompts:result?.keepPrompts||library.value.keepPrompts, + catalogEpoch:result?.catalogEpoch??library.value.catalogEpoch??0 } + clearRefsMissingFromLibrary() libraryRefreshKey.value+=1 - void loadLibraryOnce() + void loadLibraryOnce(deleted).finally(()=>{forgottenStillIds.value=new Set()}) } function onStageHotkey(e:KeyboardEvent){ if(e.metaKey||e.ctrlKey||e.altKey)return @@ -1714,7 +1751,7 @@ watch(()=>sourceAsset.value?.id,id=>{ media.addEventListener('loadedmetadata',()=>{ measured[asset.id]={width:media.videoWidth,height:media.videoHeight} },{once:true}) - media.src=`/api/library/clips/${asset.id}/video` + media.src=clipVideoUrl(asset.id) } }) watch(()=>selected.value?.id,()=>{videoTime.value=0;videoDuration.value=0}) @@ -2013,50 +2050,51 @@ async function cancel(job:any){ } let libraryLoadGen=0 -async function loadLibraryOnce(){ +async function loadLibraryOnce(deletedIds?: string[]){ // Current folder page only — never the yearly Inbox JSON on / + // After delete/wipe, replace from this response. Do not merge the pre-delete list. + const replacing=Array.isArray(deletedIds) + const gone=new Set(deletedIds||[]) const gen=++libraryLoadGen const qs=new URLSearchParams({limit:'50'}) if(form.folderId) qs.set('folderId',form.folderId) qs.set('_',String(Date.now())) const page=await $fetch(`/api/library?${qs.toString()}`) if(gen!==libraryLoadGen) return - const pageStills=page.stills||[] + const pageStills=(page.stills||[]).filter((s:any)=>s?.id&&!gone.has(s.id)) const forget=forgottenStillIds.value const keepIds=[ ...(form.photos||[]).map((p:any)=>p?.stillId).filter(Boolean), form.imageAId,form.imageBId,form.identityStillId,form.maskId,form.endStillId, ...(form.guides||[]).map((g:any)=>g?.stillId).filter(Boolean) - ].filter((id:string)=>id&&!forget.has(id)) as string[] - let kept=(library.value.stills||[]).filter((s:any)=>keepIds.includes(s.id)&&!pageStills.some((p:any)=>p.id===s.id)&&!forget.has(s.id)) - const stillMissing=keepIds.filter(id=>!forget.has(id)&&!pageStills.some((s:any)=>s.id===id)&&!kept.some((s:any)=>s.id===id)) - // Draft / upload stills must survive reload even when they fall outside the first page + ].filter((id:string)=>id&&!forget.has(id)&&!gone.has(id)) as string[] + let kept=replacing?[]:(library.value.stills||[]).filter((s:any)=>keepIds.includes(s.id)&&!pageStills.some((p:any)=>p.id===s.id)&&!forget.has(s.id)&&!gone.has(s.id)) + const stillMissing=keepIds.filter(id=>!pageStills.some((s:any)=>s.id===id)&&!kept.some((s:any)=>s.id===id)) + let epoch=page.catalogEpoch + // Draft / upload stills must survive reload even when they fall outside the first page. + // A delete replace only accepts ids the fresh catalog still returns. if(stillMissing.length){ try{ const full=await $fetch(`/api/library?light=1&_=${Date.now()}`) if(gen!==libraryLoadGen) return - const recovered=(full.stills||[]).filter((s:any)=>stillMissing.includes(s.id)&&!forget.has(s.id)) + if(typeof full?.catalogEpoch==='number') epoch=full.catalogEpoch + const recovered=(full.stills||[]).filter((s:any)=>stillMissing.includes(s.id)&&!forget.has(s.id)&&!gone.has(s.id)) kept=[...kept,...recovered.filter((s:any)=>!kept.some((k:any)=>k.id===s.id))] - }catch{/* keep page + in-memory stills */} + }catch{if(replacing) kept=[]} } if(gen!==libraryLoadGen) return library.value={ folders:page.folders||library.value.folders||[], - stills:[...pageStills,...kept].filter((s:any)=>!forget.has(s.id)), - clips:(page.clips||[]).filter((c:any)=>!forget.has(c.id)), - tracks:(page.tracks||[]).filter((t:any)=>!forget.has(t.id)), + stills:[...pageStills,...kept].filter((s:any)=>s?.id&&!forget.has(s.id)&&!gone.has(s.id)), + clips:(page.clips||[]).filter((c:any)=>c?.id&&!forget.has(c.id)&&!gone.has(c.id)), + tracks:(page.tracks||[]).filter((t:any)=>t?.id&&!forget.has(t.id)&&!gone.has(t.id)), drafts:page.drafts||library.value.drafts||[], loraAliases:page.loraAliases||library.value.loraAliases||{}, loraTriggers:page.loraTriggers||library.value.loraTriggers||{}, - keepPrompts:page.keepPrompts||library.value.keepPrompts + keepPrompts:page.keepPrompts||library.value.keepPrompts, + catalogEpoch:typeof epoch==='number'?epoch:(library.value.catalogEpoch??0) } - const allStills=[...pageStills,...kept] - // Drop filled photo cards only when the still is truly gone from the catalog - for(let i=(form.photos||[]).length-1;i>=0;i-=1){ - const id=form.photos[i]?.stillId - if(id && !allStills.some((s:any)=>s.id===id)) form.photos[i].stillId='' - } - syncPhotosBindings() + clearRefsMissingFromLibrary() } async function fetchHealth(){ @@ -2098,6 +2136,7 @@ onMounted(()=>{ // Folder page in background — never blocks Generate / prompt void loadLibraryOnce().then(()=>{ restoreBenchDraft() + clearRefsMissingFromLibrary() if(!form.folderId)form.folderId=library.value.folders[0]?.id||'' loadRevealed(form.folderId) void applyIncomingGenerationLoad() @@ -2159,6 +2198,8 @@ const mobileCtx=computed(()=>({ libraryRefreshKey:libraryRefreshKey.value, family:family.value, familyStillCount:familyStillCount.value, + clipThumbUrl, + clipVideoUrl, showSelectedStill:showSelectedStill.value, libraryOpen:libraryOpen.value, eyeOpen:eyeOpen.value, diff --git a/components/studio2/LibraryModal.vue b/components/studio2/LibraryModal.vue index 9c6d64e..f8002b1 100644 --- a/components/studio2/LibraryModal.vue +++ b/components/studio2/LibraryModal.vue @@ -154,7 +154,7 @@ import { type LibraryTrack } from '~/utils/libraryBrowse' import { clipSettingsRows, stillSettingsRows, trackSettingsRows } from '~/utils/libraryGeneration' -import { assetLabel, libraryAfterWipe, mergeLibraryRows, replaceLibraryRows } from '~/shared/studio2/viewer.mjs' +import { assetLabel, libraryAfterWipe, libraryMediaUrl, mergeLibraryRows } from '~/shared/studio2/viewer.mjs' const props = defineProps<{ open: boolean @@ -201,7 +201,7 @@ const tracks = ref([]) const fetchedAt = ref(0) const nextCursor = ref(null) const liveThumbs = ref(new Set()) -const suppressedDeletedIds = ref(new Set()) +const catalogEpoch = ref(0) const wipeBusy = ref(false) const pendingWipe = ref<{ folderId: string; name: string; count: number } | null>(null) let thumbObserver: IntersectionObserver | null = null @@ -252,9 +252,14 @@ const detailRows = computed(() => { }) function thumbSrc(entry: LibraryEntry) { - if (entry.kind === 'clip' && entry.group) return `/api/library/clips/${entry.group.head.id}/thumb` + const version = catalogEpoch.value + if (entry.kind === 'clip' && entry.group) return libraryMediaUrl(`/api/library/clips/${entry.group.head.id}/thumb`, version) if (entry.kind === 'track') return '' - if (entry.stillGroup) return `/api/library/stills/${entry.stillGroup.head.id}/thumb` + if (entry.stillGroup) { + const id = entry.stillGroup.head.id + if (!stills.value.some(item => item.id === id)) return '' + return libraryMediaUrl(`/api/library/stills/${id}/thumb`, version) + } return '' } @@ -289,10 +294,6 @@ function useAndClose() { close() } -function dropIds() { - return new Set([...(props.hiddenIds || []), ...suppressedDeletedIds.value]) -} - function onDeleteClick() { const asset = detailAsset.value if (!asset?.id) return @@ -301,15 +302,16 @@ function onDeleteClick() { function applyLibraryPage(data: any, replace: boolean) { if (Array.isArray(data?.folders) && data.folders.length) folders.value = data.folders - const drop = [...dropIds()] + if (typeof data?.catalogEpoch === 'number') catalogEpoch.value = data.catalogEpoch + const rows = (list: any[]) => (Array.isArray(list) ? list : []).filter(item => item?.id) if (replace) { - clips.value = replaceLibraryRows(data?.clips || [], drop) as LibraryClip[] - stills.value = replaceLibraryRows(data?.stills || [], drop) as LibraryStill[] - tracks.value = replaceLibraryRows(data?.tracks || [], drop) as LibraryTrack[] + clips.value = rows(data?.clips) as LibraryClip[] + stills.value = rows(data?.stills) as LibraryStill[] + tracks.value = rows(data?.tracks) as LibraryTrack[] } else { - clips.value = mergeLibraryRows(clips.value, data?.clips || [], drop) as LibraryClip[] - stills.value = mergeLibraryRows(stills.value, data?.stills || [], drop) as LibraryStill[] - tracks.value = mergeLibraryRows(tracks.value, data?.tracks || [], drop) as LibraryTrack[] + clips.value = mergeLibraryRows(clips.value, data?.clips || [], []) as LibraryClip[] + stills.value = mergeLibraryRows(stills.value, data?.stills || [], []) as LibraryStill[] + tracks.value = mergeLibraryRows(tracks.value, data?.tracks || [], []) as LibraryTrack[] } nextCursor.value = data?.nextCursor ?? null fetchedAt.value = Date.now() @@ -337,9 +339,6 @@ async function confirmWipeFolder() { ...clips.value.filter(item => item.folderId === pending.folderId).map(item => item.id), ...tracks.value.filter(item => item.folderId === pending.folderId).map(item => item.id) ] - const pendingIds = new Set(suppressedDeletedIds.value) - for (const id of gone) pendingIds.add(id) - suppressedDeletedIds.value = pendingIds stills.value = stills.value.filter(item => item.folderId !== pending.folderId) clips.value = clips.value.filter(item => item.folderId !== pending.folderId) tracks.value = tracks.value.filter(item => item.folderId !== pending.folderId) @@ -350,16 +349,16 @@ async function confirmWipeFolder() { stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))], clips: clips.value, tracks: tracks.value, - suppressedIds: [...suppressedDeletedIds.value] + suppressedIds: [] }, result, pending.folderId) - suppressedDeletedIds.value = new Set(next.suppressedIds) + if (typeof result?.catalogEpoch === 'number') catalogEpoch.value = result.catalogEpoch folders.value = next.folders stills.value = next.stills as LibraryStill[] clips.value = next.clips as LibraryClip[] tracks.value = next.tracks as LibraryTrack[] nextCursor.value = null fetchedAt.value = 0 - emit('wiped', { ...result, folderId: pending.folderId, suppressedIds: next.suppressedIds }) + emit('wiped', { ...result, folderId: pending.folderId, deletedIds: [...new Set([...(result?.deletedIds || []), ...gone])] }) await fetchLibrary(true) } catch (e: any) { loadError.value = e?.data?.statusMessage || e?.message || 'Could not empty that folder' @@ -500,9 +499,18 @@ watch([filter, activeFolderId], () => { watch(() => props.refreshKey, () => { if (!props.open) return + fetchGen += 1 void fetchLibrary(true) }) +watch(() => (props.hiddenIds || []).join('\n'), () => { + const drop = new Set(props.hiddenIds || []) + if (!drop.size) return + stills.value = stills.value.filter(item => !drop.has(item.id)) + clips.value = clips.value.filter(item => !drop.has(item.id)) + tracks.value = tracks.value.filter(item => !drop.has(item.id)) +}) + onBeforeUnmount(() => { if (import.meta.client) { document.body.style.overflow = '' diff --git a/components/studio2/Mobile.vue b/components/studio2/Mobile.vue index f6e8cb3..0348215 100644 --- a/components/studio2/Mobile.vue +++ b/components/studio2/Mobile.vue @@ -120,7 +120,7 @@ v-else-if="ctx.selected?.kind==='clip'" v-show="!ctx.isHidden(ctx.selected)" :key="ctx.selected.id" - :src="`/api/library/clips/${ctx.selected.id}/video`" + :src="ctx.clipVideoUrl(ctx.selected.id)" controls playsinline /> diff --git a/pages/library.vue b/pages/library.vue index 225967a..40ccd78 100644 --- a/pages/library.vue +++ b/pages/library.vue @@ -556,7 +556,7 @@ import { type LibraryStill, type LibraryTrack } from '~/utils/libraryBrowse' -import { libraryAfterWipe, mergeLibraryRows, replaceLibraryRows } from '~/shared/studio2/viewer.mjs' +import { libraryAfterWipe, libraryMediaUrl, mergeLibraryRows } from '~/shared/studio2/viewer.mjs' import { isXaigenStudio } from '~/utils/videoModels' import { clipSettingsRows, stillSettingsRows, trackSettingsRows } from '~/utils/libraryGeneration' @@ -637,7 +637,7 @@ const pendingDelete = ref<{ title: string; name: string; detail?: string; conseq const pendingWipe = ref<{ folderId: string; name: string; count: number } | null>(null) const wipeBusy = ref(false) const libraryLoading = ref(false) -const suppressedDeletedIds = ref(new Set()) +const catalogEpoch = ref(0) const keepingInputBusy = ref(false) const toasts = ref>([]) let toastId = 0 @@ -711,12 +711,13 @@ const visibleEntries = computed(() => { const previewVideo = computed(() => { if (focused.value?.kind !== 'clip' || !focused.value.group) return '' const id = focusedPartId.value || focused.value.group.head.id - return `/api/library/clips/${id}/video` + return libraryMediaUrl(`/api/library/clips/${id}/video`, catalogEpoch.value) }) const previewStillSrc = computed(() => { if (focused.value?.kind !== 'still' || !focused.value.stillGroup) return '' const id = focusedPartId.value || focused.value.stillGroup.head.id - return `/api/library/stills/${id}` + if (!stills.value.some(item => item.id === id)) return '' + return libraryMediaUrl(`/api/library/stills/${id}`, catalogEpoch.value) }) const previewAudio = computed(() => { if (focused.value?.kind !== 'track' || !focused.value.track) return '' @@ -777,14 +778,14 @@ const detailMeta = computed(() => { const downloadHref = computed(() => { if (focused.value?.kind === 'clip' && focused.value.group) { const id = focusedPartId.value || focused.value.group.head.id - return `/api/library/clips/${id}/video` + return libraryMediaUrl(`/api/library/clips/${id}/video`, catalogEpoch.value) } if (focused.value?.kind === 'track' && focused.value.track) { - return `/api/library/tracks/${focused.value.track.id}/audio` + return libraryMediaUrl(`/api/library/tracks/${focused.value.track.id}/audio`, catalogEpoch.value) } if (focused.value?.stillGroup) { const id = focusedPartId.value || focused.value.stillGroup.head.id - return `/api/library/stills/${id}` + return libraryMediaUrl(`/api/library/stills/${id}`, catalogEpoch.value) } return '' }) @@ -809,6 +810,7 @@ function applyLibrary(data: unknown, opts?: { replace?: boolean }) { tracks?: LibraryTrack[] nextCursor?: string | null hasMore?: boolean + catalogEpoch?: number } if (payload.id && !payload.folders && !payload.clips && !payload.stills && !payload.tracks) { if (typeof payload.hideInput === 'boolean') { @@ -822,15 +824,16 @@ function applyLibrary(data: unknown, opts?: { replace?: boolean }) { return } if (payload.folders?.length) folders.value = payload.folders - const drop = [...suppressedDeletedIds.value] + if (typeof payload.catalogEpoch === 'number') catalogEpoch.value = payload.catalogEpoch + const rows = (list: T[] | undefined) => (Array.isArray(list) ? list : []).filter(item => (item as { id?: string })?.id) if (replace) { - clips.value = replaceLibraryRows(payload.clips || [], drop) - stills.value = replaceLibraryRows(payload.stills || [], drop) - tracks.value = replaceLibraryRows(payload.tracks || [], drop) + clips.value = rows(payload.clips) + stills.value = rows(payload.stills) + tracks.value = rows(payload.tracks) } else { - clips.value = mergeLibraryRows(clips.value, payload.clips || [], drop) - stills.value = mergeLibraryRows(stills.value, payload.stills || [], drop) - tracks.value = mergeLibraryRows(tracks.value, payload.tracks || [], drop) + clips.value = mergeLibraryRows(clips.value, payload.clips || [], []) + stills.value = mergeLibraryRows(stills.value, payload.stills || [], []) + tracks.value = mergeLibraryRows(tracks.value, payload.tracks || [], []) } libraryNextCursor.value = payload.nextCursor || null if (folderId.value !== 'all' && !folders.value.some(folder => folder.id === folderId.value)) { @@ -948,9 +951,14 @@ async function toggleFocusedHidden() { } function thumbSrc(entry: LibraryEntry) { - if (entry.kind === 'clip' && entry.group) return `/api/library/clips/${entry.group.head.id}/thumb` + const version = catalogEpoch.value + if (entry.kind === 'clip' && entry.group) return libraryMediaUrl(`/api/library/clips/${entry.group.head.id}/thumb`, version) if (entry.kind === 'track') return '' - if (entry.stillGroup) return `/api/library/stills/${entry.stillGroup.parts[cardImageIndex(entry)].id}/thumb` + if (entry.stillGroup) { + const id = entry.stillGroup.parts[cardImageIndex(entry)]?.id + if (!id || !stills.value.some(item => item.id === id)) return '' + return libraryMediaUrl(`/api/library/stills/${id}/thumb`, version) + } return '' } @@ -974,9 +982,9 @@ function partThumb(part: LibraryClip | LibraryStill) { if ('hideThumbnail' in part && !('role' in part)) { const clip = part as LibraryClip // Prefer this clip’s first frame so siblings don’t all look like the Start thumb. - return `/api/library/clips/${clip.id}/first-frame?thumb=1&v=${encodeURIComponent(clip.id)}` + return libraryMediaUrl(`/api/library/clips/${clip.id}/first-frame?thumb=1`, catalogEpoch.value) } - return `/api/library/stills/${part.id}/thumb` + return libraryMediaUrl(`/api/library/stills/${part.id}/thumb`, catalogEpoch.value) } function focusPart(id: string) { @@ -1032,16 +1040,11 @@ function entryPartIds(entry: LibraryEntry) { } async function selectAll() { - // Loaded rows only. A fresh full-catalog fetch would merge later pages and - // can put suppressed ids back into the selection. const start = Date.now() while (libraryLoading.value && Date.now() - start < 15000) { await new Promise(resolve => setTimeout(resolve, 40)) } - const drop = suppressedDeletedIds.value - selectedKeys.value = entries.value - .filter(entry => entryPartIds(entry).every(id => !drop.has(id))) - .map(entry => entry.key) + selectedKeys.value = entries.value.map(entry => entry.key) lastSelectedKey.value = selectedKeys.value.at(-1) || '' } @@ -1282,14 +1285,12 @@ function askRemoveKeys(keys: string[]) { } } -function markDeletedIds(ids: string[]) { +function dropLocalIds(ids: string[]) { if (!ids.length) return - const next = new Set(suppressedDeletedIds.value) - for (const id of ids) next.add(id) - suppressedDeletedIds.value = next - stills.value = stills.value.filter(item => !next.has(item.id)) - clips.value = clips.value.filter(item => !next.has(item.id)) - tracks.value = tracks.value.filter(item => !next.has(item.id)) + const gone = new Set(ids) + stills.value = stills.value.filter(item => !gone.has(item.id)) + clips.value = clips.value.filter(item => !gone.has(item.id)) + tracks.value = tracks.value.filter(item => !gone.has(item.id)) } async function confirmDelete() { @@ -1309,13 +1310,8 @@ async function confirmDelete() { for (const part of entry.stillGroup.parts || [entry.stillGroup.head]) gone.push(part.id) } } - markDeletedIds(gone) - if (pending.keys.includes(focusedKey.value)) { - focusedKey.value = '' - focusedPartId.value = '' - } - clearSelection() - await Promise.allSettled(items.map((entry) => { + libraryFetchGen += 1 + const results = await Promise.allSettled(items.map((entry) => { if (entry.kind === 'clip') { return $fetch(`/api/library/clips/${entry.group!.head.id}`, { method: 'DELETE', query: { family: '1' } }) } @@ -1324,6 +1320,27 @@ async function confirmDelete() { } return $fetch(`/api/library/stills/${entry.stillGroup!.head.id}`, { method: 'DELETE', query: { family: '1' } }) })) + const removed: string[] = [] + results.forEach((result, index) => { + if (result.status === 'fulfilled') { + const entry = items[index] + removed.push(...entryPartIds(entry)) + return + } + const status = Number((result.reason as { statusCode?: number, status?: number })?.statusCode || (result.reason as { status?: number })?.status || 0) + if (status === 404) removed.push(...entryPartIds(items[index])) + }) + if (removed.length !== gone.length) { + const failed = results.find(result => result.status === 'rejected') as PromiseRejectedResult | undefined + const reason = failed?.reason as { data?: { statusMessage?: string }, message?: string } | undefined + toast(reason?.data?.statusMessage || reason?.message || 'Could not delete every item') + } + dropLocalIds(removed) + if (pending.keys.includes(focusedKey.value)) { + focusedKey.value = '' + focusedPartId.value = '' + } + clearSelection() await loadLibrary() } finally { deleteBusy.value = false @@ -1356,7 +1373,6 @@ async function confirmWipeFolder() { ...clips.value.filter(item => item.folderId === pending.folderId).map(item => item.id), ...tracks.value.filter(item => item.folderId === pending.folderId).map(item => item.id) ] - markDeletedIds(gone) clearSelection() clearFocus() try { @@ -1366,9 +1382,9 @@ async function confirmWipeFolder() { stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))], clips: clips.value, tracks: tracks.value, - suppressedIds: [...suppressedDeletedIds.value] + suppressedIds: [] }, result, pending.folderId) - suppressedDeletedIds.value = new Set(next.suppressedIds) + if (typeof result?.catalogEpoch === 'number') catalogEpoch.value = result.catalogEpoch folders.value = next.folders stills.value = next.stills clips.value = next.clips diff --git a/pages/studio-1.vue b/pages/studio-1.vue index b872139..f1a1d73 100644 --- a/pages/studio-1.vue +++ b/pages/studio-1.vue @@ -1786,7 +1786,7 @@ @click="openClip(entry.group.head)" > - +
@@ -2001,7 +2001,7 @@
@@ -5981,10 +5981,10 @@ function stepOutput(delta: number) { } function showOutputStill(still: LibraryStill) { - editResultUrl.value = `/api/library/stills/${still.id}` + editResultUrl.value = `/api/library/stills/${still.id}?v=0` lastV2StillId.value = still.id editDownloadName.value = clipFileName(stillTitle(still)) - if (editLightboxUrl.value) editLightboxUrl.value = `/api/library/stills/${still.id}` + if (editLightboxUrl.value) editLightboxUrl.value = `/api/library/stills/${still.id}?v=0` } function stepOutputFamily(delta: number) { @@ -6514,7 +6514,7 @@ function openStill(still: LibraryStill) { // Preview only — never yank Video/Image workspace tabs. outputFocus.value = 'edit' browseFolderId.value = still.folderId - editResultUrl.value = `/api/library/stills/${still.id}` + editResultUrl.value = `/api/library/stills/${still.id}?v=0` concealEditOutput.value = still.hideInput === true editAwaitingReveal.value = still.hideInput === true editLockedSave.value = false @@ -7907,7 +7907,7 @@ function applyEditEvent(payload: Record, hidden: boolean, folderLoc : (folderLocked || payload.folderLocked === true) if (payload.stillId && !locked) { - editResultUrl.value = `/api/library/stills/${payload.stillId}` + editResultUrl.value = `/api/library/stills/${payload.stillId}?v=0` if (studioMode.value === 'editv2' || v2JobPending.value) lastV2StillId.value = payload.stillId editLockedSave.value = false if (payload.hideThumbnail || hidden) { @@ -7951,7 +7951,7 @@ function applyEditEvent(payload: Record, hidden: boolean, folderLoc browseFolderId.value = folderId.value editStatusMessage.value = 'Saved to the locked folder. Unlock it to view.' } else { - editResultUrl.value = `/api/library/stills/${payload.stillId}` + editResultUrl.value = `/api/library/stills/${payload.stillId}?v=0` if (studioMode.value === 'editv2' || v2JobPending.value) lastV2StillId.value = payload.stillId concealEditOutput.value = Boolean(payload.hideThumbnail || hidden) editAwaitingReveal.value = concealEditOutput.value diff --git a/server/api/library/clips/[id]/first-frame.get.ts b/server/api/library/clips/[id]/first-frame.get.ts index 01e01f0..e9872a2 100644 --- a/server/api/library/clips/[id]/first-frame.get.ts +++ b/server/api/library/clips/[id]/first-frame.get.ts @@ -1,7 +1,8 @@ import { existsSync, createReadStream } from 'node:fs' -import { clipFrameThumbFile, ensureClipFirstFrame, ensureScaledThumb, fileEtag, sniffImageType } from '~/server/utils/library' +import { clipFrameThumbFile, ensureClipFirstFrame, ensureScaledThumb, setLibraryMediaHeaders, sniffImageType } from '~/server/utils/library' export default defineEventHandler(async (event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const clip = getClip(owner, id) @@ -25,13 +26,6 @@ export default defineEventHandler(async (event) => { if (thumbPath && existsSync(thumbPath)) path = thumbPath } - const etag = fileEtag(path) - setHeader(event, 'ETag', etag) - setHeader(event, 'Cache-Control', wantThumb ? 'private, max-age=60, must-revalidate' : 'private, max-age=60, must-revalidate') - if (getHeader(event, 'if-none-match') === etag) { - setResponseStatus(event, 304) - return null - } setHeader(event, 'Content-Type', wantThumb && path !== framePath ? 'image/jpeg' : sniffImageType(path)) return sendStream(event, createReadStream(path)) }) diff --git a/server/api/library/clips/[id]/last-frame.get.ts b/server/api/library/clips/[id]/last-frame.get.ts index a492987..952e939 100644 --- a/server/api/library/clips/[id]/last-frame.get.ts +++ b/server/api/library/clips/[id]/last-frame.get.ts @@ -1,7 +1,8 @@ import { existsSync, createReadStream } from 'node:fs' -import { clipFrameThumbFile, ensureClipLastFrame, ensureScaledThumb, fileEtag, sniffImageType } from '~/server/utils/library' +import { clipFrameThumbFile, ensureClipLastFrame, ensureScaledThumb, setLibraryMediaHeaders, sniffImageType } from '~/server/utils/library' export default defineEventHandler(async (event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const clip = getClip(owner, id) @@ -25,13 +26,6 @@ export default defineEventHandler(async (event) => { if (thumbPath && existsSync(thumbPath)) path = thumbPath } - const etag = fileEtag(path) - setHeader(event, 'ETag', etag) - setHeader(event, 'Cache-Control', wantThumb ? 'private, max-age=60, must-revalidate' : 'private, max-age=60, must-revalidate') - if (getHeader(event, 'if-none-match') === etag) { - setResponseStatus(event, 304) - return null - } setHeader(event, 'Content-Type', wantThumb && path !== framePath ? 'image/jpeg' : sniffImageType(path)) return sendStream(event, createReadStream(path)) }) diff --git a/server/api/library/clips/[id]/thumb.get.ts b/server/api/library/clips/[id]/thumb.get.ts index 402e192..8d3a700 100644 --- a/server/api/library/clips/[id]/thumb.get.ts +++ b/server/api/library/clips/[id]/thumb.get.ts @@ -1,7 +1,8 @@ import { existsSync, createReadStream } from 'node:fs' -import { clipThumbPath, ensureClipThumb, fileEtag, sniffImageType } from '~/server/utils/library' +import { setLibraryMediaHeaders, clipThumbPath, ensureClipThumb, sniffImageType } from '~/server/utils/library' export default defineEventHandler(async (event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const clip = getClip(owner, id) @@ -11,13 +12,6 @@ export default defineEventHandler(async (event) => { if (!path || !existsSync(path)) { throw createError({ statusCode: 404, statusMessage: 'Thumbnail not found' }) } - const etag = fileEtag(path) - setHeader(event, 'ETag', etag) - setHeader(event, 'Cache-Control', 'public, max-age=86400') - if (getHeader(event, 'if-none-match') === etag) { - setResponseStatus(event, 304) - return null - } setHeader(event, 'Content-Type', sniffImageType(path)) return sendStream(event, createReadStream(path)) }) diff --git a/server/api/library/clips/[id]/video.get.ts b/server/api/library/clips/[id]/video.get.ts index 7f423d2..f9791c8 100644 --- a/server/api/library/clips/[id]/video.get.ts +++ b/server/api/library/clips/[id]/video.get.ts @@ -1,8 +1,10 @@ import { existsSync } from 'node:fs' import { sendPathWithRange } from '~/server/utils/httpRange' +import { setLibraryMediaHeaders } from '~/server/utils/library' import { inlineFilename } from '~/shared/content-disposition.mjs' export default defineEventHandler((event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const clip = getClip(owner, id) @@ -13,6 +15,7 @@ export default defineEventHandler((event) => { } return sendPathWithRange(event, path, 'video/mp4', { 'Content-Disposition': inlineFilename(`${safeDownloadName(clipTitle(clip))}.mp4`), - 'Cache-Control': 'private, max-age=0, must-revalidate' + 'Cache-Control': 'no-store, no-cache, must-revalidate', + 'Pragma': 'no-cache' }) }) diff --git a/server/api/library/drafts/[id]/still.get.ts b/server/api/library/drafts/[id]/still.get.ts index 50f5dfe..13dc27f 100644 --- a/server/api/library/drafts/[id]/still.get.ts +++ b/server/api/library/drafts/[id]/still.get.ts @@ -1,6 +1,8 @@ import { existsSync, readFileSync } from 'node:fs' +import { setLibraryMediaHeaders } from '~/server/utils/library' export default defineEventHandler((event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const draft = getRetryDraft(owner, id) @@ -14,6 +16,5 @@ export default defineEventHandler((event) => { } const buf = readFileSync(path) setHeader(event, 'Content-Type', imageContentType(buf)) - setHeader(event, 'Cache-Control', 'private, max-age=3600') return buf }) diff --git a/server/api/library/index.get.ts b/server/api/library/index.get.ts index 7b0bd3b..9b05c77 100644 --- a/server/api/library/index.get.ts +++ b/server/api/library/index.get.ts @@ -1,6 +1,7 @@ -import { publicLibrary, publicLibraryPage } from '~/server/utils/library' +import { publicLibrary, publicLibraryPage, setLibraryMediaHeaders } from '~/server/utils/library' export default defineEventHandler((event) => { + setLibraryMediaHeaders(event) const query = getQuery(event) const light = String(query.light || '') === '1' const full = String(query.full || '') === '1' diff --git a/server/api/library/stills/[id].get.ts b/server/api/library/stills/[id].get.ts index 1adca8f..21c12fb 100644 --- a/server/api/library/stills/[id].get.ts +++ b/server/api/library/stills/[id].get.ts @@ -1,7 +1,8 @@ import { existsSync, createReadStream } from 'node:fs' -import { fileEtag, stillPath, existingStillThumbPath, stillThumbPath, sniffImageType } from '~/server/utils/library' +import { setLibraryMediaHeaders, stillPath, existingStillThumbPath, stillThumbPath, sniffImageType } from '~/server/utils/library' export default defineEventHandler((event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const still = getStill(owner, id) @@ -12,18 +13,10 @@ export default defineEventHandler((event) => { if (wantThumb) { const path = existingStillThumbPath(owner, id) if (path && path !== original && existsSync(path)) { - const etag = fileEtag(path) - setHeader(event, 'ETag', etag) - setHeader(event, 'Cache-Control', 'public, max-age=86400') - if (getHeader(event, 'if-none-match') === etag) { - setResponseStatus(event, 304) - return null - } setHeader(event, 'Content-Type', 'image/jpeg') return sendStream(event, createReadStream(path)) } void stillThumbPath(owner, id).catch(() => null) - setHeader(event, 'Cache-Control', 'no-store') setResponseStatus(event, 204) return null } @@ -32,13 +25,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, statusMessage: 'Image file is missing' }) } - const etag = fileEtag(original) - setHeader(event, 'ETag', etag) - setHeader(event, 'Cache-Control', 'private, max-age=3600') - if (getHeader(event, 'if-none-match') === etag) { - setResponseStatus(event, 304) - return null - } setHeader(event, 'Content-Type', sniffImageType(original)) return sendStream(event, createReadStream(original)) }) diff --git a/server/api/library/stills/[id]/preview.get.ts b/server/api/library/stills/[id]/preview.get.ts index a4d9fdd..3ac24ae 100644 --- a/server/api/library/stills/[id]/preview.get.ts +++ b/server/api/library/stills/[id]/preview.get.ts @@ -1,7 +1,8 @@ import { existsSync, createReadStream } from 'node:fs' -import { fileEtag, stillPath, stillPreviewPath, existingStillPreviewPath } from '~/server/utils/library' +import { setLibraryMediaHeaders, stillPath, stillPreviewPath, existingStillPreviewPath } from '~/server/utils/library' export default defineEventHandler((event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const still = getStill(owner, id) @@ -11,20 +12,11 @@ export default defineEventHandler((event) => { const original = stillPath(owner, still.id) // Ready preview → stream. Never await ffmpeg; never stream the archive master. if (path && existsSync(path) && path !== original) { - const etag = fileEtag(path) - setHeader(event, 'ETag', etag) - setHeader(event, 'Cache-Control', 'public, max-age=86400') - if (getHeader(event, 'if-none-match') === etag) { - setResponseStatus(event, 304) - return null - } setHeader(event, 'Content-Type', 'image/jpeg') return sendStream(event, createReadStream(path)) } - // Missing → answer now; build .preview.jpg in the background void stillPreviewPath(owner, id).catch(() => null) - setHeader(event, 'Cache-Control', 'no-store') setResponseStatus(event, 204) return null }) diff --git a/server/api/library/stills/[id]/thumb.get.ts b/server/api/library/stills/[id]/thumb.get.ts index 96411be..3cd593b 100644 --- a/server/api/library/stills/[id]/thumb.get.ts +++ b/server/api/library/stills/[id]/thumb.get.ts @@ -1,7 +1,8 @@ import { existsSync, createReadStream } from 'node:fs' -import { fileEtag, stillPath, stillThumbPath, existingStillThumbPath } from '~/server/utils/library' +import { setLibraryMediaHeaders, stillPath, stillThumbPath, existingStillThumbPath } from '~/server/utils/library' export default defineEventHandler((event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const still = getStill(owner, id) @@ -10,21 +11,13 @@ export default defineEventHandler((event) => { const path = existingStillThumbPath(owner, id) const original = stillPath(owner, still.id) // Ready thumb → stream. Never await ffmpeg on the request path. + // Catalog miss is a 404 from getStill — leftover thumb bytes are not served. if (path && existsSync(path) && path !== original) { - const etag = fileEtag(path) - setHeader(event, 'ETag', etag) - setHeader(event, 'Cache-Control', 'public, max-age=86400') - if (getHeader(event, 'if-none-match') === etag) { - setResponseStatus(event, 304) - return null - } setHeader(event, 'Content-Type', 'image/jpeg') return sendStream(event, createReadStream(path)) } - // Missing → answer now; build .thumb.jpg in the background (job save / upload also kick this) void stillThumbPath(owner, id).catch(() => null) - setHeader(event, 'Cache-Control', 'no-store') setResponseStatus(event, 204) return null }) diff --git a/server/api/library/tracks/[id]/audio.get.ts b/server/api/library/tracks/[id]/audio.get.ts index 5751eea..9dc5a34 100644 --- a/server/api/library/tracks/[id]/audio.get.ts +++ b/server/api/library/tracks/[id]/audio.get.ts @@ -1,8 +1,10 @@ import { existsSync } from 'node:fs' import { sendPathWithRange } from '~/server/utils/httpRange' +import { setLibraryMediaHeaders } from '~/server/utils/library' import { musicContentType } from '~/utils/music' export default defineEventHandler((event) => { + setLibraryMediaHeaders(event) const { owner } = assertLibraryOwner(event) const id = String(getRouterParam(event, 'id') || '') const track = getTrack(owner, id) @@ -14,6 +16,7 @@ export default defineEventHandler((event) => { const ext = track.ext || 'flac' return sendPathWithRange(event, path, musicContentType(ext), { 'Content-Disposition': `inline; filename="${safeDownloadName(track.name)}.${ext}"`, - 'Cache-Control': 'private, max-age=0, must-revalidate' + 'Cache-Control': 'no-store, no-cache, must-revalidate', + Pragma: 'no-cache' }) }) diff --git a/server/middleware/cache-headers.ts b/server/middleware/cache-headers.ts index 3840a4c..cd05634 100644 --- a/server/middleware/cache-headers.ts +++ b/server/middleware/cache-headers.ts @@ -8,5 +8,10 @@ export default defineEventHandler((event) => { } if (path.startsWith('/api/prompt/')) { setHeader(event, 'Cache-Control', 'no-cache, no-store, no-transform') + return + } + if (path === '/api/library' || path.startsWith('/api/library/')) { + setHeader(event, 'Cache-Control', 'no-store, no-cache, must-revalidate') + setHeader(event, 'Pragma', 'no-cache') } }) diff --git a/server/utils/library.ts b/server/utils/library.ts index dddf8c0..a77223a 100644 --- a/server/utils/library.ts +++ b/server/utils/library.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { spawn } from 'node:child_process' import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto' import { promisify } from 'node:util' -import type { H3Event } from 'h3' +import { setHeader, type H3Event } from 'h3' import { extractFirstFrame, extractFrameAt, extractLastFrame, probeDuration, remuxFaststart } from '~/server/utils/ffmpeg' import { normalizePermanenceRefs, type PermanenceRef } from '~/utils/globalLocks' import { normalizeStillSettings, type StillGenerationSettings } from '~/utils/libraryGeneration' @@ -416,8 +416,22 @@ function writeCatalog(owner: string, catalog: Catalog) { } export function invalidateCatalogCache(owner?: string) { - if (owner) catalogCache.delete(owner) - else catalogCache.clear() + // Bump the epoch so a read that already parsed pre-wipe bytes cannot + // repopulate the cache. Do not trust catalog mtime for this. + if (owner) { + catalogCache.delete(owner) + catalogEpoch.set(owner, (catalogEpoch.get(owner) || 0) + 1) + return + } + catalogCache.clear() + for (const key of catalogEpoch.keys()) { + catalogEpoch.set(key, (catalogEpoch.get(key) || 0) + 1) + } +} + +export function setLibraryMediaHeaders(event: H3Event) { + setHeader(event, 'Cache-Control', 'no-store, no-cache, must-revalidate') + setHeader(event, 'Pragma', 'no-cache') } function mutate(owner: string, fn: (catalog: Catalog) => T): Promise { @@ -656,7 +670,8 @@ export function publicLibrary(event: H3Event, opts?: { light?: boolean }) { drafts: catalog.drafts, loraAliases: catalog.loraAliases || {}, loraTriggers: catalog.loraTriggers || {}, - keepPrompts: catalog.keepPrompts || emptyKeepPrompts() + keepPrompts: catalog.keepPrompts || emptyKeepPrompts(), + catalogEpoch: catalogEpoch.get(owner) || 0 } } @@ -713,6 +728,7 @@ export function publicLibraryPage( ext?: string } + const epoch = catalogEpoch.get(owner) || 0 const rows: Row[] = [] if (typeFilter !== 'videos' && typeFilter !== 'music') { for (const still of catalog.stills) { @@ -724,7 +740,7 @@ export function publicLibraryPage( name: still.name || still.filename || still.id, type: 'still', createdAt: still.createdAt || 0, - thumbUrl: `/api/library/stills/${still.id}/thumb`, + thumbUrl: `/api/library/stills/${still.id}/thumb?v=${epoch}`, folderId: still.folderId, prompt: still.prompt, promptPre: still.promptPre, @@ -746,7 +762,7 @@ export function publicLibraryPage( name: clip.name || clip.id, type: 'clip', createdAt: clip.createdAt || 0, - thumbUrl: `/api/library/clips/${clip.id}/thumb`, + thumbUrl: `/api/library/clips/${clip.id}/thumb?v=${epoch}`, folderId: clip.folderId, prompt: clip.prompt, promptPre: clip.promptPre, @@ -814,7 +830,8 @@ export function publicLibraryPage( loraAliases: catalog.loraAliases || {}, loraTriggers: catalog.loraTriggers || {}, keepPrompts: catalog.keepPrompts || emptyKeepPrompts(), - total: rows.length + total: rows.length, + catalogEpoch: epoch } } @@ -885,13 +902,15 @@ export function deleteFolder(owner: string, id: string) { const clips = catalog.clips.filter(clip => clip.folderId === id) const stills = catalog.stills.filter(still => still.folderId === id) const tracks = (catalog.tracks || []).filter(track => track.folderId === id) + const removed = removedEntries(clips, stills, tracks) + for (const clip of clips) unlinkVerified(clipDir(owner, clip.id), true) + for (const still of stills) removeStillFiles(owner, still.id) + for (const track of tracks) unlinkVerified(trackDir(owner, track.id), true) + assertRemovedEntries(owner, removed) catalog.folders = catalog.folders.filter(item => item.id !== id) catalog.clips = catalog.clips.filter(clip => clip.folderId !== id) catalog.stills = catalog.stills.filter(still => still.folderId !== id) catalog.tracks = (catalog.tracks || []).filter(track => track.folderId !== id) - for (const clip of clips) safeRm(clipDir(owner, clip.id), true) - for (const still of stills) removeStillFiles(owner, still.id) - for (const track of tracks) safeRm(trackDir(owner, track.id), true) return { fallbackFolderId: catalog.folders[0].id } }) } @@ -929,6 +948,7 @@ function emptyFolderRows(catalog: Catalog, folderId: string) { /** Delete every still, clip, and track in a folder — catalog rows and on-disk files. Keeps the folder. */ export function wipeFolderContents(owner: string, folderId: string) { + let removed: RemovedEntry[] = [] return mutate(owner, (catalog) => { const folder = catalog.folders.find(item => item.id === folderId) if (!folder) throw createError({ statusCode: 404, statusMessage: 'Folder not found' }) @@ -940,11 +960,13 @@ export function wipeFolderContents(owner: string, folderId: string) { ...stills.map(item => item.id), ...tracks.map(item => item.id) ]) + removed = removedEntries(clips, stills, tracks) + for (const clip of clips) unlinkVerified(clipDir(owner, clip.id), true) + for (const still of stills) removeStillFiles(owner, still.id) + for (const track of tracks) unlinkVerified(trackDir(owner, track.id), true) + assertRemovedEntries(owner, removed) emptyFolderRows(catalog, folderId) detachDraftStills(catalog, deletedIds) - for (const clip of clips) safeRm(clipDir(owner, clip.id), true) - for (const still of stills) removeStillFiles(owner, still.id) - for (const track of tracks) safeRm(trackDir(owner, track.id), true) pruneMissingStillMasters(owner, catalog) const remain = [ ...catalog.clips.filter(item => sameFolder(item.folderId, folderId)), @@ -955,6 +977,7 @@ export function wipeFolderContents(owner: string, folderId: string) { console.error('[library] wipe left folder rows', folderId, remain.map(item => item.id)) emptyFolderRows(catalog, folderId) } + assertRemovedEntries(owner, removed) return { folderId: folder.id, folderName: folder.name, @@ -965,6 +988,7 @@ export function wipeFolderContents(owner: string, folderId: string) { tracks: tracks.length } }).then((result) => { + assertRemovedEntries(owner, removed) invalidateCatalogCache(owner) return result }) @@ -998,8 +1022,8 @@ function pruneMissingStillMasters(owner: string, catalog: Catalog) { keep.push(still) continue } - droppedIds.add(still.id) removeStillFiles(owner, still.id) + droppedIds.add(still.id) } catalog.stills = keep.filter(still => beforeIds.has(still.id)) if (!droppedIds.size) return 0 @@ -1446,20 +1470,140 @@ export function existingStillPreviewPath(owner: string, id: string) { return '' } -/** Never throw — a locked thumb must not abort the catalog write. */ -function safeRm(target: string, recursive = false) { +type RemovedEntry = { id: string, kind: 'still' | 'clip' | 'track' } + +function removedEntries(clips: { id: string }[], stills: { id: string }[], tracks: { id: string }[]): RemovedEntry[] { + return [ + ...stills.map(item => ({ id: item.id, kind: 'still' as const })), + ...clips.map(item => ({ id: item.id, kind: 'clip' as const })), + ...tracks.map(item => ({ id: item.id, kind: 'track' as const })) + ] +} + +function pathRemains(target: string) { try { - rmSync(target, recursive ? { recursive: true, force: true } : { force: true }) + statSync(target) + return true } catch (error) { + const code = (error as NodeJS.ErrnoException)?.code + if (code === 'ENOENT') return false const message = error instanceof Error ? error.message : String(error) - console.error('[library] file remove failed', message) + console.error('[library] file stat failed', target, message) + return true } } +function stillFileRemains(target: string) { + try { + return statSync(target).isFile() + } catch (error) { + const code = (error as NodeJS.ErrnoException)?.code + if (code === 'ENOENT') return false + const message = error instanceof Error ? error.message : String(error) + console.error('[library] file stat failed', target, message) + return true + } +} + +/** Log, retry once, then throw if the path is still there. Never swallow a failed unlink. */ +function unlinkVerified(target: string, recursive = false) { + let mode: 'missing' | 'file' | 'dir' = 'missing' + try { + mode = statSync(target).isDirectory() ? 'dir' : 'file' + } catch (error) { + const code = (error as NodeJS.ErrnoException)?.code + if (code === 'ENOENT') return + const message = error instanceof Error ? error.message : String(error) + console.error('[library] file stat failed', target, message) + throw createError({ statusCode: 500, statusMessage: `Library delete left files on disk: ${target}` }) + } + if (!recursive && mode === 'dir') return + const opts = recursive ? { recursive: true, force: true } : { force: true } + for (let attempt = 0; attempt < 2; attempt++) { + try { + rmSync(target, opts) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + console.error('[library] file remove failed', target, message) + } + if (!pathRemains(target)) return + } + console.error('[library] file still exists after remove', target) + throw createError({ statusCode: 500, statusMessage: `Library delete left files on disk: ${target}` }) +} + +function stillIdAllowed(id: string) { + return Boolean(id) && !id.includes('/') && !id.includes('\\') && !id.includes('..') +} + +/** Master, thumb, preview, any `` / `.*` sibling, and the same names on the legacy roots. */ +function stillArtifactPaths(owner: string, id: string) { + if (!stillIdAllowed(id)) { + throw createError({ statusCode: 400, statusMessage: 'Invalid still id' }) + } + const paths: string[] = [] + const seen = new Set() + const add = (path: string) => { + if (!path || seen.has(path)) return + seen.add(path) + paths.push(path) + } + add(stillPath(owner, id)) + add(stillThumbFile(owner, id)) + add(stillPreviewFile(owner, id)) + const dirs: string[] = [] + try { dirs.push(join(ownerRoot(owner), 'stills')) } catch { /* owner root unavailable */ } + try { + const root = libraryRoot() + dirs.push(join(root, 'files')) + dirs.push(join(root, 'stills')) + for (const dir of [join(root, 'files'), join(root, 'stills')]) { + add(join(dir, id)) + add(join(dir, `${id}.thumb.jpg`)) + add(join(dir, `${id}.preview.jpg`)) + } + } catch { /* legacy root unavailable */ } + for (const dir of dirs) { + let names: string[] = [] + try { + if (existsSync(dir)) names = readdirSync(dir).map(name => String(name)) + } catch { names = [] } + for (const name of names) { + if (name === id || name.startsWith(`${id}.`)) add(join(dir, name)) + } + } + return paths +} + +function entryPaths(owner: string, entry: RemovedEntry) { + if (entry.kind === 'clip') return [clipDir(owner, entry.id)] + if (entry.kind === 'track') return [trackDir(owner, entry.id)] + return stillArtifactPaths(owner, entry.id) +} + +function assertRemovedEntries(owner: string, entries: RemovedEntry[]) { + const survived: string[] = [] + for (const entry of entries) { + const paths = entryPaths(owner, entry) + const remains = entry.kind === 'still' + ? paths.some(path => stillFileRemains(path)) + : paths.some(path => pathRemains(path)) + if (remains) survived.push(entry.id) + } + if (!survived.length) return + throw createError({ + statusCode: 500, + statusMessage: `Library delete left files on disk: ${survived.join(',')}` + }) +} + +function assertStillFilesGone(owner: string, ids: string[]) { + assertRemovedEntries(owner, ids.map(id => ({ id, kind: 'still' as const }))) +} + function removeStillFiles(owner: string, id: string) { - safeRm(stillPath(owner, id)) - safeRm(stillThumbFile(owner, id)) - safeRm(stillPreviewFile(owner, id)) + for (const path of stillArtifactPaths(owner, id)) unlinkVerified(path) + assertStillFilesGone(owner, [id]) } let thumbSlots = 0 @@ -1982,11 +2126,22 @@ export function getStill(owner: string, id: string) { export function deleteStill(owner: string, id: string) { return mutate(owner, (catalog) => { const still = catalog.stills.find(item => item.id === id) - if (!still) throw createError({ statusCode: 404, statusMessage: 'Image not found' }) + // A previous delete may have dropped the row and left the files. Unlink them, then 404. + if (!still) { + removeStillFiles(owner, id) + assertStillFilesGone(owner, [id]) + throw createError({ statusCode: 404, statusMessage: 'Image not found' }) + } + removeStillFiles(owner, id) + assertStillFilesGone(owner, [id]) catalog.stills = catalog.stills.filter(item => item.id !== id) detachDraftStills(catalog, new Set([id])) - removeStillFiles(owner, id) pruneMissingStillMasters(owner, catalog) + assertStillFilesGone(owner, [id]) + return still + }).then((still) => { + assertStillFilesGone(owner, [id]) + invalidateCatalogCache(owner) return still }) } @@ -2003,15 +2158,27 @@ export function moveStill(owner: string, id: string, folderId: string) { } export function deleteStillFamily(owner: string, id: string) { + let ids: string[] = [] return mutate(owner, (catalog) => { const still = catalog.stills.find(item => item.id === id) - if (!still) throw createError({ statusCode: 404, statusMessage: 'Image not found' }) + if (!still) { + removeStillFiles(owner, id) + assertStillFilesGone(owner, [id]) + throw createError({ statusCode: 404, statusMessage: 'Image not found' }) + } const family = stillsInSameFamily(catalog, still) - const ids = new Set(family.map(item => item.id)) - catalog.stills = catalog.stills.filter(item => !ids.has(item.id)) - detachDraftStills(catalog, ids) + ids = family.map(item => item.id) + const idSet = new Set(ids) for (const item of family) removeStillFiles(owner, item.id) + assertStillFilesGone(owner, ids) + catalog.stills = catalog.stills.filter(item => !idSet.has(item.id)) + detachDraftStills(catalog, idSet) pruneMissingStillMasters(owner, catalog) + assertStillFilesGone(owner, ids) + return family + }).then((family) => { + assertStillFilesGone(owner, ids) + invalidateCatalogCache(owner) return family }) } diff --git a/shared/studio2/viewer.mjs b/shared/studio2/viewer.mjs index a4a0a69..41b43b2 100644 --- a/shared/studio2/viewer.mjs +++ b/shared/studio2/viewer.mjs @@ -22,22 +22,34 @@ export function folderImageCount(folder, localStillCount = 0) { return Number(localStillCount) || 0 } -/** Replace library rows from a wipe response. Rows already in the wiped folder stay gone. */ +/** Cache-bust a library media URL. Always includes v so a pre-deploy cached URL is not reused. */ +export function libraryMediaUrl(path, version) { + const base = String(path || '') + if (!base) return '' + const v = version == null || version === '' ? '0' : String(version) + const joiner = base.includes('?') ? '&' : '?' + return `${base}${joiner}v=${encodeURIComponent(v)}` +} + +/** Replace library rows from a wipe response. Does not keep a suppression list. */ export function libraryAfterWipe(previous, response, folderId) { - const suppressed = new Set(previous?.suppressedIds || []) const target = String(folderId || '') - for (const list of [previous?.stills, previous?.clips, previous?.tracks, response?.stills, response?.clips, response?.tracks]) { + const dropped = new Set(response?.deletedIds || []) + for (const list of [previous?.stills, previous?.clips, previous?.tracks]) { for (const item of list || []) { - if (item?.id && String(item.folderId || '') === target) suppressed.add(item.id) + if (item?.id && String(item.folderId || '') === target) dropped.add(item.id) } } - const take = (list) => (Array.isArray(list) ? list : []).filter(item => item?.id && !suppressed.has(item.id)) + const take = (list) => (Array.isArray(list) ? list : []).filter((item) => { + if (!item?.id || dropped.has(item.id)) return false + return String(item.folderId || '') !== target + }) return { folders: Array.isArray(response?.folders) ? response.folders : (previous?.folders || []), stills: take(response?.stills), clips: take(response?.clips), tracks: take(response?.tracks), - suppressedIds: [...suppressed] + suppressedIds: [] } } diff --git a/tests/library-delete-harden.test.mjs b/tests/library-delete-harden.test.mjs index 8632ecb..d381330 100644 --- a/tests/library-delete-harden.test.mjs +++ b/tests/library-delete-harden.test.mjs @@ -6,7 +6,15 @@ import ts from 'typescript' const source = readFileSync(new URL('../server/utils/library.ts', import.meta.url), 'utf8') const ast = ts.createSourceFile('library.ts', source, ts.ScriptTarget.Latest, true) const names = [ - 'safeRm', + 'removedEntries', + 'pathRemains', + 'stillFileRemains', + 'unlinkVerified', + 'stillIdAllowed', + 'stillArtifactPaths', + 'entryPaths', + 'assertRemovedEntries', + 'assertStillFilesGone', 'removeStillFiles', 'detachDraftStills', 'sameFolder', @@ -30,6 +38,36 @@ function harness() { const catalogEpoch = new Map() let writes = 0 let stored = null + function existsSync(path) { + const value = String(path) + if (files.has(value)) return true + const prefix = value.endsWith('/') ? value : `${value}/` + for (const file of files) { + if (String(file).startsWith(prefix)) return true + } + return false + } + function statSync(path) { + if (!existsSync(path)) { + const error = new Error('ENOENT') + error.code = 'ENOENT' + throw error + } + if (!files.has(String(path))) return { isFile: () => false, isDirectory: () => true } + return { isFile: () => true, isDirectory: () => false } + } + function readdirSync(dir) { + const prefix = String(dir).endsWith('/') ? String(dir) : `${dir}/` + const names = [] + for (const file of files) { + const value = String(file) + if (!value.startsWith(prefix)) continue + const rest = value.slice(prefix.length) + if (!rest || rest.includes('/')) continue + names.push(rest) + } + return names + } function readCatalog() { return stored } function writeCatalog(_owner, catalog) { stored = catalog === undefined ? _owner : catalog @@ -39,6 +77,11 @@ function harness() { const api = new Function( 'rmSync', 'existsSync', + 'statSync', + 'readdirSync', + 'join', + 'ownerRoot', + 'libraryRoot', 'console', 'stillPath', 'stillThumbFile', @@ -52,13 +95,22 @@ function harness() { 'writeCatalog', 'catalogEpoch', 'invalidateCatalogCache', - `${js}; return { catalogWithPrunedStills, deleteStill, deleteStillFamily, wipeFolderContents, emptyFolderRows };` + `${js}; return { catalogWithPrunedStills, deleteStill, deleteStillFamily, wipeFolderContents, emptyFolderRows, removeStillFiles };` )( (path) => { - if ([...thrown].some(id => String(path).includes(id))) throw new Error('EPERM') + if ([...thrown].some(id => String(path).includes(id))) { + const error = new Error('EPERM') + error.code = 'EPERM' + throw error + } files.delete(path) }, - (path) => files.has(path), + existsSync, + statSync, + readdirSync, + (...parts) => parts.map(part => String(part).replace(/^\/+|\/+$/g, '')).filter(Boolean).join('/'), + (owner) => owner, + () => 'legacy', console, (owner, id) => `${owner}/stills/${id}`, (owner, id) => `${owner}/stills/${id}.thumb.jpg`, @@ -89,10 +141,11 @@ function harness() { } } -test('deleteStill drops the catalog row when the file remove fails', async () => { +test('deleteStill does not write the catalog when the master file survives', async () => { const h = harness() h.thrown.add('locked') h.files.add('owner/stills/locked') + h.files.add('owner/stills/locked.thumb.jpg') const catalog = { stills: [{ id: 'locked', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }], drafts: [{ id: 'd', stillId: 'locked', stillFilename: 'locked.png' }], @@ -102,14 +155,78 @@ test('deleteStill drops the catalog row when the file remove fails', async () => } h.load(catalog) h.files.add('owner/stills/keep') - await h.api.deleteStill('owner', 'locked') + await assert.rejects(() => h.api.deleteStill('owner', 'locked'), /locked/) + assert.equal(h.writes, 0) + assert.deepEqual(catalog.stills.map(item => item.id), ['locked', 'keep']) + assert.equal(catalog.drafts[0].stillId, 'locked') + assert.equal(h.files.has('owner/stills/locked'), true) + assert.equal(h.files.has('owner/stills/keep'), true) + assert.deepEqual(h.invalidated, []) +}) + +test('deleteStill removes master, thumb, preview, siblings, and legacy names', async () => { + const h = harness() + const catalog = { + stills: [{ id: 'a', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }], + drafts: [{ id: 'd', stillId: 'a', stillFilename: 'a.png' }], + clips: [], + tracks: [], + folders: [{ id: 'inbox' }] + } + h.load(catalog) + for (const path of [ + 'owner/stills/a', + 'owner/stills/a.thumb.jpg', + 'owner/stills/a.preview.jpg', + 'owner/stills/a.extra.png', + 'legacy/files/a', + 'legacy/stills/a.thumb.jpg', + 'owner/stills/keep', + 'owner/stills/keep.thumb.jpg' + ]) h.files.add(path) + await h.api.deleteStill('owner', 'a') assert.equal(h.writes, 1) assert.deepEqual(catalog.stills.map(item => item.id), ['keep']) assert.equal(catalog.drafts[0].stillId, undefined) + for (const path of [ + 'owner/stills/a', + 'owner/stills/a.thumb.jpg', + 'owner/stills/a.preview.jpg', + 'owner/stills/a.extra.png', + 'legacy/files/a', + 'legacy/stills/a.thumb.jpg' + ]) assert.equal(h.files.has(path), false, path) + assert.equal(h.files.has('owner/stills/keep'), true) + assert.equal(h.files.has('owner/stills/keep.thumb.jpg'), true) + assert.deepEqual(h.invalidated, ['owner']) +}) + +test('deleteStill unlinks leftover files when the catalog row is already gone', async () => { + const h = harness() + const catalog = { + stills: [{ id: 'keep', folderId: 'inbox' }], + drafts: [], + clips: [], + tracks: [], + folders: [{ id: 'inbox' }] + } + h.load(catalog) + h.files.add('owner/stills/orphan') + h.files.add('owner/stills/orphan.thumb.jpg') + h.files.add('owner/stills/orphan.preview.jpg') + h.files.add('legacy/stills/orphan') + h.files.add('owner/stills/keep') + await assert.rejects(() => h.api.deleteStill('owner', 'orphan'), /Image not found/) + assert.equal(h.writes, 0) + assert.deepEqual(catalog.stills.map(item => item.id), ['keep']) + assert.equal(h.files.has('owner/stills/orphan'), false) + assert.equal(h.files.has('owner/stills/orphan.thumb.jpg'), false) + assert.equal(h.files.has('owner/stills/orphan.preview.jpg'), false) + assert.equal(h.files.has('legacy/stills/orphan'), false) assert.equal(h.files.has('owner/stills/keep'), true) }) -test('pruneMissingStillMasters runs on delete and on catalog read', async () => { +test('pruneMissingStillMasters drops the row and unlinks leftover files', async () => { const h = harness() const catalog = { stills: [{ id: 'gone', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }], @@ -120,13 +237,18 @@ test('pruneMissingStillMasters runs on delete and on catalog read', async () => } h.load(structuredClone(catalog)) h.files.add('owner/stills/keep') + h.files.add('owner/stills/gone.thumb.jpg') + h.files.add('owner/stills/gone.preview.jpg') const page = h.api.catalogWithPrunedStills('owner') assert.equal(h.writes, 1) assert.deepEqual(page.stills.map(item => item.id), ['keep']) assert.equal(page.drafts[0].stillId, undefined) + assert.equal(h.files.has('owner/stills/gone.thumb.jpg'), false) + assert.equal(h.files.has('owner/stills/gone.preview.jpg'), false) + assert.equal(h.files.has('owner/stills/keep'), true) }) -test('wipeFolderContents still clears the folder when a file remove throws', async () => { +test('wipeFolderContents throws and keeps the catalog when a file survives', async () => { const h = harness() h.thrown.add('locked') const catalog = { @@ -137,15 +259,16 @@ test('wipeFolderContents still clears the folder when a file remove throws', asy folders: [{ id: 'inbox', name: 'Inbox' }] } h.load(catalog) - const result = await h.api.wipeFolderContents('owner', 'inbox') - assert.equal(result.deleted, 2) - assert.equal(catalog.stills.length, 0) - assert.equal(catalog.clips.length, 0) - assert.equal(h.writes, 1) - assert.deepEqual(h.invalidated, ['owner']) + h.files.add('owner/stills/locked') + await assert.rejects(() => h.api.wipeFolderContents('owner', 'inbox'), /locked/) + assert.equal(h.writes, 0) + assert.equal(catalog.stills.length, 1) + assert.equal(catalog.clips.length, 1) + assert.equal(h.files.has('owner/stills/locked'), true) + assert.deepEqual(h.invalidated, []) }) -test('wipeFolderContents leaves zero rows for that folder and does not touch another folder', async () => { +test('wipeFolderContents leaves zero rows for that folder and zero files for those ids', async () => { const h = harness() const catalog = { stills: [ @@ -162,12 +285,20 @@ test('wipeFolderContents leaves zero rows for that folder and does not touch ano } h.load(catalog) h.files.add('owner/stills/a') + h.files.add('owner/stills/a.thumb.jpg') h.files.add('owner/stills/b') + h.files.add('owner/clips/c') + h.files.add('owner/tracks/t') const result = await h.api.wipeFolderContents('owner', 'inbox') assert.equal(result.deleted, 3) assert.deepEqual(catalog.stills.map(item => item.id), ['b']) assert.deepEqual(catalog.clips, []) assert.deepEqual(catalog.tracks.map(item => item.id), ['u']) + assert.equal(h.files.has('owner/stills/a'), false) + assert.equal(h.files.has('owner/stills/a.thumb.jpg'), false) + assert.equal(h.files.has('owner/clips/c'), false) + assert.equal(h.files.has('owner/tracks/t'), false) + assert.equal(h.files.has('owner/stills/b'), true) assert.deepEqual(h.invalidated, ['owner']) }) diff --git a/tests/library-media-cache.test.mjs b/tests/library-media-cache.test.mjs new file mode 100644 index 0000000..9ee4833 --- /dev/null +++ b/tests/library-media-cache.test.mjs @@ -0,0 +1,38 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = fileURLToPath(new URL('../server/api/library/', import.meta.url)) + +function walk(dir) { + const files = [] + for (const name of readdirSync(dir)) { + const path = join(dir, name) + if (statSync(path).isDirectory()) files.push(...walk(path)) + else if (name.endsWith('.ts')) files.push(path) + } + return files +} + +const media = walk(root).filter((path) => ( + /[/\\](thumb|preview|video|audio|first-frame|last-frame)\.get\.ts$/.test(path) + || /[/\\]stills[/\\]\[id\]\.get\.ts$/.test(path) + || /[/\\]drafts[/\\]\[id\][/\\]still\.get\.ts$/.test(path) +)) + +test('library media routes are uncached and do not answer 304', () => { + const helper = readFileSync(new URL('../server/utils/library.ts', import.meta.url), 'utf8') + assert.match(helper, /Cache-Control', 'no-store, no-cache, must-revalidate'/) + assert.match(helper, /Pragma', 'no-cache'/) + assert.ok(media.length >= 8, media.join('\n')) + for (const path of media) { + const source = readFileSync(path, 'utf8') + assert.match(source, /setLibraryMediaHeaders/, path) + assert.doesNotMatch(source, /304/, path) + assert.doesNotMatch(source, /if-none-match/i, path) + assert.doesNotMatch(source, /max-age=\d+/, path) + assert.doesNotMatch(source, /public, max-age/, path) + } +}) diff --git a/tests/library-wipe-state.test.mjs b/tests/library-wipe-state.test.mjs index 4c39713..07cc702 100644 --- a/tests/library-wipe-state.test.mjs +++ b/tests/library-wipe-state.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { folderImageCount, libraryAfterWipe, mergeLibraryRows, replaceLibraryRows } from '../shared/studio2/viewer.mjs' +import { folderImageCount, libraryAfterWipe, libraryMediaUrl, mergeLibraryRows, replaceLibraryRows } from '../shared/studio2/viewer.mjs' test('folderImageCount trusts a server count of 0', () => { assert.equal(folderImageCount({ id: 'inbox', imageCount: 0 }, 1762), 0) @@ -8,7 +8,14 @@ test('folderImageCount trusts a server count of 0', () => { assert.equal(folderImageCount(undefined, 3), 3) }) -test('libraryAfterWipe replaces state and does not keep wiped folder rows from a stale list', () => { +test('libraryMediaUrl always changes the pre-deploy cache key', () => { + assert.equal(libraryMediaUrl('/api/library/stills/abc/thumb', 0), '/api/library/stills/abc/thumb?v=0') + assert.equal(libraryMediaUrl('/api/library/stills/abc/preview', 4), '/api/library/stills/abc/preview?v=4') + assert.equal(libraryMediaUrl('/api/library/clips/abc/first-frame?thumb=1', 2), '/api/library/clips/abc/first-frame?thumb=1&v=2') + assert.notEqual(libraryMediaUrl('/api/library/stills/abc/thumb', 0), '/api/library/stills/abc/thumb') +}) + +test('libraryAfterWipe replaces the folder from the response and does not keep a suppression list', () => { const previous = { folders: [{ id: 'inbox', imageCount: 2 }], stills: [{ id: 'new-1', folderId: 'inbox' }, { id: 'new-2', folderId: 'inbox' }], @@ -24,16 +31,16 @@ test('libraryAfterWipe replaces state and does not keep wiped folder rows from a { id: 'kept', folderId: 'other' } ], clips: [{ id: 'clip-ghost', folderId: 'inbox' }], - tracks: [] + tracks: [], + deletedIds: ['new-1', 'new-2'] } const next = libraryAfterWipe(previous, stale, 'inbox') assert.deepEqual(next.stills.map(item => item.id), ['kept']) assert.deepEqual(next.clips, []) assert.equal(next.folders[0].imageCount, 0) - assert.equal(next.suppressedIds.includes('new-1'), true) - assert.equal(next.suppressedIds.includes('ghost'), true) - assert.equal(next.suppressedIds.includes('already-gone'), true) - const page = mergeLibraryRows(next.stills, stale.stills, next.suppressedIds) - assert.deepEqual(page.map(item => item.id), ['kept']) - assert.deepEqual(replaceLibraryRows(stale.stills, next.suppressedIds).map(item => item.id), ['kept']) + assert.deepEqual(next.suppressedIds, []) + const replaced = replaceLibraryRows(next.stills, []) + assert.deepEqual(replaced.map(item => item.id), ['kept']) + const page = mergeLibraryRows(replaced, [{ id: 'kept', folderId: 'other' }, { id: 'fresh', folderId: 'other' }], []) + assert.deepEqual(page.map(item => item.id), ['kept', 'fresh']) })