Delete library stills from disk before the catalog write, and stop caching their media.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Towsty
2026-10-25 17:55:30 -05:00
co-authored by Cursor
parent 545a3d749b
commit 20359bfbd4
26 changed files with 635 additions and 247 deletions
+6 -6
View File
@@ -135,16 +135,16 @@ const visibleSlots = computed(() => {
}) })
function frameThumb(key: SlotKey) { function frameThumb(key: SlotKey) {
if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}?thumb=1` 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` 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` if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?thumb=1&v=join&e=0`
return '' return ''
} }
function frameFull(key: SlotKey) { function frameFull(key: SlotKey) {
if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}` 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` 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` if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?v=join&e=0`
return '' return ''
} }
+1 -1
View File
@@ -95,7 +95,7 @@
> >
<div class="relative h-28 overflow-hidden bg-zinc-900"> <div class="relative h-28 overflow-hidden bg-zinc-900">
<img <img
:src="`/api/library/stills/${still.id}/thumb`" :src="`/api/library/stills/${still.id}/thumb?v=${still.createdAt || 0}`"
alt="" alt=""
loading="lazy" loading="lazy"
decoding="async" decoding="async"
+1 -1
View File
@@ -14,7 +14,7 @@
<span v-if="hidden" class="sensitive-glow block h-full w-full" /> <span v-if="hidden" class="sensitive-glow block h-full w-full" />
<img <img
v-else v-else
:src="`/api/library/stills/${item.stillId}?thumb=1`" :src="`/api/library/stills/${item.stillId}?thumb=1&v=0`"
alt="" alt=""
loading="lazy" loading="lazy"
decoding="async" decoding="async"
+1 -1
View File
@@ -240,7 +240,7 @@ const shots = computed(() => job.value ? queuedJobShots(currentPayload(), job.va
const thumbUrl = computed(() => { const thumbUrl = computed(() => {
const stillId = job.value?.payload?.stillId const stillId = job.value?.payload?.stillId
if (!stillId || job.value?.payload?.hideThumbnail || job.value?.payload?.folderLocked) return '' 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 loraLine = computed(() => loraStackLabel(draft.loraStack, loraAliases.value))
const loraEngine = computed(() => { const loraEngine = computed(() => {
+6 -4
View File
@@ -44,17 +44,19 @@
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { libraryMediaUrl } from '~/shared/studio2/viewer.mjs'
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
asset?: any asset?: any
hidden?: boolean hidden?: boolean
role: string role: string
roleOptions: { id: string; label: string }[] roleOptions: { id: string; label: string }[]
readonly?: boolean readonly?: boolean
}>(), { readonly: false, hidden: false }) version?: string | number
}>(), { readonly: false, hidden: false, version: 0 })
defineEmits(['pick', 'remove', 'mention', 'update:role']) defineEmits(['pick', 'remove', 'mention', 'update:role'])
const thumbSrc = computed(() => { const thumbSrc = computed(() => {
if (!props.asset) return '' if (!props.asset?.id) return ''
if (props.asset.kind === 'clip') return `/api/library/clips/${props.asset.id}/thumb` if (props.asset.kind === 'clip') return libraryMediaUrl(`/api/library/clips/${props.asset.id}/thumb`, props.version)
return `/api/library/stills/${props.asset.id}/thumb` return libraryMediaUrl(`/api/library/stills/${props.asset.id}/thumb`, props.version)
}) })
</script> </script>
+81 -40
View File
@@ -96,6 +96,7 @@
v-for="(card, index) in form.photos" v-for="(card, index) in form.photos"
:key="'photo-'+index+'-'+card.stillId" :key="'photo-'+index+'-'+card.stillId"
:asset="stillById(card.stillId)" :asset="stillById(card.stillId)"
:version="library.catalogEpoch || 0"
:hidden="hideInputs" :hidden="hideInputs"
:role="card.role" :role="card.role"
:role-options="photoRoleOptions" :role-options="photoRoleOptions"
@@ -316,7 +317,7 @@
v-show="!isHidden(selected)" v-show="!isHidden(selected)"
ref="viewerVideo" ref="viewerVideo"
:key="selected.id" :key="selected.id"
:src="`/api/library/clips/${selected.id}/video`" :src="clipVideoUrl(selected.id)"
:muted="viewerMuted" :muted="viewerMuted"
@timeupdate="onVideoTime" @timeupdate="onVideoTime"
@loadedmetadata="onVideoTime" @loadedmetadata="onVideoTime"
@@ -476,7 +477,7 @@
<div class="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-5"> <div class="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-5">
<button v-for="a in pickerAssets" :key="a.id" type="button" class="rounded-[var(--radius)] border border-[var(--line)] p-2 text-left" @click="pickAsset(a)"> <button v-for="a in pickerAssets" :key="a.id" type="button" class="rounded-[var(--radius)] border border-[var(--line)] p-2 text-left" @click="pickAsset(a)">
<span v-if="pickerThumbHidden(a)" class="flex h-24 items-center text-xs text-[var(--muted)]">Still loaded · preview hidden</span> <span v-if="pickerThumbHidden(a)" class="flex h-24 items-center text-xs text-[var(--muted)]">Still loaded · preview hidden</span>
<img v-else :src="a.kind==='clip'?'/api/library/clips/'+a.id+'/thumb':stillThumbUrl(a.id)" class="h-24 w-full object-contain" alt=""> <img v-else :src="a.kind==='clip'?clipThumbUrl(a.id):stillThumbUrl(a.id)" class="h-24 w-full object-contain" alt="">
<span class="mt-2 block truncate text-xs">{{ assetLabel(a) }}</span> <span class="mt-2 block truncate text-xs">{{ assetLabel(a) }}</span>
</button> </button>
</div> </div>
@@ -491,7 +492,7 @@ import {createLoraMemory,loraUse} from '~/shared/studio2/lora-memory.mjs'
import {filterLorasForStudio,filterLorasForUse} from '~/utils/loras' import {filterLorasForStudio,filterLorasForUse} from '~/utils/loras'
import {sectionsFrom} from '~/shared/studio2/contracts.mjs' import {sectionsFrom} from '~/shared/studio2/contracts.mjs'
import {aspectOptions,resolveSize,bindClip,restoreAll,useAsSource,hydrateStudio2Job} from '~/shared/studio2/input.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 {queueJobs,queueEngineLabel,jobStageLabel,jobProgressView,elapsedSeconds} from '~/shared/studio2/queue-view.mjs'
import {gpuStatus} from '~/shared/studio2/status.mjs' import {gpuStatus} from '~/shared/studio2/status.mjs'
import {CAPTION_STYLES} from '~/shared/caption.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)}) 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 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 clips=computed(()=>library.value.clips.filter((s:any)=>s.folderId===form.folderId))
const stillUrl=(id:string)=>`/api/library/stills/${id}` const mediaVersion=()=>library.value.catalogEpoch ?? 0
const stillThumbUrl=(id:string)=>`/api/library/stills/${id}/thumb` const stillUrl=(id:string)=>libraryMediaUrl(`/api/library/stills/${id}`,mediaVersion())
const stillPreviewUrl=(id:string)=>`/api/library/stills/${id}/preview` 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. */ /** Stage uses /preview (1600px). Tiles keep /thumb. Never auto-upgrade to the archive master. */
const stagePreviewNonce=ref(0) const stagePreviewNonce=ref(0)
const stagePreviewRetries=ref(0) const stagePreviewRetries=ref(0)
@@ -931,7 +935,7 @@ const stagePreviewSrc=computed(()=>{
const id=selected.value?.id const id=selected.value?.id
if(!id || selected.value?.kind==='clip' || selected.value?.kind==='track') return '' if(!id || selected.value?.kind==='clip' || selected.value?.kind==='track') return ''
const base=stillPreviewUrl(id) const base=stillPreviewUrl(id)
return stagePreviewNonce.value?`${base}?t=${stagePreviewNonce.value}`:base return stagePreviewNonce.value?`${base}&t=${stagePreviewNonce.value}`:base
}) })
function onStagePreviewError(){ function onStagePreviewError(){
if(!selected.value?.id || stagePreviewRetries.value>=8) return if(!selected.value?.id || stagePreviewRetries.value>=8) return
@@ -982,10 +986,7 @@ const showSelectedStill=computed(()=>{
const item=selected.value const item=selected.value
if(!item?.id || item.kind==='clip' || item.kind==='track') return false if(!item?.id || item.kind==='clip' || item.kind==='track') return false
if(forgottenStillIds.value.has(item.id)) return false if(forgottenStillIds.value.has(item.id)) return false
if((library.value.stills||[]).some((s:any)=>s.id===item.id)) return true return (library.value.stills||[]).some((s:any)=>s.id===item.id)
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
}) })
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 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) const sourceSize=computed(()=>measured[sourceAsset.value?.id] || sourceAsset.value)
@@ -1133,6 +1134,30 @@ function clearFormSlots(ids:string[]){
selectionPinned.value=false 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. */ /** Photos array is source of truth — never resurrect cards from leftover imageAId. */
function syncPhotosBindings(){ function syncPhotosBindings(){
const filled=(form.photos||[]).filter((p:any)=>p?.stillId) const filled=(form.photos||[]).filter((p:any)=>p?.stillId)
@@ -1495,6 +1520,7 @@ async function deleteOutput(explicit?:any){
return return
} }
} }
seenOutputs.add(id)
forgottenStillIds.value=new Set([...forgottenStillIds.value,id]) forgottenStillIds.value=new Set([...forgottenStillIds.value,id])
clearFormSlots([id]) clearFormSlots([id])
library.value={ library.value={
@@ -1503,9 +1529,13 @@ async function deleteOutput(explicit?:any){
clips:(library.value.clips||[]).filter((c:any)=>c.id!==id), clips:(library.value.clips||[]).filter((c:any)=>c.id!==id),
tracks:(library.value.tracks||[]).filter((t:any)=>t.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 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() await refreshJobs()
} }
function stepFamily(delta:number){ function stepFamily(delta:number){
@@ -1549,19 +1579,24 @@ function onLibraryDelete(item:any){
} }
function onLibraryWiped(result:any){ function onLibraryWiped(result:any){
const folderId=String(result?.folderId||form.folderId||'') 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({ const next=libraryAfterWipe({
folders:library.value.folders, folders:library.value.folders,
stills:library.value.stills, stills:library.value.stills,
clips:library.value.clips, clips:library.value.clips,
tracks:library.value.tracks, tracks:library.value.tracks,
suppressedIds:[...forgottenStillIds.value] suppressedIds:[]
}, result, folderId) }, result, folderId)
forgottenStillIds.value=new Set(next.suppressedIds) forgottenStillIds.value=new Set(deleted)
clearFormSlots(next.suppressedIds) clearFormSlots(deleted)
if(selected.value && (forgottenStillIds.value.has(selected.value.id) || String(selected.value.folderId||'')===folderId)){
selected.value=null selected.value=null
selectionPinned.value=false selectionPinned.value=false
}
library.value={ library.value={
...library.value, ...library.value,
folders:next.folders, folders:next.folders,
@@ -1571,10 +1606,12 @@ function onLibraryWiped(result:any){
drafts:result?.drafts||[], drafts:result?.drafts||[],
loraAliases:result?.loraAliases||library.value.loraAliases||{}, loraAliases:result?.loraAliases||library.value.loraAliases||{},
loraTriggers:result?.loraTriggers||library.value.loraTriggers||{}, 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 libraryRefreshKey.value+=1
void loadLibraryOnce() void loadLibraryOnce(deleted).finally(()=>{forgottenStillIds.value=new Set()})
} }
function onStageHotkey(e:KeyboardEvent){ function onStageHotkey(e:KeyboardEvent){
if(e.metaKey||e.ctrlKey||e.altKey)return if(e.metaKey||e.ctrlKey||e.altKey)return
@@ -1714,7 +1751,7 @@ watch(()=>sourceAsset.value?.id,id=>{
media.addEventListener('loadedmetadata',()=>{ media.addEventListener('loadedmetadata',()=>{
measured[asset.id]={width:media.videoWidth,height:media.videoHeight} measured[asset.id]={width:media.videoWidth,height:media.videoHeight}
},{once:true}) },{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}) watch(()=>selected.value?.id,()=>{videoTime.value=0;videoDuration.value=0})
@@ -2013,50 +2050,51 @@ async function cancel(job:any){
} }
let libraryLoadGen=0 let libraryLoadGen=0
async function loadLibraryOnce(){ async function loadLibraryOnce(deletedIds?: string[]){
// Current folder page only — never the yearly Inbox JSON on / // 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 gen=++libraryLoadGen
const qs=new URLSearchParams({limit:'50'}) const qs=new URLSearchParams({limit:'50'})
if(form.folderId) qs.set('folderId',form.folderId) if(form.folderId) qs.set('folderId',form.folderId)
qs.set('_',String(Date.now())) qs.set('_',String(Date.now()))
const page=await $fetch<any>(`/api/library?${qs.toString()}`) const page=await $fetch<any>(`/api/library?${qs.toString()}`)
if(gen!==libraryLoadGen) return 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 forget=forgottenStillIds.value
const keepIds=[ const keepIds=[
...(form.photos||[]).map((p:any)=>p?.stillId).filter(Boolean), ...(form.photos||[]).map((p:any)=>p?.stillId).filter(Boolean),
form.imageAId,form.imageBId,form.identityStillId,form.maskId,form.endStillId, form.imageAId,form.imageBId,form.identityStillId,form.maskId,form.endStillId,
...(form.guides||[]).map((g:any)=>g?.stillId).filter(Boolean) ...(form.guides||[]).map((g:any)=>g?.stillId).filter(Boolean)
].filter((id:string)=>id&&!forget.has(id)) as string[] ].filter((id:string)=>id&&!forget.has(id)&&!gone.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)) 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=>!forget.has(id)&&!pageStills.some((s:any)=>s.id===id)&&!kept.some((s:any)=>s.id===id)) const stillMissing=keepIds.filter(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 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){ if(stillMissing.length){
try{ try{
const full=await $fetch<any>(`/api/library?light=1&_=${Date.now()}`) const full=await $fetch<any>(`/api/library?light=1&_=${Date.now()}`)
if(gen!==libraryLoadGen) return 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))] 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 if(gen!==libraryLoadGen) return
library.value={ library.value={
folders:page.folders||library.value.folders||[], folders:page.folders||library.value.folders||[],
stills:[...pageStills,...kept].filter((s:any)=>!forget.has(s.id)), stills:[...pageStills,...kept].filter((s:any)=>s?.id&&!forget.has(s.id)&&!gone.has(s.id)),
clips:(page.clips||[]).filter((c:any)=>!forget.has(c.id)), clips:(page.clips||[]).filter((c:any)=>c?.id&&!forget.has(c.id)&&!gone.has(c.id)),
tracks:(page.tracks||[]).filter((t:any)=>!forget.has(t.id)), tracks:(page.tracks||[]).filter((t:any)=>t?.id&&!forget.has(t.id)&&!gone.has(t.id)),
drafts:page.drafts||library.value.drafts||[], drafts:page.drafts||library.value.drafts||[],
loraAliases:page.loraAliases||library.value.loraAliases||{}, loraAliases:page.loraAliases||library.value.loraAliases||{},
loraTriggers:page.loraTriggers||library.value.loraTriggers||{}, 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] clearRefsMissingFromLibrary()
// 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()
} }
async function fetchHealth(){ async function fetchHealth(){
@@ -2098,6 +2136,7 @@ onMounted(()=>{
// Folder page in background — never blocks Generate / prompt // Folder page in background — never blocks Generate / prompt
void loadLibraryOnce().then(()=>{ void loadLibraryOnce().then(()=>{
restoreBenchDraft() restoreBenchDraft()
clearRefsMissingFromLibrary()
if(!form.folderId)form.folderId=library.value.folders[0]?.id||'' if(!form.folderId)form.folderId=library.value.folders[0]?.id||''
loadRevealed(form.folderId) loadRevealed(form.folderId)
void applyIncomingGenerationLoad() void applyIncomingGenerationLoad()
@@ -2159,6 +2198,8 @@ const mobileCtx=computed(()=>({
libraryRefreshKey:libraryRefreshKey.value, libraryRefreshKey:libraryRefreshKey.value,
family:family.value, family:family.value,
familyStillCount:familyStillCount.value, familyStillCount:familyStillCount.value,
clipThumbUrl,
clipVideoUrl,
showSelectedStill:showSelectedStill.value, showSelectedStill:showSelectedStill.value,
libraryOpen:libraryOpen.value, libraryOpen:libraryOpen.value,
eyeOpen:eyeOpen.value, eyeOpen:eyeOpen.value,
+29 -21
View File
@@ -154,7 +154,7 @@ import {
type LibraryTrack type LibraryTrack
} from '~/utils/libraryBrowse' } from '~/utils/libraryBrowse'
import { clipSettingsRows, stillSettingsRows, trackSettingsRows } from '~/utils/libraryGeneration' 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<{ const props = defineProps<{
open: boolean open: boolean
@@ -201,7 +201,7 @@ const tracks = ref<LibraryTrack[]>([])
const fetchedAt = ref(0) const fetchedAt = ref(0)
const nextCursor = ref<string | null>(null) const nextCursor = ref<string | null>(null)
const liveThumbs = ref(new Set<string>()) const liveThumbs = ref(new Set<string>())
const suppressedDeletedIds = ref(new Set<string>()) const catalogEpoch = ref(0)
const wipeBusy = ref(false) const wipeBusy = ref(false)
const pendingWipe = ref<{ folderId: string; name: string; count: number } | null>(null) const pendingWipe = ref<{ folderId: string; name: string; count: number } | null>(null)
let thumbObserver: IntersectionObserver | null = null let thumbObserver: IntersectionObserver | null = null
@@ -252,9 +252,14 @@ const detailRows = computed(() => {
}) })
function thumbSrc(entry: LibraryEntry) { 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.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 '' return ''
} }
@@ -289,10 +294,6 @@ function useAndClose() {
close() close()
} }
function dropIds() {
return new Set([...(props.hiddenIds || []), ...suppressedDeletedIds.value])
}
function onDeleteClick() { function onDeleteClick() {
const asset = detailAsset.value const asset = detailAsset.value
if (!asset?.id) return if (!asset?.id) return
@@ -301,15 +302,16 @@ function onDeleteClick() {
function applyLibraryPage(data: any, replace: boolean) { function applyLibraryPage(data: any, replace: boolean) {
if (Array.isArray(data?.folders) && data.folders.length) folders.value = data.folders 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) { if (replace) {
clips.value = replaceLibraryRows(data?.clips || [], drop) as LibraryClip[] clips.value = rows(data?.clips) as LibraryClip[]
stills.value = replaceLibraryRows(data?.stills || [], drop) as LibraryStill[] stills.value = rows(data?.stills) as LibraryStill[]
tracks.value = replaceLibraryRows(data?.tracks || [], drop) as LibraryTrack[] tracks.value = rows(data?.tracks) as LibraryTrack[]
} else { } else {
clips.value = mergeLibraryRows(clips.value, data?.clips || [], drop) as LibraryClip[] clips.value = mergeLibraryRows(clips.value, data?.clips || [], []) as LibraryClip[]
stills.value = mergeLibraryRows(stills.value, data?.stills || [], drop) as LibraryStill[] stills.value = mergeLibraryRows(stills.value, data?.stills || [], []) as LibraryStill[]
tracks.value = mergeLibraryRows(tracks.value, data?.tracks || [], drop) as LibraryTrack[] tracks.value = mergeLibraryRows(tracks.value, data?.tracks || [], []) as LibraryTrack[]
} }
nextCursor.value = data?.nextCursor ?? null nextCursor.value = data?.nextCursor ?? null
fetchedAt.value = Date.now() fetchedAt.value = Date.now()
@@ -337,9 +339,6 @@ async function confirmWipeFolder() {
...clips.value.filter(item => item.folderId === pending.folderId).map(item => item.id), ...clips.value.filter(item => item.folderId === pending.folderId).map(item => item.id),
...tracks.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) stills.value = stills.value.filter(item => item.folderId !== pending.folderId)
clips.value = clips.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) 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 }))], stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))],
clips: clips.value, clips: clips.value,
tracks: tracks.value, tracks: tracks.value,
suppressedIds: [...suppressedDeletedIds.value] suppressedIds: []
}, result, pending.folderId) }, result, pending.folderId)
suppressedDeletedIds.value = new Set(next.suppressedIds) if (typeof result?.catalogEpoch === 'number') catalogEpoch.value = result.catalogEpoch
folders.value = next.folders folders.value = next.folders
stills.value = next.stills as LibraryStill[] stills.value = next.stills as LibraryStill[]
clips.value = next.clips as LibraryClip[] clips.value = next.clips as LibraryClip[]
tracks.value = next.tracks as LibraryTrack[] tracks.value = next.tracks as LibraryTrack[]
nextCursor.value = null nextCursor.value = null
fetchedAt.value = 0 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) await fetchLibrary(true)
} catch (e: any) { } catch (e: any) {
loadError.value = e?.data?.statusMessage || e?.message || 'Could not empty that folder' loadError.value = e?.data?.statusMessage || e?.message || 'Could not empty that folder'
@@ -500,9 +499,18 @@ watch([filter, activeFolderId], () => {
watch(() => props.refreshKey, () => { watch(() => props.refreshKey, () => {
if (!props.open) return if (!props.open) return
fetchGen += 1
void fetchLibrary(true) 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(() => { onBeforeUnmount(() => {
if (import.meta.client) { if (import.meta.client) {
document.body.style.overflow = '' document.body.style.overflow = ''
+1 -1
View File
@@ -120,7 +120,7 @@
v-else-if="ctx.selected?.kind==='clip'" v-else-if="ctx.selected?.kind==='clip'"
v-show="!ctx.isHidden(ctx.selected)" v-show="!ctx.isHidden(ctx.selected)"
:key="ctx.selected.id" :key="ctx.selected.id"
:src="`/api/library/clips/${ctx.selected.id}/video`" :src="ctx.clipVideoUrl(ctx.selected.id)"
controls controls
playsinline playsinline
/> />
+57 -41
View File
@@ -556,7 +556,7 @@ import {
type LibraryStill, type LibraryStill,
type LibraryTrack type LibraryTrack
} from '~/utils/libraryBrowse' } 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 { isXaigenStudio } from '~/utils/videoModels'
import { clipSettingsRows, stillSettingsRows, trackSettingsRows } from '~/utils/libraryGeneration' 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 pendingWipe = ref<{ folderId: string; name: string; count: number } | null>(null)
const wipeBusy = ref(false) const wipeBusy = ref(false)
const libraryLoading = ref(false) const libraryLoading = ref(false)
const suppressedDeletedIds = ref(new Set<string>()) const catalogEpoch = ref(0)
const keepingInputBusy = ref(false) const keepingInputBusy = ref(false)
const toasts = ref<Array<{ id: number; message: string }>>([]) const toasts = ref<Array<{ id: number; message: string }>>([])
let toastId = 0 let toastId = 0
@@ -711,12 +711,13 @@ const visibleEntries = computed(() => {
const previewVideo = computed(() => { const previewVideo = computed(() => {
if (focused.value?.kind !== 'clip' || !focused.value.group) return '' if (focused.value?.kind !== 'clip' || !focused.value.group) return ''
const id = focusedPartId.value || focused.value.group.head.id 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(() => { const previewStillSrc = computed(() => {
if (focused.value?.kind !== 'still' || !focused.value.stillGroup) return '' if (focused.value?.kind !== 'still' || !focused.value.stillGroup) return ''
const id = focusedPartId.value || focused.value.stillGroup.head.id 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(() => { const previewAudio = computed(() => {
if (focused.value?.kind !== 'track' || !focused.value.track) return '' if (focused.value?.kind !== 'track' || !focused.value.track) return ''
@@ -777,14 +778,14 @@ const detailMeta = computed(() => {
const downloadHref = computed(() => { const downloadHref = computed(() => {
if (focused.value?.kind === 'clip' && focused.value.group) { if (focused.value?.kind === 'clip' && focused.value.group) {
const id = focusedPartId.value || focused.value.group.head.id 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) { 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) { if (focused.value?.stillGroup) {
const id = focusedPartId.value || focused.value.stillGroup.head.id const id = focusedPartId.value || focused.value.stillGroup.head.id
return `/api/library/stills/${id}` return libraryMediaUrl(`/api/library/stills/${id}`, catalogEpoch.value)
} }
return '' return ''
}) })
@@ -809,6 +810,7 @@ function applyLibrary(data: unknown, opts?: { replace?: boolean }) {
tracks?: LibraryTrack[] tracks?: LibraryTrack[]
nextCursor?: string | null nextCursor?: string | null
hasMore?: boolean hasMore?: boolean
catalogEpoch?: number
} }
if (payload.id && !payload.folders && !payload.clips && !payload.stills && !payload.tracks) { if (payload.id && !payload.folders && !payload.clips && !payload.stills && !payload.tracks) {
if (typeof payload.hideInput === 'boolean') { if (typeof payload.hideInput === 'boolean') {
@@ -822,15 +824,16 @@ function applyLibrary(data: unknown, opts?: { replace?: boolean }) {
return return
} }
if (payload.folders?.length) folders.value = payload.folders if (payload.folders?.length) folders.value = payload.folders
const drop = [...suppressedDeletedIds.value] if (typeof payload.catalogEpoch === 'number') catalogEpoch.value = payload.catalogEpoch
const rows = <T,>(list: T[] | undefined) => (Array.isArray(list) ? list : []).filter(item => (item as { id?: string })?.id)
if (replace) { if (replace) {
clips.value = replaceLibraryRows(payload.clips || [], drop) clips.value = rows(payload.clips)
stills.value = replaceLibraryRows(payload.stills || [], drop) stills.value = rows(payload.stills)
tracks.value = replaceLibraryRows(payload.tracks || [], drop) tracks.value = rows(payload.tracks)
} else { } else {
clips.value = mergeLibraryRows(clips.value, payload.clips || [], drop) clips.value = mergeLibraryRows(clips.value, payload.clips || [], [])
stills.value = mergeLibraryRows(stills.value, payload.stills || [], drop) stills.value = mergeLibraryRows(stills.value, payload.stills || [], [])
tracks.value = mergeLibraryRows(tracks.value, payload.tracks || [], drop) tracks.value = mergeLibraryRows(tracks.value, payload.tracks || [], [])
} }
libraryNextCursor.value = payload.nextCursor || null libraryNextCursor.value = payload.nextCursor || null
if (folderId.value !== 'all' && !folders.value.some(folder => folder.id === folderId.value)) { if (folderId.value !== 'all' && !folders.value.some(folder => folder.id === folderId.value)) {
@@ -948,9 +951,14 @@ async function toggleFocusedHidden() {
} }
function thumbSrc(entry: LibraryEntry) { 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.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 '' return ''
} }
@@ -974,9 +982,9 @@ function partThumb(part: LibraryClip | LibraryStill) {
if ('hideThumbnail' in part && !('role' in part)) { if ('hideThumbnail' in part && !('role' in part)) {
const clip = part as LibraryClip const clip = part as LibraryClip
// Prefer this clip’s first frame so siblings don’t all look like the Start thumb. // 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) { function focusPart(id: string) {
@@ -1032,16 +1040,11 @@ function entryPartIds(entry: LibraryEntry) {
} }
async function selectAll() { 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() const start = Date.now()
while (libraryLoading.value && Date.now() - start < 15000) { while (libraryLoading.value && Date.now() - start < 15000) {
await new Promise(resolve => setTimeout(resolve, 40)) await new Promise(resolve => setTimeout(resolve, 40))
} }
const drop = suppressedDeletedIds.value selectedKeys.value = entries.value.map(entry => entry.key)
selectedKeys.value = entries.value
.filter(entry => entryPartIds(entry).every(id => !drop.has(id)))
.map(entry => entry.key)
lastSelectedKey.value = selectedKeys.value.at(-1) || '' 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 if (!ids.length) return
const next = new Set(suppressedDeletedIds.value) const gone = new Set(ids)
for (const id of ids) next.add(id) stills.value = stills.value.filter(item => !gone.has(item.id))
suppressedDeletedIds.value = next clips.value = clips.value.filter(item => !gone.has(item.id))
stills.value = stills.value.filter(item => !next.has(item.id)) tracks.value = tracks.value.filter(item => !gone.has(item.id))
clips.value = clips.value.filter(item => !next.has(item.id))
tracks.value = tracks.value.filter(item => !next.has(item.id))
} }
async function confirmDelete() { async function confirmDelete() {
@@ -1309,13 +1310,8 @@ async function confirmDelete() {
for (const part of entry.stillGroup.parts || [entry.stillGroup.head]) gone.push(part.id) for (const part of entry.stillGroup.parts || [entry.stillGroup.head]) gone.push(part.id)
} }
} }
markDeletedIds(gone) libraryFetchGen += 1
if (pending.keys.includes(focusedKey.value)) { const results = await Promise.allSettled(items.map((entry) => {
focusedKey.value = ''
focusedPartId.value = ''
}
clearSelection()
await Promise.allSettled(items.map((entry) => {
if (entry.kind === 'clip') { if (entry.kind === 'clip') {
return $fetch(`/api/library/clips/${entry.group!.head.id}`, { method: 'DELETE', query: { family: '1' } }) 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' } }) 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() await loadLibrary()
} finally { } finally {
deleteBusy.value = false deleteBusy.value = false
@@ -1356,7 +1373,6 @@ async function confirmWipeFolder() {
...clips.value.filter(item => item.folderId === pending.folderId).map(item => item.id), ...clips.value.filter(item => item.folderId === pending.folderId).map(item => item.id),
...tracks.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() clearSelection()
clearFocus() clearFocus()
try { try {
@@ -1366,9 +1382,9 @@ async function confirmWipeFolder() {
stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))], stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))],
clips: clips.value, clips: clips.value,
tracks: tracks.value, tracks: tracks.value,
suppressedIds: [...suppressedDeletedIds.value] suppressedIds: []
}, result, pending.folderId) }, result, pending.folderId)
suppressedDeletedIds.value = new Set(next.suppressedIds) if (typeof result?.catalogEpoch === 'number') catalogEpoch.value = result.catalogEpoch
folders.value = next.folders folders.value = next.folders
stills.value = next.stills stills.value = next.stills
clips.value = next.clips clips.value = next.clips
+8 -8
View File
@@ -1786,7 +1786,7 @@
@click="openClip(entry.group.head)" @click="openClip(entry.group.head)"
> >
<span v-if="entry.group.head.hideThumbnail" class="sensitive-glow block h-full w-full" /> <span v-if="entry.group.head.hideThumbnail" class="sensitive-glow block h-full w-full" />
<img v-else :src="`/api/library/clips/${entry.group.head.id}/thumb`" alt="" loading="lazy" decoding="async" class="h-full w-full object-cover"> <img v-else :src="`/api/library/clips/${entry.group.head.id}/thumb?v=0`" alt="" loading="lazy" decoding="async" class="h-full w-full object-cover">
</button> </button>
<div class="min-w-0 flex-1"> <div class="min-w-0 flex-1">
<div class="flex items-start gap-2"> <div class="flex items-start gap-2">
@@ -2001,7 +2001,7 @@
<span v-if="entry.stillGroup.head.hideInput" class="sensitive-glow block h-full w-full" /> <span v-if="entry.stillGroup.head.hideInput" class="sensitive-glow block h-full w-full" />
<img <img
v-else v-else
:src="`/api/library/stills/${entry.stillGroup.head.id}?thumb=1`" :src="`/api/library/stills/${entry.stillGroup.head.id}?thumb=1&v=0`"
alt="" alt=""
loading="lazy" loading="lazy"
decoding="async" decoding="async"
@@ -2092,7 +2092,7 @@
> >
<button type="button" class="relative h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-zinc-900" @click="openStill(item)"> <button type="button" class="relative h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-zinc-900" @click="openStill(item)">
<span v-if="item.hideInput" class="sensitive-glow block h-full w-full" /> <span v-if="item.hideInput" class="sensitive-glow block h-full w-full" />
<img v-else :src="`/api/library/stills/${item.id}?thumb=1`" alt="" loading="lazy" decoding="async" class="h-full w-full object-cover"> <img v-else :src="`/api/library/stills/${item.id}?thumb=1&v=0`" alt="" loading="lazy" decoding="async" class="h-full w-full object-cover">
</button> </button>
<div class="min-w-0 flex-1"> <div class="min-w-0 flex-1">
<div class="flex items-start gap-2"> <div class="flex items-start gap-2">
@@ -5981,10 +5981,10 @@ function stepOutput(delta: number) {
} }
function showOutputStill(still: LibraryStill) { function showOutputStill(still: LibraryStill) {
editResultUrl.value = `/api/library/stills/${still.id}` editResultUrl.value = `/api/library/stills/${still.id}?v=0`
lastV2StillId.value = still.id lastV2StillId.value = still.id
editDownloadName.value = clipFileName(stillTitle(still)) 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) { function stepOutputFamily(delta: number) {
@@ -6514,7 +6514,7 @@ function openStill(still: LibraryStill) {
// Preview only — never yank Video/Image workspace tabs. // Preview only — never yank Video/Image workspace tabs.
outputFocus.value = 'edit' outputFocus.value = 'edit'
browseFolderId.value = still.folderId 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 concealEditOutput.value = still.hideInput === true
editAwaitingReveal.value = still.hideInput === true editAwaitingReveal.value = still.hideInput === true
editLockedSave.value = false editLockedSave.value = false
@@ -7907,7 +7907,7 @@ function applyEditEvent(payload: Record<string, any>, hidden: boolean, folderLoc
: (folderLocked || payload.folderLocked === true) : (folderLocked || payload.folderLocked === true)
if (payload.stillId && !locked) { 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 if (studioMode.value === 'editv2' || v2JobPending.value) lastV2StillId.value = payload.stillId
editLockedSave.value = false editLockedSave.value = false
if (payload.hideThumbnail || hidden) { if (payload.hideThumbnail || hidden) {
@@ -7951,7 +7951,7 @@ function applyEditEvent(payload: Record<string, any>, hidden: boolean, folderLoc
browseFolderId.value = folderId.value browseFolderId.value = folderId.value
editStatusMessage.value = 'Saved to the locked folder. Unlock it to view.' editStatusMessage.value = 'Saved to the locked folder. Unlock it to view.'
} else { } 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 if (studioMode.value === 'editv2' || v2JobPending.value) lastV2StillId.value = payload.stillId
concealEditOutput.value = Boolean(payload.hideThumbnail || hidden) concealEditOutput.value = Boolean(payload.hideThumbnail || hidden)
editAwaitingReveal.value = concealEditOutput.value editAwaitingReveal.value = concealEditOutput.value
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs' 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) => { export default defineEventHandler(async (event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const clip = getClip(owner, id) const clip = getClip(owner, id)
@@ -25,13 +26,6 @@ export default defineEventHandler(async (event) => {
if (thumbPath && existsSync(thumbPath)) path = thumbPath 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)) setHeader(event, 'Content-Type', wantThumb && path !== framePath ? 'image/jpeg' : sniffImageType(path))
return sendStream(event, createReadStream(path)) return sendStream(event, createReadStream(path))
}) })
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs' 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) => { export default defineEventHandler(async (event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const clip = getClip(owner, id) const clip = getClip(owner, id)
@@ -25,13 +26,6 @@ export default defineEventHandler(async (event) => {
if (thumbPath && existsSync(thumbPath)) path = thumbPath 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)) setHeader(event, 'Content-Type', wantThumb && path !== framePath ? 'image/jpeg' : sniffImageType(path))
return sendStream(event, createReadStream(path)) return sendStream(event, createReadStream(path))
}) })
+2 -8
View File
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs' 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) => { export default defineEventHandler(async (event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const clip = getClip(owner, id) const clip = getClip(owner, id)
@@ -11,13 +12,6 @@ export default defineEventHandler(async (event) => {
if (!path || !existsSync(path)) { if (!path || !existsSync(path)) {
throw createError({ statusCode: 404, statusMessage: 'Thumbnail not found' }) 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)) setHeader(event, 'Content-Type', sniffImageType(path))
return sendStream(event, createReadStream(path)) return sendStream(event, createReadStream(path))
}) })
+4 -1
View File
@@ -1,8 +1,10 @@
import { existsSync } from 'node:fs' import { existsSync } from 'node:fs'
import { sendPathWithRange } from '~/server/utils/httpRange' import { sendPathWithRange } from '~/server/utils/httpRange'
import { setLibraryMediaHeaders } from '~/server/utils/library'
import { inlineFilename } from '~/shared/content-disposition.mjs' import { inlineFilename } from '~/shared/content-disposition.mjs'
export default defineEventHandler((event) => { export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const clip = getClip(owner, id) const clip = getClip(owner, id)
@@ -13,6 +15,7 @@ export default defineEventHandler((event) => {
} }
return sendPathWithRange(event, path, 'video/mp4', { return sendPathWithRange(event, path, 'video/mp4', {
'Content-Disposition': inlineFilename(`${safeDownloadName(clipTitle(clip))}.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'
}) })
}) })
+2 -1
View File
@@ -1,6 +1,8 @@
import { existsSync, readFileSync } from 'node:fs' import { existsSync, readFileSync } from 'node:fs'
import { setLibraryMediaHeaders } from '~/server/utils/library'
export default defineEventHandler((event) => { export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const draft = getRetryDraft(owner, id) const draft = getRetryDraft(owner, id)
@@ -14,6 +16,5 @@ export default defineEventHandler((event) => {
} }
const buf = readFileSync(path) const buf = readFileSync(path)
setHeader(event, 'Content-Type', imageContentType(buf)) setHeader(event, 'Content-Type', imageContentType(buf))
setHeader(event, 'Cache-Control', 'private, max-age=3600')
return buf return buf
}) })
+2 -1
View File
@@ -1,6 +1,7 @@
import { publicLibrary, publicLibraryPage } from '~/server/utils/library' import { publicLibrary, publicLibraryPage, setLibraryMediaHeaders } from '~/server/utils/library'
export default defineEventHandler((event) => { export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const query = getQuery(event) const query = getQuery(event)
const light = String(query.light || '') === '1' const light = String(query.light || '') === '1'
const full = String(query.full || '') === '1' const full = String(query.full || '') === '1'
+2 -16
View File
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs' 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) => { export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const still = getStill(owner, id) const still = getStill(owner, id)
@@ -12,18 +13,10 @@ export default defineEventHandler((event) => {
if (wantThumb) { if (wantThumb) {
const path = existingStillThumbPath(owner, id) const path = existingStillThumbPath(owner, id)
if (path && path !== original && existsSync(path)) { 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') setHeader(event, 'Content-Type', 'image/jpeg')
return sendStream(event, createReadStream(path)) return sendStream(event, createReadStream(path))
} }
void stillThumbPath(owner, id).catch(() => null) void stillThumbPath(owner, id).catch(() => null)
setHeader(event, 'Cache-Control', 'no-store')
setResponseStatus(event, 204) setResponseStatus(event, 204)
return null return null
} }
@@ -32,13 +25,6 @@ export default defineEventHandler((event) => {
throw createError({ statusCode: 404, statusMessage: 'Image file is missing' }) 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)) setHeader(event, 'Content-Type', sniffImageType(original))
return sendStream(event, createReadStream(original)) return sendStream(event, createReadStream(original))
}) })
+2 -10
View File
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs' 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) => { export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const still = getStill(owner, id) const still = getStill(owner, id)
@@ -11,20 +12,11 @@ export default defineEventHandler((event) => {
const original = stillPath(owner, still.id) const original = stillPath(owner, still.id)
// Ready preview → stream. Never await ffmpeg; never stream the archive master. // Ready preview → stream. Never await ffmpeg; never stream the archive master.
if (path && existsSync(path) && path !== original) { 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') setHeader(event, 'Content-Type', 'image/jpeg')
return sendStream(event, createReadStream(path)) return sendStream(event, createReadStream(path))
} }
// Missing → answer now; build .preview.jpg in the background
void stillPreviewPath(owner, id).catch(() => null) void stillPreviewPath(owner, id).catch(() => null)
setHeader(event, 'Cache-Control', 'no-store')
setResponseStatus(event, 204) setResponseStatus(event, 204)
return null return null
}) })
+3 -10
View File
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs' 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) => { export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const still = getStill(owner, id) const still = getStill(owner, id)
@@ -10,21 +11,13 @@ export default defineEventHandler((event) => {
const path = existingStillThumbPath(owner, id) const path = existingStillThumbPath(owner, id)
const original = stillPath(owner, still.id) const original = stillPath(owner, still.id)
// Ready thumb → stream. Never await ffmpeg on the request path. // 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) { 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') setHeader(event, 'Content-Type', 'image/jpeg')
return sendStream(event, createReadStream(path)) 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) void stillThumbPath(owner, id).catch(() => null)
setHeader(event, 'Cache-Control', 'no-store')
setResponseStatus(event, 204) setResponseStatus(event, 204)
return null return null
}) })
+4 -1
View File
@@ -1,8 +1,10 @@
import { existsSync } from 'node:fs' import { existsSync } from 'node:fs'
import { sendPathWithRange } from '~/server/utils/httpRange' import { sendPathWithRange } from '~/server/utils/httpRange'
import { setLibraryMediaHeaders } from '~/server/utils/library'
import { musicContentType } from '~/utils/music' import { musicContentType } from '~/utils/music'
export default defineEventHandler((event) => { export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event) const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '') const id = String(getRouterParam(event, 'id') || '')
const track = getTrack(owner, id) const track = getTrack(owner, id)
@@ -14,6 +16,7 @@ export default defineEventHandler((event) => {
const ext = track.ext || 'flac' const ext = track.ext || 'flac'
return sendPathWithRange(event, path, musicContentType(ext), { return sendPathWithRange(event, path, musicContentType(ext), {
'Content-Disposition': `inline; filename="${safeDownloadName(track.name)}.${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'
}) })
}) })
+5
View File
@@ -8,5 +8,10 @@ export default defineEventHandler((event) => {
} }
if (path.startsWith('/api/prompt/')) { if (path.startsWith('/api/prompt/')) {
setHeader(event, 'Cache-Control', 'no-cache, no-store, no-transform') 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')
} }
}) })
+194 -27
View File
@@ -6,7 +6,7 @@ import { join } from 'node:path'
import { spawn } from 'node:child_process' import { spawn } from 'node:child_process'
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto' import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
import { promisify } from 'node:util' 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 { extractFirstFrame, extractFrameAt, extractLastFrame, probeDuration, remuxFaststart } from '~/server/utils/ffmpeg'
import { normalizePermanenceRefs, type PermanenceRef } from '~/utils/globalLocks' import { normalizePermanenceRefs, type PermanenceRef } from '~/utils/globalLocks'
import { normalizeStillSettings, type StillGenerationSettings } from '~/utils/libraryGeneration' import { normalizeStillSettings, type StillGenerationSettings } from '~/utils/libraryGeneration'
@@ -416,8 +416,22 @@ function writeCatalog(owner: string, catalog: Catalog) {
} }
export function invalidateCatalogCache(owner?: string) { export function invalidateCatalogCache(owner?: string) {
if (owner) catalogCache.delete(owner) // Bump the epoch so a read that already parsed pre-wipe bytes cannot
else catalogCache.clear() // 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<T>(owner: string, fn: (catalog: Catalog) => T): Promise<T> { function mutate<T>(owner: string, fn: (catalog: Catalog) => T): Promise<T> {
@@ -656,7 +670,8 @@ export function publicLibrary(event: H3Event, opts?: { light?: boolean }) {
drafts: catalog.drafts, drafts: catalog.drafts,
loraAliases: catalog.loraAliases || {}, loraAliases: catalog.loraAliases || {},
loraTriggers: catalog.loraTriggers || {}, 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 ext?: string
} }
const epoch = catalogEpoch.get(owner) || 0
const rows: Row[] = [] const rows: Row[] = []
if (typeFilter !== 'videos' && typeFilter !== 'music') { if (typeFilter !== 'videos' && typeFilter !== 'music') {
for (const still of catalog.stills) { for (const still of catalog.stills) {
@@ -724,7 +740,7 @@ export function publicLibraryPage(
name: still.name || still.filename || still.id, name: still.name || still.filename || still.id,
type: 'still', type: 'still',
createdAt: still.createdAt || 0, createdAt: still.createdAt || 0,
thumbUrl: `/api/library/stills/${still.id}/thumb`, thumbUrl: `/api/library/stills/${still.id}/thumb?v=${epoch}`,
folderId: still.folderId, folderId: still.folderId,
prompt: still.prompt, prompt: still.prompt,
promptPre: still.promptPre, promptPre: still.promptPre,
@@ -746,7 +762,7 @@ export function publicLibraryPage(
name: clip.name || clip.id, name: clip.name || clip.id,
type: 'clip', type: 'clip',
createdAt: clip.createdAt || 0, createdAt: clip.createdAt || 0,
thumbUrl: `/api/library/clips/${clip.id}/thumb`, thumbUrl: `/api/library/clips/${clip.id}/thumb?v=${epoch}`,
folderId: clip.folderId, folderId: clip.folderId,
prompt: clip.prompt, prompt: clip.prompt,
promptPre: clip.promptPre, promptPre: clip.promptPre,
@@ -814,7 +830,8 @@ export function publicLibraryPage(
loraAliases: catalog.loraAliases || {}, loraAliases: catalog.loraAliases || {},
loraTriggers: catalog.loraTriggers || {}, loraTriggers: catalog.loraTriggers || {},
keepPrompts: catalog.keepPrompts || emptyKeepPrompts(), 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 clips = catalog.clips.filter(clip => clip.folderId === id)
const stills = catalog.stills.filter(still => still.folderId === id) const stills = catalog.stills.filter(still => still.folderId === id)
const tracks = (catalog.tracks || []).filter(track => track.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.folders = catalog.folders.filter(item => item.id !== id)
catalog.clips = catalog.clips.filter(clip => clip.folderId !== id) catalog.clips = catalog.clips.filter(clip => clip.folderId !== id)
catalog.stills = catalog.stills.filter(still => still.folderId !== id) catalog.stills = catalog.stills.filter(still => still.folderId !== id)
catalog.tracks = (catalog.tracks || []).filter(track => track.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 } 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. */ /** 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) { export function wipeFolderContents(owner: string, folderId: string) {
let removed: RemovedEntry[] = []
return mutate(owner, (catalog) => { return mutate(owner, (catalog) => {
const folder = catalog.folders.find(item => item.id === folderId) const folder = catalog.folders.find(item => item.id === folderId)
if (!folder) throw createError({ statusCode: 404, statusMessage: 'Folder not found' }) 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), ...stills.map(item => item.id),
...tracks.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) emptyFolderRows(catalog, folderId)
detachDraftStills(catalog, deletedIds) 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) pruneMissingStillMasters(owner, catalog)
const remain = [ const remain = [
...catalog.clips.filter(item => sameFolder(item.folderId, folderId)), ...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)) console.error('[library] wipe left folder rows', folderId, remain.map(item => item.id))
emptyFolderRows(catalog, folderId) emptyFolderRows(catalog, folderId)
} }
assertRemovedEntries(owner, removed)
return { return {
folderId: folder.id, folderId: folder.id,
folderName: folder.name, folderName: folder.name,
@@ -965,6 +988,7 @@ export function wipeFolderContents(owner: string, folderId: string) {
tracks: tracks.length tracks: tracks.length
} }
}).then((result) => { }).then((result) => {
assertRemovedEntries(owner, removed)
invalidateCatalogCache(owner) invalidateCatalogCache(owner)
return result return result
}) })
@@ -998,8 +1022,8 @@ function pruneMissingStillMasters(owner: string, catalog: Catalog) {
keep.push(still) keep.push(still)
continue continue
} }
droppedIds.add(still.id)
removeStillFiles(owner, still.id) removeStillFiles(owner, still.id)
droppedIds.add(still.id)
} }
catalog.stills = keep.filter(still => beforeIds.has(still.id)) catalog.stills = keep.filter(still => beforeIds.has(still.id))
if (!droppedIds.size) return 0 if (!droppedIds.size) return 0
@@ -1446,20 +1470,140 @@ export function existingStillPreviewPath(owner: string, id: string) {
return '' return ''
} }
/** Never throw — a locked thumb must not abort the catalog write. */ type RemovedEntry = { id: string, kind: 'still' | 'clip' | 'track' }
function safeRm(target: string, recursive = false) {
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 { try {
rmSync(target, recursive ? { recursive: true, force: true } : { force: true }) statSync(target)
return true
} catch (error) { } catch (error) {
const code = (error as NodeJS.ErrnoException)?.code
if (code === 'ENOENT') return false
const message = error instanceof Error ? error.message : String(error) 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 `<id>` / `<id>.*` 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<string>()
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) { function removeStillFiles(owner: string, id: string) {
safeRm(stillPath(owner, id)) for (const path of stillArtifactPaths(owner, id)) unlinkVerified(path)
safeRm(stillThumbFile(owner, id)) assertStillFilesGone(owner, [id])
safeRm(stillPreviewFile(owner, id))
} }
let thumbSlots = 0 let thumbSlots = 0
@@ -1982,11 +2126,22 @@ export function getStill(owner: string, id: string) {
export function deleteStill(owner: string, id: string) { export function deleteStill(owner: string, id: string) {
return mutate(owner, (catalog) => { return mutate(owner, (catalog) => {
const still = catalog.stills.find(item => item.id === id) 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) catalog.stills = catalog.stills.filter(item => item.id !== id)
detachDraftStills(catalog, new Set([id])) detachDraftStills(catalog, new Set([id]))
removeStillFiles(owner, id)
pruneMissingStillMasters(owner, catalog) pruneMissingStillMasters(owner, catalog)
assertStillFilesGone(owner, [id])
return still
}).then((still) => {
assertStillFilesGone(owner, [id])
invalidateCatalogCache(owner)
return still return still
}) })
} }
@@ -2003,15 +2158,27 @@ export function moveStill(owner: string, id: string, folderId: string) {
} }
export function deleteStillFamily(owner: string, id: string) { export function deleteStillFamily(owner: string, id: string) {
let ids: string[] = []
return mutate(owner, (catalog) => { return mutate(owner, (catalog) => {
const still = catalog.stills.find(item => item.id === id) 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 family = stillsInSameFamily(catalog, still)
const ids = new Set(family.map(item => item.id)) ids = family.map(item => item.id)
catalog.stills = catalog.stills.filter(item => !ids.has(item.id)) const idSet = new Set(ids)
detachDraftStills(catalog, ids)
for (const item of family) removeStillFiles(owner, item.id) 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) pruneMissingStillMasters(owner, catalog)
assertStillFilesGone(owner, ids)
return family
}).then((family) => {
assertStillFilesGone(owner, ids)
invalidateCatalogCache(owner)
return family return family
}) })
} }
+18 -6
View File
@@ -22,22 +22,34 @@ export function folderImageCount(folder, localStillCount = 0) {
return Number(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) { export function libraryAfterWipe(previous, response, folderId) {
const suppressed = new Set(previous?.suppressedIds || [])
const target = String(folderId || '') 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 || []) { 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 { return {
folders: Array.isArray(response?.folders) ? response.folders : (previous?.folders || []), folders: Array.isArray(response?.folders) ? response.folders : (previous?.folders || []),
stills: take(response?.stills), stills: take(response?.stills),
clips: take(response?.clips), clips: take(response?.clips),
tracks: take(response?.tracks), tracks: take(response?.tracks),
suppressedIds: [...suppressed] suppressedIds: []
} }
} }
+146 -15
View File
@@ -6,7 +6,15 @@ import ts from 'typescript'
const source = readFileSync(new URL('../server/utils/library.ts', import.meta.url), 'utf8') 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 ast = ts.createSourceFile('library.ts', source, ts.ScriptTarget.Latest, true)
const names = [ const names = [
'safeRm', 'removedEntries',
'pathRemains',
'stillFileRemains',
'unlinkVerified',
'stillIdAllowed',
'stillArtifactPaths',
'entryPaths',
'assertRemovedEntries',
'assertStillFilesGone',
'removeStillFiles', 'removeStillFiles',
'detachDraftStills', 'detachDraftStills',
'sameFolder', 'sameFolder',
@@ -30,6 +38,36 @@ function harness() {
const catalogEpoch = new Map() const catalogEpoch = new Map()
let writes = 0 let writes = 0
let stored = null 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 readCatalog() { return stored }
function writeCatalog(_owner, catalog) { function writeCatalog(_owner, catalog) {
stored = catalog === undefined ? _owner : catalog stored = catalog === undefined ? _owner : catalog
@@ -39,6 +77,11 @@ function harness() {
const api = new Function( const api = new Function(
'rmSync', 'rmSync',
'existsSync', 'existsSync',
'statSync',
'readdirSync',
'join',
'ownerRoot',
'libraryRoot',
'console', 'console',
'stillPath', 'stillPath',
'stillThumbFile', 'stillThumbFile',
@@ -52,13 +95,22 @@ function harness() {
'writeCatalog', 'writeCatalog',
'catalogEpoch', 'catalogEpoch',
'invalidateCatalogCache', 'invalidateCatalogCache',
`${js}; return { catalogWithPrunedStills, deleteStill, deleteStillFamily, wipeFolderContents, emptyFolderRows };` `${js}; return { catalogWithPrunedStills, deleteStill, deleteStillFamily, wipeFolderContents, emptyFolderRows, removeStillFiles };`
)( )(
(path) => { (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) 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, console,
(owner, id) => `${owner}/stills/${id}`, (owner, id) => `${owner}/stills/${id}`,
(owner, id) => `${owner}/stills/${id}.thumb.jpg`, (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() const h = harness()
h.thrown.add('locked') h.thrown.add('locked')
h.files.add('owner/stills/locked') h.files.add('owner/stills/locked')
h.files.add('owner/stills/locked.thumb.jpg')
const catalog = { const catalog = {
stills: [{ id: 'locked', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }], stills: [{ id: 'locked', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }],
drafts: [{ id: 'd', stillId: 'locked', stillFilename: 'locked.png' }], 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.load(catalog)
h.files.add('owner/stills/keep') 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.equal(h.writes, 1)
assert.deepEqual(catalog.stills.map(item => item.id), ['keep']) assert.deepEqual(catalog.stills.map(item => item.id), ['keep'])
assert.equal(catalog.drafts[0].stillId, undefined) 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) 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 h = harness()
const catalog = { const catalog = {
stills: [{ id: 'gone', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }], 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.load(structuredClone(catalog))
h.files.add('owner/stills/keep') 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') const page = h.api.catalogWithPrunedStills('owner')
assert.equal(h.writes, 1) assert.equal(h.writes, 1)
assert.deepEqual(page.stills.map(item => item.id), ['keep']) assert.deepEqual(page.stills.map(item => item.id), ['keep'])
assert.equal(page.drafts[0].stillId, undefined) 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() const h = harness()
h.thrown.add('locked') h.thrown.add('locked')
const catalog = { const catalog = {
@@ -137,15 +259,16 @@ test('wipeFolderContents still clears the folder when a file remove throws', asy
folders: [{ id: 'inbox', name: 'Inbox' }] folders: [{ id: 'inbox', name: 'Inbox' }]
} }
h.load(catalog) h.load(catalog)
const result = await h.api.wipeFolderContents('owner', 'inbox') h.files.add('owner/stills/locked')
assert.equal(result.deleted, 2) await assert.rejects(() => h.api.wipeFolderContents('owner', 'inbox'), /locked/)
assert.equal(catalog.stills.length, 0) assert.equal(h.writes, 0)
assert.equal(catalog.clips.length, 0) assert.equal(catalog.stills.length, 1)
assert.equal(h.writes, 1) assert.equal(catalog.clips.length, 1)
assert.deepEqual(h.invalidated, ['owner']) 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 h = harness()
const catalog = { const catalog = {
stills: [ stills: [
@@ -162,12 +285,20 @@ test('wipeFolderContents leaves zero rows for that folder and does not touch ano
} }
h.load(catalog) h.load(catalog)
h.files.add('owner/stills/a') h.files.add('owner/stills/a')
h.files.add('owner/stills/a.thumb.jpg')
h.files.add('owner/stills/b') 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') const result = await h.api.wipeFolderContents('owner', 'inbox')
assert.equal(result.deleted, 3) assert.equal(result.deleted, 3)
assert.deepEqual(catalog.stills.map(item => item.id), ['b']) assert.deepEqual(catalog.stills.map(item => item.id), ['b'])
assert.deepEqual(catalog.clips, []) assert.deepEqual(catalog.clips, [])
assert.deepEqual(catalog.tracks.map(item => item.id), ['u']) 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']) assert.deepEqual(h.invalidated, ['owner'])
}) })
+38
View File
@@ -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)
}
})
+16 -9
View File
@@ -1,6 +1,6 @@
import test from 'node:test' import test from 'node:test'
import assert from 'node:assert/strict' 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', () => { test('folderImageCount trusts a server count of 0', () => {
assert.equal(folderImageCount({ id: 'inbox', imageCount: 0 }, 1762), 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) 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 = { const previous = {
folders: [{ id: 'inbox', imageCount: 2 }], folders: [{ id: 'inbox', imageCount: 2 }],
stills: [{ id: 'new-1', folderId: 'inbox' }, { id: 'new-2', folderId: 'inbox' }], 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' } { id: 'kept', folderId: 'other' }
], ],
clips: [{ id: 'clip-ghost', folderId: 'inbox' }], clips: [{ id: 'clip-ghost', folderId: 'inbox' }],
tracks: [] tracks: [],
deletedIds: ['new-1', 'new-2']
} }
const next = libraryAfterWipe(previous, stale, 'inbox') const next = libraryAfterWipe(previous, stale, 'inbox')
assert.deepEqual(next.stills.map(item => item.id), ['kept']) assert.deepEqual(next.stills.map(item => item.id), ['kept'])
assert.deepEqual(next.clips, []) assert.deepEqual(next.clips, [])
assert.equal(next.folders[0].imageCount, 0) assert.equal(next.folders[0].imageCount, 0)
assert.equal(next.suppressedIds.includes('new-1'), true) assert.deepEqual(next.suppressedIds, [])
assert.equal(next.suppressedIds.includes('ghost'), true) const replaced = replaceLibraryRows(next.stills, [])
assert.equal(next.suppressedIds.includes('already-gone'), true) assert.deepEqual(replaced.map(item => item.id), ['kept'])
const page = mergeLibraryRows(next.stills, stale.stills, next.suppressedIds) const page = mergeLibraryRows(replaced, [{ id: 'kept', folderId: 'other' }, { id: 'fresh', folderId: 'other' }], [])
assert.deepEqual(page.map(item => item.id), ['kept']) assert.deepEqual(page.map(item => item.id), ['kept', 'fresh'])
assert.deepEqual(replaceLibraryRows(stale.stills, next.suppressedIds).map(item => item.id), ['kept'])
}) })