Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Library batch delete: a failed undo keeps the folder for a later try, disk errors are not taken...

Bowen Xue90e60efb7d0e
diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.py
index 6c52943..9549c1a 100644
--- a/freevideo_engine/comfy_library.py
+++ b/freevideo_engine/comfy_library.py
@@ -429,24 +429,44 @@ def _queued_continuation_uses(path, output_directory, queue):
return False
-def delete_video(output_directory, identity, *, queue=None):
- """Delete one saved creation: its whole run folder, only when FreeVideo wrote everything in it.
+def _request_states(root, cache):
+ """The small request records of every run, re-read only when their file changed."""
+ rows = []
+ for state_path in root.glob('*/*/comfy-request.json'):
+ try:
+ info = state_path.stat()
+ key = (info.st_mtime_ns, info.st_size, getattr(info, 'st_ino', 0))
+ known = cache.get(state_path)
+ if known is None or known[0] != key:
+ state = json.loads(state_path.read_text(encoding='utf-8')) if info.st_size <= 1024 * 1024 else {}
+ known = cache[state_path] = (key, state)
+ except (OSError, ValueError):
+ continue
+ rows.append(known[1])
+ return rows
- The folder is first renamed into FreeVideo/.deleted, so it leaves the
- library at once, or, when Windows still has a file open, nothing changes.
+
+class RecordUnsaved(Exception):
+ """The record that names a folder before it moves could not be written, so nothing moved."""
+
+
+def _trash_creation(output_directory, identity, queue, cache, announce=None):
+ """Check that a creation may go, and rename its folder into FreeVideo/.deleted.
+
+ Returns the trash folder and the content identifier of its video. Nothing is
+ deleted yet: the caller removes the folder when it is sure it is not wanted back.
+ ``announce(target, identifier)`` runs under the same locks just before the move, so a
+ caller can write down where the folder is going first; if it raises, nothing moves.
"""
- try:
- output_directory = checked_real_path(output_directory)
- except AliasUnavailable as error:
- raise DeleteRefused('not-freevideo') from error
path = _video(output_directory, identity)
_report(path)
root = Path(output_directory).resolve() / 'FreeVideo'
folder = path.parent
if folder.parent.parent != root or not _plain(folder.parent) or not _plain(folder):
raise DeleteRefused('not-freevideo')
- # Not while the startup release is deleting files in this folder.
- with _RELEASING, (queue.mutex if queue is not None else nullcontext()):
+ # Not while the startup release is deleting files in this folder. _PENDING comes first,
+ # as in undo_deleted, so the move and its in-flight mark cannot interleave with a purge.
+ with _PENDING, _RELEASING, (queue.mutex if queue is not None else nullcontext()):
from .comfy_editor import reference_users
try:
users = reference_users(output_directory, identity)
@@ -460,11 +480,7 @@ def delete_video(output_directory, identity, *, queue=None):
if _queued_continuation_uses(path, output_directory, queue):
raise DeleteRefused('continuation-in-use')
# A second pass of this preview may be reading its first pass right now.
- for state_path in root.glob('*/*/comfy-request.json'):
- try:
- state = json.loads(state_path.read_text(encoding='utf-8')) if state_path.stat().st_size <= 1024 * 1024 else {}
- except (OSError, ValueError):
- continue
+ for state in _request_states(root, cache):
if not isinstance(state, dict) or state.get('status') not in ('queued', 'starting', 'running'):
continue
source = state.get('upscaled_preview')
@@ -479,7 +495,7 @@ def delete_video(output_directory, identity, *, queue=None):
# cleanup may fail, including in lightweight CI without PyAV.
identifier = None
try:
- from .continuation_store import video_id, delete_id
+ from .continuation_store import video_id
identifier = video_id(path)
except ModuleNotFoundError as error:
if error.name not in ('av', __package__ + '.continuation_store'):
@@ -491,30 +507,497 @@ def delete_video(output_directory, identity, *, queue=None):
if not _plain(trash):
raise DeleteRefused('not-freevideo')
target = trash / ('%s-%d' % (identity.replace('/', '-'), time.time_ns()))
+ if announce is not None:
+ announce(target, identifier)
try:
folder.rename(target)
except OSError as error:
raise DeleteRefused('in-use') from error
- if identifier is not None:
- try:
- delete_id(identifier)
- except Exception as error:
- logging.warning('[FreeVideo] Continuation cleanup failed (%s).', type(error).__name__)
- freed, left = _remove(target)
- # A result-cache row naming this creation can no longer be reused.
+ _INFLIGHT.add(target.name)
+ return target, identifier
+
+
+def _forget(identifiers, root):
+ """Drop what only a deleted creation needed: its continuation data and reusable results."""
+ for identifier in identifiers:
+ if identifier is None:
+ continue
+ try:
+ from .continuation_store import delete_id
+ delete_id(identifier)
+ except Exception as error:
+ logging.warning('[FreeVideo] Continuation cleanup failed (%s).', type(error).__name__)
+
+
+def _forget_results(identities, root):
+ """A result-cache row naming a deleted creation can no longer be reused."""
for index in (root / '.result-cache').glob('*.json'):
try:
- if index.stat().st_size <= 1024 * 1024 and json.loads(index.read_text(encoding='utf-8')).get('id') == identity:
+ if index.stat().st_size <= 1024 * 1024 and json.loads(index.read_text(encoding='utf-8')).get('id') in identities:
index.unlink()
- except (OSError, ValueError, AttributeError):
+ except (OSError, ValueError, AttributeError, TypeError):
pass
+
+
+def delete_video(output_directory, identity, *, queue=None):
+ """Delete one saved creation: its whole run folder, only when FreeVideo wrote everything in it.
+
+ The folder is first renamed into FreeVideo/.deleted, so it leaves the
+ library at once, or, when Windows still has a file open, nothing changes.
+ """
+ try:
+ output_directory = checked_real_path(output_directory)
+ except AliasUnavailable as error:
+ raise DeleteRefused('not-freevideo') from error
+ root = Path(output_directory).resolve() / 'FreeVideo'
+ target, identifier = _trash_creation(output_directory, identity, queue, {})
+ try:
+ _forget([identifier], root)
+ freed, left = _remove(target)
+ _forget_results({identity}, root)
+ finally:
+ with _PENDING:
+ _INFLIGHT.discard(target.name)
# Finish earlier deletions that Windows had kept open.
- for earlier in trash.iterdir():
- if earlier != target and _plain(earlier) and earlier.is_dir():
- freed += _remove(earlier)[0]
+ freed += _purge_trash(root / '.deleted', keep={target.name})
return dict(id=identity, freed_bytes=freed, left=len(left))
+# Several creations deleted together stay in FreeVideo/.deleted for a few seconds, so
+# one click can bring them back. A manifest beside them names what to restore or remove.
+UNDO_SECONDS = 10
+_UNDO_GRACE = 3 # the server waits a little longer than the page shows
+_MANIFEST = '.pending-'
+_BATCH_NAME = re.compile(r'[0-9]{1,20}-[0-9a-f]{6}')
+# A folder in the trash is named by the id it had, with its slash a dash, and the time it moved.
+_TRASH_NAME = re.compile(r'\d{4}-\d{2}-\d{2}-[0-9a-f]{32}-\d+')
+_PENDING = threading.Lock()
+MAX_BATCH = 500
+MAX_EXTEND = 200
+_SESSION = os.urandom(6).hex()
+# Batch names taken in the last hour, and those whose deletion is still moving folders.
+# A name is taken before the first folder moves, so a repeated or parallel request with it
+# is refused instead of overwriting the other's record. Guarded by _PENDING.
+_CLAIMED = {}
+_ACTIVE = set()
+_CLAIM_SECONDS = 3600
+_CLAIM_LIMIT = 4096
+# Folders already moved into FreeVideo/.deleted whose batch record is not written yet.
+# A purge running at the same time must leave them alone. Guarded by _PENDING.
+_INFLIGHT = set()
+
+
+def _pending_manifests(trash):
+ rows = []
+ try:
+ names = sorted(path for path in trash.iterdir() if path.name.startswith(_MANIFEST) and path.suffix == '.json')
+ except OSError:
+ return rows
+ for path in names:
+ try:
+ value = json.loads(path.read_text(encoding='utf-8'))
+ if isinstance(value, dict) and isinstance(value.get('items'), list):
+ rows.append((path, value))
+ except (OSError, ValueError):
+ continue
+ return rows
+
+
+def _claim(token, manifest):
+ with _PENDING:
+ now = time.monotonic()
+ for name in [name for name, taken in _CLAIMED.items() if now - taken > _CLAIM_SECONDS]:
+ del _CLAIMED[name]
+ while len(_CLAIMED) >= _CLAIM_LIMIT:
+ del _CLAIMED[next(iter(_CLAIMED))]
+ if token in _CLAIMED or manifest.exists():
+ raise ValueError('Invalid selection')
+ _CLAIMED[token] = now
+ _ACTIVE.add(token)
+
+
+def _hold(root, tokens, due):
+ """Set the end of the undo time of batches an earlier request of the same click already made.
+
+ Returns the batches whose record could not be written; those keep the time they had.
+ """
+ from .monitoring import save
+ failed = []
+ with _PENDING:
+ for token in tokens:
+ path = root / '.deleted' / (_MANIFEST + token + '.json')
+ try:
+ value = json.loads(path.read_text(encoding='utf-8'))
+ current = float(value['due'])
+ if value.get('restore') or time.time() >= current:
+ continue
+ value['due'] = due
+ save(path, value)
+ except (ValueError, KeyError, TypeError, AttributeError):
+ continue
+ except OSError:
+ if path.exists():
+ failed.append(token)
+ return failed
+
+
+def _recover(root, path, value):
+ """Try again to put back what a failed delete could not; never removes anything.
+
+ The caller holds _PENDING and _RELEASING."""
+ from .monitoring import save
+ rows = [item for item in value['items'] if isinstance(item, dict) and isinstance(item.get('id'), str)
+ and _ID.fullmatch(item['id']) and isinstance(item.get('name'), str)
+ and _TRASH_NAME.fullmatch(item['name'])]
+ failed = set(_restore_moved(root, rows))
+ left = [row for row in rows if row['id'] in failed]
+ try:
+ if left:
+ if len(left) != len(value['items']):
+ save(path, dict(value, items=left))
+ else:
+ path.unlink()
+ except OSError:
+ logging.warning('FreeVideo could not update the record of creations it still has to put back.')
+ return
+ _INFLIGHT.difference_update(row['name'] for row in rows if row['id'] not in failed)
+
+
+def _purge_trash(trash, keep=()):
+ """Remove folders that earlier deletions left behind, except those a batch may still restore.
+
+ The folders to remove are chosen while no batch is moving one in, so a folder
+ that is on its way into a batch record is never taken for left-over rubbish.
+ """
+ freed = 0
+ try:
+ with _PENDING:
+ held = set(keep) | _INFLIGHT
+ for _, value in _pending_manifests(trash):
+ held.update(str(item.get('name')) for item in value['items'] if isinstance(item, dict))
+ leftovers = [earlier for earlier in trash.iterdir() if earlier.name not in held]
+ for earlier in leftovers:
+ try:
+ if _plain(earlier) and earlier.is_dir():
+ freed += _remove(earlier)[0]
+ except OSError:
+ continue
+ except OSError:
+ pass
+ return freed
+
+
+def _restore_moved(root, rows):
+ """Put folders back where they were taken from; returns the ids that could not be restored."""
+ trash, failed = root / '.deleted', []
+ for row in rows:
+ try:
+ source, folder = trash / row['name'], root / row['id']
+ # Named before it moved: a folder that never left, or is already back, needs nothing.
+ if not os.path.lexists(source):
+ continue
+ if folder.exists():
+ raise OSError
+ folder.parent.mkdir(parents=True, exist_ok=True)
+ source.rename(folder)
+ except OSError:
+ failed.append(row['id'])
+ return failed
+
+
+def delete_videos(output_directory, identities, *, queue=None, batch=None, extend=()):
+ """Delete several creations at once, each under the single delete's checks.
+
+ A creation that is in use is skipped with its reason, never forced. The rest
+ leave the library at once and are removed for good ``UNDO_SECONDS`` later;
+ ``undo_deleted`` brings them back until then. ``batch`` lets the page name the batch
+ before asking, so a page that is reloaded while the request runs can still undo it. A name
+ is used once: a second request with it is refused. ``extend`` names the earlier batches of
+ the same click; their undo time is kept open while this request runs and ends with it.
+ """
+ if batch is not None and not (isinstance(batch, str) and _BATCH_NAME.fullmatch(batch)):
+ raise ValueError('Invalid selection')
+ if (not isinstance(identities, list) or not identities or len(identities) > MAX_BATCH
+ or not all(isinstance(identity, str) for identity in identities)):
+ raise ValueError('Invalid selection')
+ if (not isinstance(extend, (list, tuple)) or len(extend) > MAX_EXTEND
+ or not all(isinstance(name, str) and _BATCH_NAME.fullmatch(name) for name in extend)):
+ raise ValueError('Invalid selection')
+ try:
+ output_directory = checked_real_path(output_directory)
+ except AliasUnavailable as error:
+ raise DeleteRefused('not-freevideo') from error
+ root = Path(output_directory).resolve() / 'FreeVideo'
+ finish_deleted(output_directory)
+ cache, moved, skipped = {}, [], []
+ from .monitoring import save
+ token = batch or '%d-%s' % (time.time_ns(), os.urandom(3).hex())
+ manifest = root / '.deleted' / (_MANIFEST + token + '.json')
+ _claim(token, manifest)
+ if extend:
+ _hold(root, extend, time.time() + 120)
+
+ def announce(row):
+ # Written before the folder moves, as a record that only puts things back: if the move, the next
+ # step, a later write or this process fails, whatever sits in the trash is named and never removed.
+ # The caller holds _PENDING.
+ def write(target, identifier):
+ try:
+ save(manifest, dict(schema=1, due=0, restore=True, session=_SESSION,
+ items=moved + [dict(row, name=target.name, continuation=identifier)]))
+ except OSError as error:
+ raise RecordUnsaved from error
+ return write
+
+ def publish(due):
+ # Every folder is in the trash and named; from now on the record removes them when the time is over.
+ with _PENDING:
+ save(manifest, dict(schema=1, due=due, born=time.time(), session=_SESSION, items=moved))
+ _INFLIGHT.difference_update(row['name'] for row in moved)
+
+ try:
+ for identity in dict.fromkeys(identities):
+ try:
+ target, identifier = _trash_creation(output_directory, identity, queue, cache,
+ announce=announce(dict(id=identity)))
+ except DeleteRefused as error:
+ skipped.append(dict(id=identity, reason=error.reason, kept=error.kept[:20]))
+ except RecordUnsaved:
+ skipped.append(dict(id=identity, reason='unsaved', kept=[]))
+ except (FileNotFoundError, NotADirectoryError, ValueError):
+ # The creation is already gone from disk (or was never complete): it only has to leave the page.
+ skipped.append(dict(id=identity, reason='unavailable', kept=[]))
+ except OSError:
+ # Still there but not readable or writable (permissions, read-only disk): it stays, and says so.
+ skipped.append(dict(id=identity, reason='failed', kept=[]))
+ else:
+ moved.append(dict(id=identity, name=target.name, continuation=identifier))
+ if moved:
+ # The undo time starts when the last creation has left the library.
+ publish(time.time() + UNDO_SECONDS + _UNDO_GRACE)
+ else:
+ with _PENDING:
+ try:
+ manifest.unlink()
+ except OSError:
+ pass
+ except BaseException:
+ with _PENDING, _RELEASING:
+ failed = set(_restore_moved(root, moved))
+ _INFLIGHT.difference_update(row['name'] for row in moved)
+ try:
+ if not failed:
+ manifest.unlink()
+ else:
+ logging.warning('FreeVideo could not put back %d creations after a failed delete.', len(failed))
+ # What could not be put back stays named by a record that only restores it, until it can be.
+ save(manifest, dict(schema=1, due=0, restore=True, session=_SESSION,
+ items=[row for row in moved if row['id'] in failed]))
+ except OSError:
+ # The record already on disk was written before the moves and says the same.
+ pass
+ raise
+ finally:
+ # The earlier chunks get their normal time before this one is reported as finished.
+ if extend:
+ _hold(root, extend, time.time() + UNDO_SECONDS + _UNDO_GRACE)
+ with _PENDING:
+ _ACTIVE.discard(token)
+ if moved:
+ timer = threading.Timer(UNDO_SECONDS + _UNDO_GRACE + 1, _finish_quietly, (output_directory,))
+ timer.daemon = True
+ timer.start()
+ return dict(batch=token if moved else None, undo_seconds=UNDO_SECONDS,
+ deleted=[row['id'] for row in moved], skipped=skipped)
+
+
+def _finish_quietly(output_directory):
+ try:
+ finish_deleted(output_directory)
+ except Exception:
+ logging.warning('FreeVideo could not finish removing deleted creations.', exc_info=True)
+
+
+def finish_deleted(output_directory, *, everything=False):
+ """Remove for good the batches whose undo time is over (all of them with ``everything``).
+
+ Also what the continuation store and the result cache kept for them, and any
+ folder an earlier deletion could not remove. Returns the bytes freed.
+ """
+ root = Path(checked_real_path(output_directory)).resolve() / 'FreeVideo'
+ trash = root / '.deleted'
+ if not trash.is_dir() or not _plain(trash):
+ return 0
+ claimed, recover = [], []
+ with _PENDING:
+ for path, value in _pending_manifests(trash):
+ try:
+ # A batch still moving folders is not touched.
+ if path.name[len(_MANIFEST):-len('.json')] in _ACTIVE or any(
+ isinstance(item, dict) and item.get('name') in _INFLIGHT for item in value['items']):
+ continue
+ if value.get('restore'):
+ recover.append((path, value))
+ # Starting up, only what an earlier session left is finished; a batch of this one is still undoable.
+ elif (everything and value.get('session') != _SESSION) or time.time() >= float(value.get('due', 0)):
+ path.unlink()
+ claimed.append(value['items'])
+ except (OSError, ValueError, TypeError):
+ continue
+ if recover:
+ with _PENDING, _RELEASING:
+ for path, value in recover:
+ _recover(root, path, value)
+ freed = 0
+ for items in claimed:
+ rows = [item for item in items if isinstance(item, dict) and isinstance(item.get('name'), str)
+ and _TRASH_NAME.fullmatch(item['name'])]
+ _forget([item.get('continuation') for item in rows], root)
+ for item in rows:
+ folder = trash / item['name']
+ if folder.name == item['name'] and _plain(folder) and folder.is_dir():
+ freed += _remove(folder)[0]
+ _forget_results({item.get('id') for item in rows}, root)
+ return freed + _purge_trash(trash)
+
+
+class UndoBusy(ValueError):
+ """The batch is still being deleted; asking again once that is done works."""
+
+
+def undo_deleted(output_directory, token):
+ """Put a batch back while its undo time lasts; raises ValueError('expired') afterwards."""
+ output_directory = checked_real_path(output_directory)
+ root = Path(output_directory).resolve() / 'FreeVideo'
+ trash = root / '.deleted'
+ if not isinstance(token, str) or not _BATCH_NAME.fullmatch(token):
+ raise ValueError('Invalid batch')
+ manifest = trash / (_MANIFEST + token + '.json')
+ restored, lost = [], []
+ from .monitoring import save
+ with _PENDING, _RELEASING:
+ if token in _ACTIVE:
+ raise UndoBusy('busy')
+ try:
+ value = json.loads(manifest.read_text(encoding='utf-8'))
+ if value.get('restore') or time.time() >= float(value['due']):
+ raise ValueError('expired')
+ items = [item for item in value['items'] if isinstance(item, dict)]
+ except (OSError, KeyError, TypeError, AttributeError):
+ raise ValueError('expired') from None
+ rows = [item for item in items if isinstance(item.get('id'), str) and _ID.fullmatch(item['id'])
+ and isinstance(item.get('name'), str) and _TRASH_NAME.fullmatch(item['name'])]
+ # From here the record only puts things back, so whatever fails or stops half way is never removed.
+ try:
+ save(manifest, dict(value, restore=True, due=0, items=items))
+ except OSError:
+ logging.warning('FreeVideo could not record an undo, so nothing was restored.')
+ return dict(restored=[], lost=[item.get('id') for item in items])
+ for item in items:
+ if item not in rows:
+ lost.append(item.get('id'))
+ continue
+ try:
+ source, folder = trash / item['name'], root / item['id']
+ if folder.exists() or not _plain(source):
+ raise OSError
+ folder.parent.mkdir(parents=True, exist_ok=True)
+ source.rename(folder)
+ restored.append(item['id'])
+ except OSError:
+ lost.append(item['id'])
+ # What could not come back stays named by the record, to be put back later and never removed.
+ kept = [item for item in items if item.get('id') in lost]
+ try:
+ if kept:
+ save(manifest, dict(value, restore=True, due=0, items=kept))
+ else:
+ manifest.unlink()
+ except OSError:
+ pass
+ return dict(restored=restored, lost=lost)
+
+
+def _checked_tokens(tokens):
+ if (not isinstance(tokens, list) or len(tokens) > MAX_EXTEND
+ or not all(isinstance(name, str) and _BATCH_NAME.fullmatch(name) for name in tokens)):
+ raise ValueError('Invalid selection')
+ return list(dict.fromkeys(tokens))
+
+
+def undo_state(output_directory, tokens):
+ """What the server says about each batch: ``busy`` (folders still moving), ``ready`` with the
+ seconds left to undo it, or ``gone`` (finished, restored, expired or never made)."""
+ tokens = _checked_tokens(tokens)
+ root = Path(checked_real_path(output_directory)).resolve() / 'FreeVideo'
+ states = {}
+ with _PENDING:
+ for token in tokens:
+ if token in _ACTIVE:
+ states[token] = dict(state='busy')
+ continue
+ try:
+ value = json.loads((root / '.deleted' / (_MANIFEST + token + '.json')).read_text(encoding='utf-8'))
+ left = float(value['due']) - time.time() - _UNDO_GRACE
+ if value.get('restore') or left <= 0:
+ raise ValueError
+ states[token] = dict(state='ready', seconds=left, count=len(value['items']))
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ states[token] = dict(state='gone')
+ return states
+
+
+def hold_deleted(output_directory, tokens, *, running):
+ """Keep earlier batches of one click undoable while its next request runs (``running``), or
+ give them the normal undo time again once it is over; returns ``undo_state``.
+
+ Raises OSError when a batch's record could not be written: the caller must not go on as if it was held.
+ """
+ tokens = _checked_tokens(tokens)
+ if not isinstance(running, bool):
+ raise ValueError('Invalid selection')
+ root = Path(checked_real_path(output_directory)).resolve() / 'FreeVideo'
+ seconds = 120 if running else UNDO_SECONDS + _UNDO_GRACE
+ failed = _hold(root, tokens, time.time() + seconds)
+ states = undo_state(output_directory, tokens)
+ if any(row['state'] == 'ready' for row in states.values()):
+ # The request that would have ended their time may never come: check once the time is over.
+ timer = threading.Timer(seconds + 1, _finish_quietly, (output_directory,))
+ timer.daemon = True
+ timer.start()
+ if failed:
+ raise OSError('Could not keep the batches')
+ return states
+
+
+def folder_sizes(output_directory, identities):
+ """Bytes each creation's whole run folder holds, links not followed; unknown ids are left out."""
+ if not isinstance(identities, list) or len(identities) > MAX_BATCH:
+ raise ValueError('Invalid selection')
+ root = Path(checked_real_path(output_directory)).resolve() / 'FreeVideo'
+ sizes = {}
+ for identity in identities:
+ if not isinstance(identity, str) or not _ID.fullmatch(identity):
+ continue
+ folder = root / identity
+ total = 0
+ try:
+ if not _plain(folder):
+ continue
+ for parent, folders, files in os.walk(folder):
+ folders[:] = [name for name in folders if _plain(Path(parent) / name)]
+ for name in files:
+ try:
+ info = os.lstat(Path(parent) / name)
+ total += info.st_size if stat.S_ISREG(info.st_mode) else 0
+ except OSError:
+ pass
+ except OSError:
+ continue
+ sizes[identity] = total
+ return sizes
+
+
def register():
from aiohttp import web
import folder_paths
@@ -533,6 +1016,11 @@ def register():
result['freed_bytes'] / 1e9, result['videos'])
except Exception:
logging.warning('FreeVideo could not free the decoded files of earlier videos.', exc_info=True)
+ try:
+ # A deletion the last session did not finish: its undo time is long over.
+ finish_deleted(folder_paths.get_output_directory(), everything=True)
+ except Exception:
+ logging.warning('FreeVideo could not finish removing deleted creations.', exc_info=True)
threading.Thread(target=release, name='freevideo-release-decoded', daemon=True).start()
@server.routes.get('/freevideo/sampling-estimate')
@@ -623,6 +1111,62 @@ def register():
raise web.HTTPNotFound(text='Saved video unavailable') from None
return web.json_response(dict(result, deleted=True))
+ @server.routes.post('/freevideo/library/delete-batch')
+ async def delete_batch(request):
+ try:
+ body = await request.json()
+ result = await asyncio.to_thread(delete_videos, folder_paths.get_output_directory(),
+ body.get('ids') if isinstance(body, dict) else None,
+ queue=getattr(server, 'prompt_queue', None),
+ batch=body.get('batch') if isinstance(body, dict) else None,
+ extend=body.get('extend') or () if isinstance(body, dict) else ())
+ except (DeleteRefused, OSError, ValueError, TypeError):
+ raise web.HTTPBadRequest(text='Invalid selection') from None
+ return web.json_response(result)
+
+ @server.routes.post('/freevideo/library/undo')
+ async def undo(request):
+ try:
+ body = await request.json()
+ result = await asyncio.to_thread(undo_deleted, folder_paths.get_output_directory(),
+ body.get('batch') if isinstance(body, dict) else None)
+ except UndoBusy:
+ return web.json_response(dict(restored=[], lost=[], busy=True), status=409)
+ except (OSError, ValueError, TypeError):
+ return web.json_response(dict(restored=[], lost=[], expired=True), status=410)
+ return web.json_response(result)
+
+ @server.routes.post('/freevideo/library/undo-state')
+ async def undo_status(request):
+ try:
+ body = await request.json()
+ result = await asyncio.to_thread(undo_state, folder_paths.get_output_directory(),
+ body.get('batches') if isinstance(body, dict) else None)
+ except (OSError, ValueError, TypeError):
+ raise web.HTTPBadRequest(text='Invalid selection') from None
+ return web.json_response(dict(batches=result), headers={'Cache-Control': 'no-store'})
+
+ @server.routes.post('/freevideo/library/hold')
+ async def hold(request):
+ try:
+ body = await request.json()
+ result = await asyncio.to_thread(hold_deleted, folder_paths.get_output_directory(),
+ body.get('batches') if isinstance(body, dict) else None,
+ running=body.get('running', False) if isinstance(body, dict) else None)
+ except (OSError, ValueError, TypeError):
+ raise web.HTTPBadRequest(text='Invalid selection') from None
+ return web.json_response(dict(batches=result), headers={'Cache-Control': 'no-store'})
+
+ @server.routes.post('/freevideo/library/sizes')
+ async def sizes(request):
+ try:
+ body = await request.json()
+ result = await asyncio.to_thread(folder_sizes, folder_paths.get_output_directory(),
+ body.get('ids') if isinstance(body, dict) else None)
+ except (OSError, ValueError, TypeError):
+ raise web.HTTPBadRequest(text='Invalid selection') from None
+ return web.json_response(dict(sizes=result), headers={'Cache-Control': 'no-store'})
+
@server.routes.get('/freevideo/library/download')
async def download(request):
try:
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index b2cd7b6..69e205f 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -728,7 +728,7 @@ class Session:
repairable = value['state'] in ('ready', 'invalid')
if active.get('state') == 'running':
labels = {'install': ('Downloading', '正在下载'), 'repair': ('Repairing', '正在修复'),
- 'remove': ('Removing', '正在删除'), 'verify': ('Checking', '正在校验')}
+ 'remove': ('Removing', '正在删除'), 'verify': ('Checking', '正在检查')}
detail = self.t(*labels[active['action']])
elif active.get('state') == 'paused_for_generation':
detail = self.t('Paused while generating', '生成时暂停')
diff --git a/web/library.css b/web/library.css
index b61a2c6..cd8a009 100644
--- a/web/library.css
+++ b/web/library.css
@@ -23,7 +23,7 @@
@media(max-width:900px){.fv-studio.fv-library{width:calc(100vw - 24px);height:calc(100dvh - 24px)}.fv-library-body{grid-template-columns:280px minmax(0,1fr)}.fv-library-detail{padding:20px}}
@media(max-width:680px){
.fv-studio.fv-library{width:calc(100vw - 16px);height:calc(100dvh - 16px)}
- .fv-library .fv-library-header{padding:12px 8px;gap:4px}.fv-library-header h2{font-size:14px}
+ .fv-library .fv-library-header{padding:12px 8px;gap:4px}.fv-library-header h2{font-size:14px;white-space:nowrap;min-width:0;overflow:hidden;text-overflow:ellipsis}
.fv-library-body{height:calc(100% - 63px);display:flex;flex-direction:column}
.fv-library-collection{flex:1;border:0}.fv-library-grid{grid-template-columns:repeat(auto-fill,minmax(135px,1fr))}
.fv-library-detail{flex:1;display:none;gap:14px;padding:14px}.fv-library .fv-library-all{display:inline-flex;align-self:flex-start}
@@ -44,3 +44,28 @@
.fv-library .fv-library-notice{min-height:0;margin:6px 0 0;text-align:center}
.fv-library .fv-library-notice:empty{display:none}
.fv-library .fv-library-picture .fv-agent-badge{position:absolute;top:6px;right:6px;padding:1px 8px;border-radius:999px;font-size:10px;font-weight:var(--fv-medium);color:var(--fv-ink);background:color-mix(in srgb,var(--fv-bg) 72%,transparent);border:1px solid color-mix(in srgb,var(--fv-accent) 55%,transparent);backdrop-filter:blur(4px)}
+/* Selecting several creations to delete together. */
+.fv-library-tools{justify-self:end;display:flex;gap:4px}
+.fv-library .fv-library-picking{position:sticky;top:-18px;z-index:2;display:flex;justify-content:flex-start;gap:4px;margin:-18px -18px 12px;padding:10px 14px;background:var(--fv-bg);border-bottom:1px solid var(--fv-border)}
+.fv-library .fv-library-picking button{min-height:30px;padding:4px 10px;font-size:12px}
+.fv-library .fv-library-day{grid-column:1/-1;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:6px 4px 0;font-size:12px;font-weight:var(--fv-medium);color:var(--fv-ink);text-align:left}
+.fv-library .fv-library-day button{min-height:26px;padding:2px 8px;font-size:12px}
+.fv-library-check{position:absolute;right:6px;bottom:6px;display:none;place-items:center;width:20px;height:20px;border-radius:50%;border:1.5px solid #fff9;background:#0008;color:transparent;font-size:12px;line-height:1}
+.fv-library[data-selecting=true] .fv-library-grid{user-select:none;-webkit-user-select:none}
+.fv-library[data-selecting=true] .fv-library-check{display:grid}
+.fv-library .fv-library-card.fv-picked .fv-library-check{background:var(--fv-accent);border-color:var(--fv-accent);color:var(--fv-bg)}
+.fv-library .fv-library-card.fv-picked{border-color:var(--fv-accent);background:var(--fv-selected)}
+.fv-library[data-selecting=true] .fv-library-card:not(.fv-picked)[aria-pressed=true]{border-color:transparent;background:transparent}
+.fv-library .fv-library-dock{position:sticky;bottom:-18px;z-index:3;margin:0 -18px -18px}.fv-library .fv-library-dock:not(:has(>:not([hidden]))){display:none}
+.fv-library .fv-library-selection{display:grid;gap:6px;margin:14px 0 0;padding:12px 14px;background:var(--fv-bg);border-top:1px solid var(--fv-border);text-align:left}
+.fv-library .fv-library-selection strong{font-size:13px;font-weight:var(--fv-semibold)}
+.fv-library .fv-library-selection small{font-size:12px;line-height:1.55;color:var(--fv-muted)}
+.fv-library .fv-library-selection-actions{display:flex;justify-content:flex-end;gap:8px}
+.fv-library .fv-library-selection-actions button{min-height:34px;padding:0 14px}
+.fv-library .fv-library-danger{border-color:transparent;background:var(--fv-danger-subtle,#30212a);color:var(--fv-danger,#f09aa2)}
+.fv-library .fv-library-danger:hover:not(:disabled){border-color:color-mix(in srgb,var(--fv-danger,#f09aa2) 45%,transparent)}
+.fv-library .fv-library-undo{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:4px 8px;margin:14px 0 0;padding:10px 14px;background:var(--fv-card);border-top:1px solid var(--fv-border);font-size:13px}
+.fv-library .fv-library-undo:not([hidden])~.fv-library-selection:not([hidden]){margin-top:0}
+.fv-library .fv-library-undo button{min-height:28px;padding:2px 10px;font-size:13px;color:var(--fv-accent)}
+.fv-library .fv-library-skipped{flex-basis:100%;font-size:12px;color:var(--fv-muted)}
+@media(max-width:680px){.fv-library-tools{gap:0}.fv-library .fv-library-header{grid-template-columns:auto minmax(0,1fr) auto}.fv-library-header h2{text-align:center}.fv-library-header button{white-space:nowrap}.fv-studio.fv-library .fv-library-header button{padding-left:6px;padding-right:6px}}
diff --git a/web/library.js b/web/library.js
index 2570e15..72f88f0 100644
--- a/web/library.js
+++ b/web/library.js
@@ -14,6 +14,79 @@ const view = file => {
};
let opened;
+// Batches that can still be undone live outside the dialog: closing and reopening it, a
+// page reload, a second delete within the undo time and other tabs all see the same list.
+const UNDO_KEY = 'freevideo.library.undo';
+let undoMemory = [];
+// Batches this page dropped: a store that cannot be written must not bring them back.
+const forgotten = new Set();
+const PENDING_LIMIT = 10 * 60 * 1000;
+const jsonHeaders = {'Content-Type': 'application/json'};
+const undoRows = () => {
+ // What this page knows and what the store holds are joined by batch, so a failed or late write
+ // from one side never drops a batch the other still has; the page's own copy is the newer one.
+ const byToken = new Map();
+ let stored = [];
+ try { const value = JSON.parse(localStorage.getItem(UNDO_KEY)); if (Array.isArray(value)) stored = value; } catch { /* Memory only. */ }
+ for (const row of [...stored, ...undoMemory]) if (row && typeof row.token === 'string' && !forgotten.has(row.token)) byToken.set(row.token, row);
+ const now = Date.now();
+ // A batch still being deleted is kept until the server has answered for it, however long that takes; the
+ // time to undo only runs from the answer. A request the server has never heard of is dropped after a while.
+ return [...byToken.values()].filter(row => row.count > 0 && (row.pending ? row.confirmed || now < (row.born || row.due) + PENDING_LIMIT : row.due > now));
+};
+const saveUndoRows = rows => {
+ undoMemory = rows;
+ try { localStorage.setItem(UNDO_KEY, JSON.stringify(rows)); } catch { /* Memory only. */ }
+};
+// A row is ``pending`` from the request until the server has answered it: the batch may exist already, but it is not offered yet.
+const rememberUndo = (token, count, seconds, pending = false) =>
+ saveUndoRows([...undoRows().filter(row => row.token !== token), {token, count, due: Date.now() + seconds * 1000, pending, born: Date.now()}]);
+const forgetUndo = tokens => { for (const token of tokens) forgotten.add(token); saveUndoRows(undoRows().filter(row => !tokens.includes(row.token))); };
+const setUndoDue = (tokens, seconds) => saveUndoRows(undoRows().map(row => tokens.includes(row.token) ? {...row, due: Date.now() + seconds * 1000} : row));
+// Batches this page is still deleting: they are kept for a reload but are not offered for undo yet.
+const deletingNow = new Set();
+const offeredUndoRows = () => undoRows().filter(row => !deletingNow.has(row.token) && !row.pending);
+const undoChangedHere = () => window.dispatchEvent(new CustomEvent('freevideo-library-undo'));
+// The server is the authority on what can still be undone; what it says replaces what this page guessed.
+const applyUndoStates = states => {
+ const now = Date.now(), before = undoRows();
+ const after = before.flatMap(row => {
+ const state = deletingNow.has(row.token) ? null : states[row.token];
+ if (!state) return [row];
+ if (state.state === 'ready') {
+ const due = now + Math.max(0, Number(state.seconds) || 0) * 1000, count = state.count > 0 ? state.count : row.count;
+ // The server's time moves by the round trip only; that is not a change other tabs need to hear about.
+ return [!row.pending && count === row.count && Math.abs(due - row.due) < 2000 ? row : {...row, pending: false, confirmed: false, count, due}];
+ }
+ // Once the server has said the batch exists, it is kept until the server says it is ready or gone.
+ if (state.state === 'busy') return [row.confirmed && row.due > now + 30000 ? row : {...row, confirmed: true, due: now + 60000}];
+ if (row.pending && !row.confirmed) return [row];
+ forgotten.add(row.token);
+ return [];
+ });
+ // Written only when something changed: two open tabs would otherwise answer each other's writes for ever.
+ if (after.length !== before.length || after.some((row, index) => row !== before[index])) saveUndoRows(after);
+};
+async function askUndoState(path, body) {
+ try {
+ const response = await api.fetchApi(path, {method: 'POST', headers: jsonHeaders, body: JSON.stringify(body), signal: AbortSignal.timeout(5000)});
+ if (!response.ok) return null;
+ return (await response.json()).batches || {};
+ } catch { return null; }
+}
+// Keeps earlier batches of one click undoable while its next request runs, then gives them the normal time again.
+async function holdBatches(tokens, running) {
+ const states = await askUndoState('/freevideo/library/hold', {batches: tokens, running});
+ if (!states) return false;
+ applyUndoStates(states);
+ return true;
+}
+// The page names a batch before asking for the delete, so a reload while it runs still finds it.
+const newBatchName = () => {
+ const random = crypto.getRandomValues(new Uint8Array(3));
+ return `${Date.now()}${String(Math.floor(Math.random() * 1e6)).padStart(6, '0')}-${[...random].map(byte => byte.toString(16).padStart(2, '0')).join('')}`;
+};
+
export async function libraryPage(t, {limit = 24, before = null, signal} = {}) {
const query = new URLSearchParams({limit: String(limit)});
if (before) query.set('before', before);
@@ -96,13 +169,29 @@ export function openLibrary(t, {upscale = null, selectedWork = null, extend = nu
const back = button(backLabel || t('Back to create', '返回创作'), () => closeDialog(dialog), 'fv-quiet');
const title = el('h2', t('Your creations', '我的作品'));
const refresh = button(t('Refresh', '刷新'), () => load(false), 'fv-quiet');
- header.append(back, title, refresh);
+ const choose = button(t('Select', '选择'), () => setSelecting(!selecting), 'fv-quiet fv-library-choose');
+ const tools = el('div', null, 'fv-library-tools'); tools.append(choose, refresh);
+ header.append(back, title, tools);
const body = el('div', null, 'fv-library-body');
const collection = el('section', null, 'fv-library-collection'); collection.setAttribute('aria-label', t('Saved videos', '已保存的视频'));
const grid = el('div', null, 'fv-library-grid');
const message = el('p', '', 'fv-library-message'); message.setAttribute('role', 'status');
const more = button(t('Show more', '加载更多'), () => load(true), 'fv-quiet'); more.hidden = true;
- collection.append(grid, message, more);
+ // Selecting several creations: a strip above the cards, the delete bar below them.
+ const picking = el('div', null, 'fv-library-picking'); picking.hidden = true;
+ const pickAll = button(t('Select all', '全选'), () => selectAll(), 'fv-quiet');
+ const pickNone = button(t('Select none', '全不选'), () => { picked.clear(); syncSelection(); }, 'fv-quiet');
+ picking.append(pickAll, pickNone);
+ const undoBar = el('p', null, 'fv-library-undo'); undoBar.setAttribute('role', 'status'); undoBar.hidden = true;
+ const bar = el('div', null, 'fv-library-selection'); bar.hidden = true;
+ const barLabel = el('strong'), barText = el('small'), barActions = el('div', null, 'fv-library-selection-actions');
+ const barCancel = button(t('Cancel', '取消'), () => { confirming = false; syncSelection(); }, 'fv-quiet');
+ const barDelete = button('', () => confirmDelete(), 'fv-library-danger');
+ barActions.append(barCancel, barDelete);
+ bar.append(barLabel, barText, barActions);
+ // The undo note and the delete bar share one sticky dock so they stack instead of covering each other.
+ const dock = el('div', null, 'fv-library-dock'); dock.append(undoBar, bar);
+ collection.append(picking, grid, message, more, dock);
workflowBackfill(collection, t);
const detail = el('section', null, 'fv-library-detail');
const all = button(t('All creations', '全部作品'), () => {
@@ -119,6 +208,8 @@ export function openLibrary(t, {upscale = null, selectedWork = null, extend = nu
detail.append(all, frame, caption, links, notice, stats, budget);
body.append(collection, detail); dialog.append(header, body);
let disposed = false, loading = false, next = null, selected = null, player = null, arrivals = [];
+ let selecting = false, confirming = false, deleting = false, anchor = null, undoTimer = null, sizeTimer = null, sizeRound = 0;
+ const picked = new Set(), sizes = new Map();
const rows = new Map(), cards = new Map();
const abort = new AbortController();
const narrow = matchMedia('(max-width: 680px)');
@@ -167,7 +258,7 @@ export function openLibrary(t, {upscale = null, selectedWork = null, extend = nu
secondPass: row.preview && upscale ? () => secondPass(row) : null,
remove: () => remove(row)}));
notice.textContent = '';
- for (const [file, card] of cards) card.setAttribute('aria-pressed', String(file === selected));
+ for (const [file, card] of cards) card.setAttribute('aria-pressed', String(selecting ? picked.has(file) : file === selected));
}
// These are the saved generation's measurements, including when the
// same MP4 has since been reused. Never substitute the active request.
@@ -233,6 +324,283 @@ export function openLibrary(t, {upscale = null, selectedWork = null, extend = nu
notice.textContent = t('Deleted.', '已删除。');
if (!rows.size) message.textContent = t('Your finished videos will appear here.', '生成完成的视频会保存在这里。');
}
+ // --- Selecting several creations ---
+ const gb = bytes => `${(bytes / 2 ** 30).toFixed(bytes < 2 ** 30 ? 2 : 1)} GB`;
+ const ordered = () => [...grid.querySelectorAll('.fv-library-card')];
+ const dayOf = video => (rows.get(video)?.id || '').slice(0, 10);
+ const lastDay = () => dayOf(ordered().at(-1)?.dataset.video);
+ const dayName = day => {
+ const [y, m, d] = day.split('-').map(Number), value = new Date(y, (m || 1) - 1, d || 1);
+ return Number.isNaN(value.getTime()) ? day : (t('en', 'zh') === 'zh' ? `${value.getMonth() + 1}月${value.getDate()}日 ${value.toLocaleDateString('zh-CN', {weekday: 'short'})}` : value.toLocaleDateString('en-US', {month: 'long', day: 'numeric', weekday: 'short'}));
+ };
+ // Day headings exist only while selecting; the cards keep their order.
+ function regroup() {
+ for (const heading of grid.querySelectorAll('.fv-library-day')) heading.remove();
+ if (!selecting) return;
+ let day = null;
+ for (const card of ordered()) {
+ const value = dayOf(card.dataset.video);
+ if (value === day) continue;
+ day = value;
+ const heading = el('div', null, 'fv-library-day'); heading.dataset.day = value;
+ const name = el('span', dayName(value));
+ const whole = button('', async () => {
+ if (deleting) return;
+ // The day goes on until a card of an earlier day or the end of the list is loaded.
+ whole.disabled = true;
+ while (next && !disposed && lastDay() === value && await load(true));
+ if (disposed || (next && lastDay() === value)) { whole.disabled = false; return; }
+ const videos = ordered().map(card => card.dataset.video).filter(video => dayOf(video) === value);
+ const all = videos.every(video => picked.has(video));
+ for (const video of videos) all ? picked.delete(video) : picked.add(video);
+ anchor = null; syncSelection();
+ }, 'fv-quiet');
+ heading.append(name, whole);
+ grid.insertBefore(heading, card);
+ }
+ syncSelection();
+ }
+ function pick(video, range) {
+ const list = ordered().map(card => card.dataset.video), to = list.indexOf(video), from = list.indexOf(anchor);
+ if (range && from >= 0 && to >= 0) {
+ const on = !picked.has(video);
+ for (const item of list.slice(Math.min(from, to), Math.max(from, to) + 1)) on ? picked.add(item) : picked.delete(item);
+ } else picked.has(video) ? picked.delete(video) : picked.add(video);
+ anchor = video; confirming = false; syncSelection();
+ }
+ function wantedSizes() {
+ const ids = [...picked].map(video => rows.get(video)?.id).filter(id => id && !sizes.has(id));
+ if (!ids.length) return;
+ clearTimeout(sizeTimer);
+ sizeTimer = setTimeout(async () => {
+ const round = ++sizeRound;
+ try {
+ for (let at = 0; at < ids.length; at += 500) {
+ const response = await api.fetchApi('/freevideo/library/sizes', {method: 'POST',
+ headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ids: ids.slice(at, at + 500)}), signal: abort.signal});
+ if (!response.ok) return;
+ for (const [id, bytes] of Object.entries((await response.json()).sizes || {})) sizes.set(id, bytes);
+ }
+ } catch { return; }
+ if (!disposed && round === sizeRound) syncSelection(false);
+ }, 250);
+ }
+ const pickedSize = () => {
+ let total = 0;
+ for (const video of picked) { const bytes = sizes.get(rows.get(video)?.id); if (bytes == null) return null; total += bytes; }
+ return total;
+ };
+ function syncSelection(fetchSizes = true) {
+ dialog.dataset.selecting = String(selecting);
+ choose.textContent = selecting ? t('Cancel', '取消') : t('Select', '选择');
+ picking.hidden = bar.hidden = !selecting;
+ for (const video of [...picked]) if (!rows.has(video)) picked.delete(video);
+ for (const [video, card] of cards) {
+ card.classList.toggle('fv-picked', selecting && picked.has(video));
+ card.setAttribute('aria-pressed', String(selecting ? picked.has(video) : video === selected));
+ }
+ pickAll.disabled = deleting; pickNone.disabled = deleting || !picked.size;
+ for (const heading of grid.querySelectorAll('.fv-library-day')) {
+ const videos = ordered().map(card => card.dataset.video).filter(video => dayOf(video) === heading.dataset.day);
+ const loaded = !(next && heading.dataset.day === lastDay());
+ heading.lastElementChild.textContent = loaded && videos.length && videos.every(video => picked.has(video)) ? t('Deselect day', '取消这一天') : t('Select day', '选择这一天');
+ }
+ if (!selecting) return;
+ const count = picked.size, size = pickedSize();
+ if (fetchSizes) wantedSizes();
+ const about = size == null ? '' : ` · ${t('about', '约')} ${gb(size)}`;
+ barActions.hidden = !count;
+ barCancel.hidden = !confirming;
+ if (confirming) {
+ barLabel.textContent = t(`Delete ${count} ${count === 1 ? 'creation' : 'creations'}?${size == null ? '' : ` About ${gb(size)}.`}`, `删除 ${count} 个作品?${size == null ? '' : `共约 ${gb(size)}。`}`);
+ barText.textContent = t('The videos and their files will be deleted.', '视频和相关文件都会删除。');
+ barDelete.textContent = deleting ? t('Deleting…', '正在删除…') : t('Delete', '删除');
+ barCancel.disabled = barDelete.disabled = deleting;
+ } else {
+ barLabel.textContent = count ? '' : t('Select creations to delete', '选择要删除的作品');
+ barText.textContent = '';
+ barDelete.textContent = t(`Delete ${count}`, `删除 ${count} 个`) + about;
+ barDelete.disabled = deleting;
+ }
+ barLabel.hidden = !barLabel.textContent; barText.hidden = !barText.textContent;
+ }
+ function setSelecting(value) {
+ if (selecting === value || deleting) return;
+ selecting = value; confirming = false; anchor = null; picked.clear();
+ if (value) dialog.dataset.detail = 'false';
+ else if (!narrow.matches && selected) dialog.dataset.detail = 'true';
+ regroup(); syncSelection();
+ }
+ async function selectAll() {
+ pickAll.disabled = true;
+ while (next && !disposed && await load(true));
+ if (disposed) return;
+ for (const video of rows.keys()) picked.add(video);
+ confirming = false; syncSelection();
+ }
+ async function confirmDelete() {
+ if (!picked.size || deleting) return;
+ if (!confirming) {
+ confirming = true; syncSelection(); barDelete.focus();
+ // The confirmation names the size; wait briefly for it if it has not arrived.
+ if (pickedSize() == null) {
+ for (let wait = 0; wait < 20 && !disposed && pickedSize() == null && confirming; wait++) await new Promise(resolve => setTimeout(resolve, 100));
+ if (!disposed) syncSelection(false);
+ }
+ return;
+ }
+ await removeSelected();
+ }
+ let undoNote = null, undoFailure = '';
+ // Shows what can still be undone: every batch deleted within the undo time, from any
+ // dialog, tab or page load. Without any, only the notes remain.
+ function showUndo() {
+ clearTimeout(undoTimer);
+ if (disposed) return;
+ const live = offeredUndoRows(), deletedCount = live.reduce((sum, row) => sum + row.count, 0);
+ const notes = [undoNote ? el('span', undoNote, 'fv-library-skipped') : null, undoFailure ? el('span', undoFailure, 'fv-library-skipped') : null].filter(Boolean);
+ const settle = () => { if (undoRows().length) { showUndo(); return; } undoNote = null; undoFailure = ''; undoBar.replaceChildren(); undoBar.hidden = true; };
+ undoBar.replaceChildren(); undoBar.hidden = !deletedCount && !notes.length;
+ if (!deletedCount) { undoBar.append(...notes); return; }
+ const tokens = live.map(row => row.token);
+ const text = el('span', t(`Deleted ${deletedCount}`, `已删除 ${deletedCount} 个`));
+ const undo = button(t('Undo', '撤销'), async () => {
+ undo.disabled = true; clearTimeout(undoTimer);
+ let lost = 0, expired = false;
+ const settled = [], again = [];
+ for (const batch of tokens) {
+ try {
+ const response = await api.fetchApi('/freevideo/library/undo', {method: 'POST',
+ headers: {'Content-Type': 'application/json'}, body: JSON.stringify({batch})});
+ if (response.ok) { lost += ((await response.json()).lost || []).length; settled.push(batch); }
+ // Only the server saying the time is over ends a batch; any other failure can be tried again.
+ else if (response.status === 410) { expired = true; settled.push(batch); } else again.push(batch);
+ } catch { again.push(batch); }
+ }
+ forgetUndo(settled);
+ if (settled.length) window.dispatchEvent(new CustomEvent('freevideo-library-restored'));
+ if (disposed) return;
+ if (again.length) {
+ undoFailure = t('Could not undo. Try again.', '没能撤销,请重试。');
+ showUndo();
+ if (settled.length) load(false);
+ return;
+ }
+ undoFailure = '';
+ undoBar.replaceChildren(el('span', expired ? t('The undo time has passed.', '已过了撤销时间。')
+ : lost ? t(`Restored, but ${lost} could not be brought back.`, `已恢复,其中 ${lost} 个没能恢复。`) : t('Restored.', '已恢复。')));
+ undoTimer = setTimeout(settle, 4000);
+ load(false);
+ }, 'fv-quiet');
+ undoBar.append(text, undo, ...notes);
+ undoTimer = setTimeout(settle, Math.min(...live.map(row => row.due)) - Date.now() + 50);
+ }
+ const skippedText = skipped => {
+ const using = skipped.filter(row => row.reason !== 'foreign-files').length, other = skipped.length - using;
+ const folders = (count, en) => count === 1 ? en.replace('folders have', 'folder has') : en;
+ if (using && other) return t(`${using + other} kept: ${using} in use, ${other} ${folders(other, 'folders have')} other files.`, `${using + other} 个已保留:${using} 个正在使用,${other} 个文件夹里有别的文件。`);
+ if (using) return t(`${using} in use, kept.`, `${using} 个正在使用,已保留。`);
+ return t(`${other} ${folders(other, 'folders have')} other files, kept.`, `${other} 个文件夹里有别的文件,已保留。`);
+ };
+ async function removeSelected() {
+ deleting = true; syncSelection();
+ const videos = [...picked], idOf = new Map(videos.map(video => [video, rows.get(video)?.id])), ids = videos.map(video => idOf.get(video)).filter(Boolean);
+ // Windows keeps a streamed video open; release it before deleting.
+ const selectedRow = rows.get(selected);
+ if (picked.has(selected)) releasePlayer();
+ const skipped = [], removed = new Set();
+ let failed = false, unsaved = false;
+ const earlier = [];
+ // A chunk's creations leave the page as soon as the chunk is done, so an undo during a later chunk is not undone by it.
+ const leave = gone => {
+ for (const video of videos) {
+ if (removed.has(video) || !gone.has(idOf.get(video))) continue;
+ removed.add(video);
+ window.dispatchEvent(new CustomEvent('freevideo-library-deleted', {detail: {video}}));
+ if (disposed) continue;
+ rows.delete(video); cards.get(video)?.remove(); cards.delete(video);
+ }
+ };
+ let undoFor = 10;
+ try {
+ for (let at = 0; at < ids.length; at += 500) {
+ const part = ids.slice(at, at + 500), name = newBatchName();
+ // Kept before asking: a page reloaded or closed while the server works still finds the batch and offers the undo.
+ rememberUndo(name, part.length, 120, true);
+ deletingNow.add(name);
+ try {
+ // The chunks already deleted stay undoable while this one runs; the server holds them the same way.
+ if (earlier.length && !await holdBatches(earlier, true)) { forgetUndo([name]); throw new Error('failed'); }
+ // Only an answer from the server that it refused drops the row; a request cut off by a reload
+ // or a lost connection may still have been carried out, so the batch is looked up again.
+ const response = await api.fetchApi('/freevideo/library/delete-batch', {method: 'POST',
+ headers: jsonHeaders, body: JSON.stringify({ids: part, batch: name, extend: earlier})});
+ if (!response.ok) { forgetUndo([name]); throw new Error('failed'); }
+ const value = await response.json();
+ const gone = new Set(value.deleted || []);
+ // A creation that is already gone from disk only needs to leave the page.
+ for (const row of value.skipped || []) {
+ // 'unsaved' and 'failed': the creation could not be noted or touched, so it stayed and is still selected.
+ if (row.reason === 'unavailable') gone.add(row.id); else if (row.reason === 'unsaved' || row.reason === 'failed') unsaved = true; else skipped.push(row);
+ }
+ // The server's own undo time, kept at once so a later chunk that fails, or a closed dialog, cannot lose it.
+ if (value.batch && value.batch !== name) forgetUndo([name]);
+ if (value.batch) { undoFor = Number(value.undo_seconds) || 10; rememberUndo(value.batch, (value.deleted || []).length, earlier.length || at + 500 < ids.length ? 120 : undoFor); earlier.push(value.batch); }
+ else forgetUndo([name]);
+ leave(gone);
+ } finally {
+ deletingNow.delete(name);
+ }
+ // Offered as soon as this chunk is done, not only when the last one is.
+ undoChangedHere();
+ }
+ } catch { failed = true; }
+ if (unsaved) failed = true;
+ // However it ended, the earlier chunks get the normal undo time from now; the server is asked, and
+ // this page's own estimate stands when it cannot answer.
+ if (earlier.length) { setUndoDue(earlier, undoFor); await holdBatches(earlier, false); }
+ deleting = false;
+ undoChangedHere();
+ syncUndo();
+ if (disposed) return;
+ if (!rows.has(selected) && selected) {
+ selected = null; frame.replaceChildren(); links.replaceChildren(); date.textContent = geometry.textContent = '';
+ stats.hidden = true; stats.replaceChildren(); budget.textContent = '';
+ } else if (selectedRow && rows.has(selected) && !player) mountPlayer(selectedRow);
+ if (!rows.size) message.textContent = t('Your finished videos will appear here.', '生成完成的视频会保存在这里。');
+ const kept = new Set(skipped.map(row => row.id));
+ for (const video of videos) if (kept.has(idOf.get(video))) picked.delete(video);
+ undoNote = skipped.length ? skippedText(skipped) : null;
+ if (failed) {
+ // What was deleted keeps its Undo; only the part that is still selected is tried again.
+ for (const video of removed) picked.delete(video);
+ confirming = false;
+ undoFailure = removed.size
+ ? t(`${picked.size} could not be deleted. Try again.`, `还有 ${picked.size} 个没能删除,请重试。`)
+ : t('Could not delete. Try again.', '没能删除,请重试。');
+ if (!picked.size) setSelecting(false); else regroup();
+ } else { undoFailure = ''; setSelecting(false); }
+ if (!selected && !narrow.matches && rows.size) select(rows.values().next().value, false);
+ showUndo();
+ // The delete button is gone; keep the keyboard inside the dialog.
+ if (!dialog.contains(document.activeElement)) choose.focus();
+ }
+ // Asks the server about batches this page did not make or cannot vouch for (after a reload, or while a
+ // request of an earlier page still runs), and again until every pending one is settled.
+ let syncTimer = 0, syncing = false;
+ async function syncUndo() {
+ clearTimeout(syncTimer);
+ if (disposed || syncing) return;
+ const unsure = undoRows().filter(row => !deletingNow.has(row.token)).map(row => row.token).slice(0, 200);
+ if (!unsure.length) return;
+ syncing = true;
+ const states = await askUndoState('/freevideo/library/undo-state', {batches: unsure});
+ syncing = false;
+ if (disposed) return;
+ if (states) applyUndoStates(states);
+ showUndo();
+ if (undoRows().some(row => !deletingNow.has(row.token) && (row.pending || states?.[row.token]?.state === 'busy'))) syncTimer = setTimeout(syncUndo, 1500);
+ }
const thumbnails = new IntersectionObserver(entries => {
for (const {target, isIntersecting} of entries) if (isIntersecting) {
target.src = target.dataset.src; thumbnails.unobserve(target);
@@ -242,14 +610,16 @@ export function openLibrary(t, {upscale = null, selectedWork = null, extend = nu
if (!row?.video) return;
rows.set(row.video, row);
if (cards.has(row.video)) return;
- const card = button('', () => select(rows.get(row.video)), 'fv-library-card');
+ const card = button('', event => selecting ? pick(row.video, event.shiftKey) : select(rows.get(row.video)), 'fv-library-card');
+ card.dataset.video = row.video;
card.setAttribute('aria-label', `${timestamp(row)} · ${dimensions(row)}`);
- card.setAttribute('aria-pressed', String(row.video === selected));
+ card.setAttribute('aria-pressed', String(selecting ? picked.has(row.video) : row.video === selected));
+ card.classList.toggle('fv-picked', selecting && picked.has(row.video));
const picture = el('div', null, 'fv-library-picture');
const image = el('img'); image.alt = ''; image.decoding = 'async';
image.dataset.src = videoThumbnailURL(row);
image.onerror = () => { image.hidden = true; };
- picture.append(image);
+ picture.append(image, el('span', '✓', 'fv-library-check'));
if (row.preview) picture.append(el('span', t('Preview', '预览'), 'fv-preview-badge'));
// Made by an AI agent: say so, with the name the agent gave the shot.
if (row.agent) {
@@ -259,10 +629,11 @@ export function openLibrary(t, {upscale = null, selectedWork = null, extend = nu
}
card.append(picture, el('span', row.agent?.label || timestamp(row)), el('small', row.agent?.label ? timestamp(row) : dimensions(row)));
cards.set(row.video, card); first ? grid.prepend(card) : grid.append(card); thumbnails.observe(image);
+ if (selecting) regroup();
}
async function load(appendPage) {
- if (loading || disposed) return;
- loading = true; arrivals = []; refresh.disabled = more.disabled = true;
+ if (loading || disposed) return false;
+ loading = true; arrivals = []; refresh.disabled = more.disabled = true; let ok = false;
message.textContent = rows.size ? '' : t('Loading your creations…', '正在读取作品…');
try {
const data = await libraryPage(t, {before: appendPage ? next : null, signal: abort.signal}); if (disposed) return;
@@ -277,9 +648,11 @@ export function openLibrary(t, {upscale = null, selectedWork = null, extend = nu
if (!narrow.matches && rows.size) select(rows.values().next().value, false);
else dialog.dataset.detail = 'false';
} else select(rows.get(selected), false);
+ ok = true; regroup();
if (selectedWork) { const row = [...rows.values()].find(row => row.id === selectedWork || row.video === selectedWork); if (row) { select(row); selectedWork = null; } else if (next) queueMicrotask(() => load(true)); }
} catch (error) { if (!disposed && error.name !== 'AbortError') message.textContent = error.message; }
finally { if (!disposed) { loading = false; refresh.disabled = more.disabled = false; } }
+ return ok;
}
const completed = event => {
const row = event.detail?.value;
@@ -292,11 +665,23 @@ export function openLibrary(t, {upscale = null, selectedWork = null, extend = nu
if (!selected && !narrow.matches) select(rows.get(row.video), false);
};
window.addEventListener('freevideo-result', completed);
- dialog.addEventListener('cancel', event => { event.preventDefault(); closeDialog(dialog); });
+ dialog.addEventListener('cancel', event => { event.preventDefault(); if (selecting && !deleting) setSelecting(false); else closeDialog(dialog); });
dialog.onclose = () => {
- disposed = true; abort.abort(); thumbnails.disconnect(); releasePlayer();
- window.removeEventListener('freevideo-result', completed); dialog.remove();
+ disposed = true; abort.abort(); thumbnails.disconnect(); releasePlayer(); clearTimeout(undoTimer); clearTimeout(sizeTimer); clearTimeout(syncTimer);
+ window.removeEventListener('freevideo-result', completed); window.removeEventListener('storage', undoChanged); window.removeEventListener('freevideo-library-undo', showUndo); window.removeEventListener('freevideo-library-deleted', deletedElsewhere); dialog.remove();
if (opened === dialog) opened = null;
};
- document.body.append(dialog); dialog.showModal(); load(false);
+ // Another tab undid or added a batch, or this one is opened again within the undo time.
+ const undoChanged = event => { if (!event.key || event.key === UNDO_KEY) { showUndo(); syncUndo(); } };
+ window.addEventListener('storage', undoChanged); window.addEventListener('freevideo-library-undo', showUndo);
+ // A delete that an earlier opening of the dialog is still carrying out takes its creations off this one too.
+ const deletedElsewhere = event => {
+ const video = event.detail?.video;
+ if (!video || !rows.has(video)) return;
+ rows.delete(video); cards.get(video)?.remove(); cards.delete(video);
+ if (selected === video) { selected = null; frame.replaceChildren(); links.replaceChildren(); date.textContent = geometry.textContent = ''; stats.hidden = true; stats.replaceChildren(); budget.textContent = ''; dialog.dataset.detail = 'false'; }
+ picked.delete(video);
+ };
+ window.addEventListener('freevideo-library-deleted', deletedElsewhere);
+ document.body.append(dialog); dialog.showModal(); load(false); showUndo(); syncUndo();
}
diff --git a/web/result_actions.js b/web/result_actions.js
index 68d5690..17a2856 100644
--- a/web/result_actions.js
+++ b/web/result_actions.js
@@ -83,10 +83,10 @@ function deleteAction(t, remove) {
const label = document.createElement('span'); label.textContent = t('Delete', '删除');
summary.append(icon('trash'), label);
const panel = document.createElement('div'); panel.className = 'fv-menu fv-confirm';
- const title = document.createElement('strong'); title.textContent = t('Delete this creation?', '删除这条作品?');
+ const title = document.createElement('strong'); title.textContent = t('Delete this creation?', '删除这个作品?');
const hint = document.createElement('small');
- hint.textContent = t('The video, its generation records and preview data are removed. This cannot be undone.',
- '视频、生成记录和预览数据都会删除,无法恢复。');
+ hint.textContent = t('The video and its files will be deleted.',
+ '视频和相关文件都会删除。');
const problem = document.createElement('small'); problem.className = 'fv-confirm-problem'; problem.hidden = true;
const row = document.createElement('div'); row.className = 'fv-confirm-actions';
const cancel = action('button', t('Cancel', '取消'), null, 'fv-action-secondary');
diff --git a/web/studio_recent.js b/web/studio_recent.js
index 222e7b5..a9de9ab 100644
--- a/web/studio_recent.js
+++ b/web/studio_recent.js
@@ -90,10 +90,12 @@ export function createRecentVideos(t, {body, onSelect}) {
};
window.addEventListener('freevideo-result', completed);
window.addEventListener('freevideo-library-deleted', deleted);
+ window.addEventListener('freevideo-library-restored', refresh);
return {element, toggle, refresh, setSelected, dispose() {
disposed = true; request?.abort(); thumbnails.disconnect();
clearTimeout(resizeTimer); body.classList.remove('fv-recent-resizing');
window.removeEventListener('freevideo-result', completed);
window.removeEventListener('freevideo-library-deleted', deleted);
+ window.removeEventListener('freevideo-library-restored', refresh);
}};
}