CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder. Closes #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
639 lines
31 KiB
JavaScript
639 lines
31 KiB
JavaScript
// Videos (owner review 1, R9; decision 22): every render of the server in one list (GET /api/v1/videos), as cards or
|
||
// rows, with the filters in the address (#/videos?sequence=<id> is a sequence's "All videos"). The panel manages and never
|
||
// edits (owner review 2, R6): it plays a render in the browser, downloads it, copies it hash-verified into the server's
|
||
// videos folder (a video-copy job) and deletes it into the archive's trash after a dry run that names what goes, whose
|
||
// fingerprint the delete sends back. Restoring goes through Library › Trash. Nothing here renders or changes a project.
|
||
import { t, applyStrings } from "../i18n.js";
|
||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, routeParams, redraw } from "../ui.js";
|
||
import { icons } from "../icons.js";
|
||
import { lazyImage, watchImages, Selection, selectableGrid, listed, JOB_ENDED } from "./library/shared.js";
|
||
|
||
const VIEW_KEY = "chronos.admin.videos.view";
|
||
const PAGE = 100;
|
||
/** The most a refresh reads back in one request (VideoQuery.MaxLimit). */
|
||
const MAX_PAGE = 500;
|
||
const KINDS = ["video", "still", "sequence"];
|
||
const SORTS = ["newest", "oldest", "largest", "title"];
|
||
const FILTERS = ["q", "kind", "codec", "year", "sequence", "sort"];
|
||
/** Permissions bits (Chronos.Core.Model.Permissions): copying needs Edit, deleting Delete. */
|
||
const EDIT = 4;
|
||
const DELETE = 8;
|
||
/** File types a browser plays in a <video> element, and those it shows as an image (stills, GIF, APNG). */
|
||
const VIDEO_TYPES = new Set(["mp4", "m4v", "mov", "webm"]);
|
||
const IMAGE_TYPES = new Set(["png", "apng", "jpg", "jpeg", "gif", "webp"]);
|
||
const CODECS = { h264: "H.264", hevc: "HEVC", av1: "AV1", mjpeg: "MJPEG", gif: "GIF", apng: "APNG" };
|
||
|
||
export async function render(root, { api, setMeta, actions, onEvent }) {
|
||
const params = routeParams();
|
||
const filters = Object.fromEntries(FILTERS.map((f) => [f, params.get(f) ?? ""]));
|
||
if (!SORTS.includes(filters.sort)) filters.sort = "newest";
|
||
if (!KINDS.includes(filters.kind)) filters.kind = "";
|
||
let view = storedView();
|
||
let rows = [];
|
||
let cursor = null;
|
||
let total = null;
|
||
let generation = 0;
|
||
let refreshTimer = null;
|
||
/** Codecs and years of the videos seen on this page, offered by their menus (the API has no facets for them). */
|
||
const codecs = new Set();
|
||
const years = new Set();
|
||
const selection = new Selection();
|
||
/** Sequence titles read for the sequence filter, by id. */
|
||
const titles = new Map();
|
||
const user = api.user();
|
||
const may = (bit) => (Number(user?.permissions ?? 0) & bit) !== 0;
|
||
/** The server's videos folder: "" when none is set (Copy is off), null while unknown (the server decides). */
|
||
let folder = null;
|
||
api.get("/api/v1/server/settings").then((s) => {
|
||
folder = s.videosPath ?? "";
|
||
if (root.isConnected) drawMass();
|
||
}, () => {});
|
||
|
||
actions.innerHTML = `
|
||
<a class="btn" href="#/library?view=trash" data-i18n-title="Admin.Videos.Trash.Tip">${icons.trash}<span data-i18n="Admin.Library.Trash"></span></a>
|
||
<button class="btn icon" id="refresh" data-i18n-title="Admin.Library.Refresh.Tip">${icons.refresh}</button>`;
|
||
applyStrings(actions);
|
||
actions.querySelector("#refresh").addEventListener("click", () => load());
|
||
|
||
root.innerHTML = `
|
||
<div class="toolbar" role="search">
|
||
<input class="input search" type="search" id="q" dir="auto" value="${attr(filters.q)}" data-i18n-placeholder="Admin.Videos.Search"
|
||
data-i18n-title="Admin.Videos.Search.Tip" aria-label="${attr(t("Admin.Videos.Search"))}">
|
||
<select class="input small" id="kind" data-i18n-title="Admin.Videos.Kind.Tip" aria-label="${attr(t("Admin.Videos.Kind"))}"></select>
|
||
<select class="input small" id="codec" data-i18n-title="Admin.Videos.Codec.Tip" aria-label="${attr(t("Admin.Videos.Codec"))}"></select>
|
||
<select class="input small" id="year" data-i18n-title="Admin.Videos.Year.Tip" aria-label="${attr(t("Admin.Videos.Year"))}"></select>
|
||
<select class="input small" id="sort" data-i18n-title="Admin.Videos.Sort.Tip" aria-label="${attr(t("Admin.Videos.Sort"))}">${SORTS.map((s) =>
|
||
`<option value="${s}" ${s === filters.sort ? "selected" : ""}>${escapeHtml(t(`Admin.Videos.Sort.${cap(s)}`))}</option>`).join("")}</select>
|
||
<span class="inline" id="sequence-filter"></span>
|
||
<button class="btn small" id="clear" data-i18n="Admin.Library.ClearFilters" data-i18n-title="Admin.Library.ClearFilters.Tip" hidden></button>
|
||
<span class="spacer"></span>
|
||
<div class="segmented" role="group" aria-label="${attr(t("Admin.Library.View"))}">
|
||
<button class="btn icon" data-view="cards" aria-pressed="${view === "cards"}" data-i18n-title="Admin.Videos.View.Cards.Tip"
|
||
aria-label="${attr(t("Admin.Videos.View.Cards"))}">${icons.grid}</button>
|
||
<button class="btn icon" data-view="list" aria-pressed="${view === "list"}" data-i18n-title="Admin.Videos.View.List.Tip"
|
||
aria-label="${attr(t("Admin.Videos.View.List"))}">${icons.list}</button>
|
||
</div>
|
||
</div>
|
||
<section class="panel flush library" aria-label="${attr(t("Admin.Videos.Title"))}">
|
||
<div id="items"></div>
|
||
<div class="table-foot" id="foot" hidden><span class="muted" id="shown"></span><span class="spacer"></span>
|
||
<button class="btn small" id="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
|
||
</section>
|
||
<div class="mass-bar" id="mass" role="toolbar" aria-label="${attr(t("Admin.Library.Selection"))}" hidden></div>`;
|
||
applyStrings(root);
|
||
const itemsHost = root.querySelector("#items");
|
||
const mass = root.querySelector("#mass");
|
||
|
||
let searchTimer = null;
|
||
root.querySelector("#q").addEventListener("input", (e) => {
|
||
clearTimeout(searchTimer);
|
||
searchTimer = setTimeout(() => setFilter("q", e.target.value.trim()), 300);
|
||
});
|
||
for (const f of ["kind", "codec", "year", "sort"]) root.querySelector(`#${f}`).addEventListener("change", (e) => setFilter(f, e.target.value));
|
||
root.querySelector("#clear").addEventListener("click", clearFilters);
|
||
root.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => {
|
||
view = b.dataset.view;
|
||
root.querySelectorAll("[data-view]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
|
||
try {
|
||
localStorage.setItem(VIEW_KEY, view);
|
||
} catch {
|
||
// Only this page keeps the view then.
|
||
}
|
||
draw();
|
||
}));
|
||
root.querySelector("#more").addEventListener("click", () => load(true));
|
||
|
||
const grid = selectableGrid(itemsHost, {
|
||
selection,
|
||
order: () => rows.map((v) => v.id),
|
||
open: (key) => play(rows.find((v) => v.id === key)),
|
||
onChange: syncSelection,
|
||
});
|
||
|
||
function setFilter(name, value) {
|
||
if (filters[name] === value) return;
|
||
filters[name] = value;
|
||
writeAddress();
|
||
selection.clear();
|
||
load();
|
||
}
|
||
|
||
function clearFilters() {
|
||
for (const f of FILTERS) filters[f] = f === "sort" ? filters.sort : "";
|
||
root.querySelector("#q").value = "";
|
||
writeAddress();
|
||
selection.clear();
|
||
load();
|
||
root.querySelector("#q").focus();
|
||
}
|
||
|
||
/** The address keeps the filters (no hashchange: the page stays), so a reload or a link shows the same list. */
|
||
function writeAddress() {
|
||
const query = new URLSearchParams(Object.entries(filters).filter(([k, v]) => v && !(k === "sort" && v === "newest")));
|
||
history.replaceState(null, "", `#/videos${query.size ? `?${query}` : ""}`);
|
||
}
|
||
|
||
function isFiltered() {
|
||
return FILTERS.some((f) => f !== "sort" && filters[f]);
|
||
}
|
||
|
||
function listQuery(limit, after) {
|
||
const p = new URLSearchParams({ limit: String(limit) });
|
||
for (const f of ["q", "kind", "codec", "year", "sequence"]) if (filters[f]) p.set(f, filters[f]);
|
||
if (filters.sort !== "newest") p.set("sort", filters.sort);
|
||
if (after) p.set("cursor", after);
|
||
return `/api/v1/videos?${p}`;
|
||
}
|
||
|
||
async function load(more = false) {
|
||
const mine = ++generation;
|
||
let page;
|
||
try {
|
||
page = await api.get(listQuery(PAGE, more ? cursor : null));
|
||
} catch (err) {
|
||
if (mine !== generation || !root.isConnected) return;
|
||
toast(errorText(err), true);
|
||
if (!more && rows.length === 0) draw();
|
||
return;
|
||
}
|
||
if (mine !== generation || !root.isConnected) return;
|
||
cursor = page.next ?? null;
|
||
if (!more) total = page.total ?? null;
|
||
learn(page.items);
|
||
if (more) {
|
||
rows = rows.concat(page.items);
|
||
itemsHost.insertAdjacentHTML("beforeend", page.items.map(itemHtml).join(""));
|
||
watchImages(itemsHost);
|
||
grid.restore();
|
||
syncSelection();
|
||
} else {
|
||
rows = page.items;
|
||
draw();
|
||
}
|
||
drawFilters();
|
||
drawFoot();
|
||
}
|
||
|
||
/** The videos shown again (a job ended, a sequence changed), as many as are shown; the selection keeps those still there. */
|
||
async function refreshVisible() {
|
||
const mine = ++generation;
|
||
const wanted = Math.max(rows.length, PAGE);
|
||
let items = [];
|
||
let after = null;
|
||
let counted = total;
|
||
try {
|
||
do {
|
||
const page = await api.get(listQuery(Math.min(wanted - items.length, MAX_PAGE), after));
|
||
if (items.length === 0) counted = page.total ?? null;
|
||
items = items.concat(page.items);
|
||
after = page.next ?? null;
|
||
} while (after && items.length < wanted);
|
||
} catch {
|
||
// The next event or Refresh tries again.
|
||
return;
|
||
}
|
||
if (mine !== generation || !root.isConnected) return;
|
||
rows = items;
|
||
cursor = after;
|
||
total = counted;
|
||
learn(rows);
|
||
const known = new Set(rows.map((v) => v.id));
|
||
selection.set([...selection.ids].filter((id) => known.has(id)));
|
||
const focused = itemsHost.contains(document.activeElement);
|
||
draw();
|
||
grid.restore(focused);
|
||
drawFilters();
|
||
drawFoot();
|
||
}
|
||
|
||
function refreshSoon(delay) {
|
||
clearTimeout(refreshTimer);
|
||
refreshTimer = setTimeout(() => {
|
||
if (root.isConnected) refreshVisible();
|
||
}, delay);
|
||
}
|
||
|
||
function learn(items) {
|
||
for (const v of items) {
|
||
if (v.codec) codecs.add(v.codec.toLowerCase());
|
||
years.add(String(new Date(v.created).getUTCFullYear()));
|
||
}
|
||
}
|
||
|
||
function drawFilters() {
|
||
const option = (value, label, chosen) => `<option value="${attr(value)}" ${value === chosen ? "selected" : ""}>${escapeHtml(label)}</option>`;
|
||
// A value of the address no video shown has stays in its menu, so the filter shows what the list does.
|
||
const withChosen = (set, chosen) => [...new Set([...set, ...(chosen ? [chosen] : [])])].sort();
|
||
root.querySelector("#kind").innerHTML = option("", t("Admin.Videos.Kind.All"), filters.kind) +
|
||
KINDS.map((k) => option(k, t(`Admin.Videos.Kind.${cap(k)}`), filters.kind)).join("");
|
||
root.querySelector("#codec").innerHTML = option("", t("Admin.Videos.Codec.All"), filters.codec) +
|
||
withChosen(codecs, filters.codec).map((c) => option(c, codecLabel(c), filters.codec)).join("");
|
||
root.querySelector("#year").innerHTML = option("", t("Admin.Videos.Year.All"), filters.year) +
|
||
withChosen(years, filters.year).reverse().map((y) => option(y, y, filters.year)).join("");
|
||
root.querySelectorAll(".toolbar select").forEach((s) => s.classList.toggle("active", s.id !== "sort" && s.value !== ""));
|
||
root.querySelector("#clear").hidden = !isFiltered();
|
||
// One sequence's videos ("All videos" of a sequence page): its title, which opens it, and × for every sequence's
|
||
// videos again (the other filters stay).
|
||
const title = filters.sequence ? rows.find((v) => v.sequenceId === filters.sequence)?.sequenceTitle ?? sequenceTitle(filters.sequence) : null;
|
||
const chip = root.querySelector("#sequence-filter");
|
||
chip.innerHTML = filters.sequence ? `<a class="pill" href="#/library?id=${attr(encodeURIComponent(filters.sequence))}" dir="auto"
|
||
title="${attr(t("Admin.Library.Open.Tip"))}">${escapeHtml(title ?? "…")}</a>
|
||
<button class="btn icon small subtle" id="clear-sequence" data-i18n-title="Admin.Videos.Sequence.Clear.Tip"
|
||
aria-label="${attr(t("Admin.Videos.Sequence.Clear.Tip"))}">${icons.close}</button>` : "";
|
||
applyStrings(chip);
|
||
chip.querySelector("#clear-sequence")?.addEventListener("click", () => setFilter("sequence", ""));
|
||
setMeta(title ?? "");
|
||
}
|
||
|
||
/**
|
||
* The title of a sequence none of whose videos is on the page (a filter that matches nothing, or its videos further
|
||
* down): read once from the sequence's own record, and the chip redrawn when it comes; undefined until then.
|
||
*/
|
||
function sequenceTitle(id) {
|
||
if (titles.has(id)) return titles.get(id);
|
||
titles.set(id, undefined);
|
||
api.get(`/api/v1/sequences/${encodeURIComponent(id)}`).then((s) => {
|
||
titles.set(id, s.title ?? "");
|
||
if (root.isConnected && filters.sequence === id) drawFilters();
|
||
}, () => {});
|
||
return undefined;
|
||
}
|
||
|
||
function draw() {
|
||
itemsHost.className = `seq-items video-items ${view === "list" ? "rows" : "cards"}`;
|
||
itemsHost.setAttribute("role", "listbox");
|
||
itemsHost.setAttribute("aria-multiselectable", "true");
|
||
itemsHost.setAttribute("aria-label", t("Admin.Videos.Title"));
|
||
if (rows.length === 0) {
|
||
itemsHost.removeAttribute("role");
|
||
itemsHost.removeAttribute("aria-multiselectable");
|
||
itemsHost.innerHTML = emptyState("Admin.Videos.Empty", isFiltered()
|
||
? `<button class="btn small" id="clear-empty" data-i18n="Admin.Library.ClearFilters" data-i18n-title="Admin.Library.ClearFilters.Tip"></button>` : "");
|
||
applyStrings(itemsHost);
|
||
itemsHost.querySelector("#clear-empty")?.addEventListener("click", clearFilters);
|
||
syncSelection();
|
||
return;
|
||
}
|
||
const head = view === "list" ? `<div class="seq-head" aria-hidden="true"><span></span><span></span>
|
||
<span data-i18n="Admin.Videos.Column.Title"></span><span class="col-kind" data-i18n="Admin.Videos.Column.Kind"></span>
|
||
<span class="col-format" data-i18n="Admin.Videos.Column.Format"></span><span class="end col-duration" data-i18n="Admin.Videos.Column.Duration"></span>
|
||
<span class="end col-bytes" data-i18n="Admin.Videos.Column.Size"></span><span class="col-date" data-i18n="Admin.Videos.Column.Date"></span>
|
||
<span class="col-hash" data-i18n="Admin.Videos.Column.Hash"></span><span data-i18n="Admin.Videos.Column.State"></span></div>` : "";
|
||
itemsHost.innerHTML = head + rows.map(itemHtml).join("");
|
||
applyStrings(itemsHost);
|
||
watchImages(itemsHost);
|
||
grid.restore();
|
||
syncSelection();
|
||
}
|
||
|
||
function itemHtml(v) {
|
||
const kind = videoKind(v);
|
||
const format = formatText(v);
|
||
const length = kind === "still" ? "" : clock(v.durationSeconds);
|
||
const label = [v.sequenceTitle, v.presetName, format, length, formatBytes(v.bytes)].filter(Boolean).join(" · ");
|
||
const check = `<input type="checkbox" class="seq-check" data-check tabindex="-1" aria-hidden="true" title="${attr(t("Admin.Videos.Select.Tip"))}">`;
|
||
const thumb = lazyImage(posterUrl(v));
|
||
const missing = v.state === "missing" ? " missing" : "";
|
||
if (view === "list") {
|
||
return `<div class="seq-row${missing}" role="option" data-key="${attr(v.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Videos.Play.Tip"))}">
|
||
${check}${thumb}
|
||
<span class="stack"><strong class="ellipsis" dir="auto">${escapeHtml(v.sequenceTitle)}</strong>
|
||
<small dir="auto">${escapeHtml(presetText(v))}</small></span>
|
||
<span class="nowrap col-kind">${escapeHtml(kindText(kind))}</span>
|
||
<span class="num nowrap col-format" dir="ltr">${escapeHtml(format)}</span>
|
||
<span class="num end nowrap col-duration">${escapeHtml(length || "—")}</span>
|
||
<span class="num end nowrap col-bytes">${escapeHtml(formatBytes(v.bytes))}</span>
|
||
<span class="muted nowrap col-date">${escapeHtml(formatDateTime(v.created))}</span>
|
||
<span class="mono muted nowrap col-hash" dir="ltr" title="${attr(v.sha256 ?? "")}">${escapeHtml(shortHash(v.sha256))}</span>
|
||
<span class="chips-row">${stateChips(v)}</span>
|
||
</div>`;
|
||
}
|
||
return `<div class="seq-card${missing}" role="option" data-key="${attr(v.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Videos.Play.Tip"))}">
|
||
${thumb}${check}
|
||
<span class="count num" aria-hidden="true">${escapeHtml(length || kindText(kind))}</span>
|
||
<span class="info"><strong class="ellipsis" dir="auto">${escapeHtml(v.sequenceTitle)}</strong>
|
||
<span class="facts ellipsis" dir="auto">${escapeHtml(presetText(v))}</span>
|
||
<span class="facts ellipsis num" dir="ltr">${escapeHtml([format, formatBytes(v.bytes)].join(" · "))}</span>
|
||
<span class="facts ellipsis">${escapeHtml(formatDateTime(v.created))}</span>
|
||
<span class="chips-row">${stateChips(v)}</span></span>
|
||
</div>`;
|
||
}
|
||
|
||
function drawFoot() {
|
||
const known = total ?? rows.length;
|
||
root.querySelector("#foot").hidden = rows.length === 0 || (!cursor && rows.length >= known);
|
||
root.querySelector("#more").hidden = !cursor;
|
||
root.querySelector("#shown").textContent = t("Admin.Library.Shown", formatNumber(rows.length), total === null ? "…" : formatNumber(total));
|
||
}
|
||
|
||
function syncSelection() {
|
||
itemsHost.querySelectorAll('[role="option"]').forEach((el) => {
|
||
const on = selection.has(el.dataset.key);
|
||
el.setAttribute("aria-selected", String(on));
|
||
const box = el.querySelector("[data-check]");
|
||
if (box) box.checked = on;
|
||
});
|
||
itemsHost.classList.toggle("selecting", selection.size > 0);
|
||
drawMass();
|
||
}
|
||
|
||
/** The selection's actions: Play and Download for one video, Copy to folder and Delete… for any number. */
|
||
function drawMass() {
|
||
const n = selection.size;
|
||
if (n === 0) {
|
||
mass.hidden = true;
|
||
mass.innerHTML = "";
|
||
return;
|
||
}
|
||
const one = n === 1;
|
||
const [only] = selection.ids;
|
||
const downloadWhy = one ? downloadBlock(rows.find((v) => v.id === only)) : "Admin.Videos.Download.One.Tip";
|
||
const copyWhy = !may(EDIT) ? "Admin.Videos.Copy.NoRight.Tip" : folder === "" ? "Admin.Videos.Copy.NoFolder.Tip" : null;
|
||
const deleteWhy = may(DELETE) ? null : "Admin.Videos.Delete.NoRight.Tip";
|
||
mass.hidden = false;
|
||
redraw(mass, () => {
|
||
mass.innerHTML = `
|
||
<strong class="nowrap" role="status">${escapeHtml(t("Admin.Videos.Selected", formatNumber(n)))}</strong>
|
||
${n < rows.length ? `<button class="btn small subtle" id="mass-all" data-mass="all" data-i18n="Admin.Sequence.SelectAll" data-i18n-title="Admin.Videos.SelectAll.Tip"></button>` : ""}
|
||
<span class="spacer"></span>
|
||
<button class="btn small" id="mass-play" data-mass="play" data-i18n-title="${one ? "Admin.Videos.Play.Tip" : "Admin.Videos.Play.One.Tip"}"
|
||
${one ? "" : "disabled"}>${icons.play}<span data-i18n="Admin.Videos.Play"></span></button>
|
||
<button class="btn small" id="mass-download" data-mass="download" data-i18n-title="${downloadWhy ?? "Admin.Videos.Download.Tip"}"
|
||
${downloadWhy ? "disabled" : ""}>${icons.download}<span data-i18n="Admin.Videos.Download"></span></button>
|
||
<button class="btn small" id="mass-copy" data-mass="copy" data-i18n-title="${copyWhy ?? "Admin.Videos.Copy.Tip"}"
|
||
${copyWhy ? "disabled" : ""}>${icons.copyToFolder}<span data-i18n="Admin.Videos.Copy"></span></button>
|
||
<button class="btn small destructive" id="mass-delete" data-mass="delete" data-i18n="Admin.Videos.Delete"
|
||
data-i18n-title="${deleteWhy ?? "Admin.Videos.Delete.Tip"}" ${deleteWhy ? "disabled" : ""}></button>
|
||
<button class="btn small icon subtle" id="mass-clear" data-mass="clear" data-i18n-title="Admin.Library.ClearSelection.Tip">${icons.close}</button>`;
|
||
applyStrings(mass);
|
||
});
|
||
mass.querySelectorAll("[data-mass]").forEach((b) => b.addEventListener("click", () => massAction(b.dataset.mass, b)));
|
||
}
|
||
|
||
async function massAction(action, button) {
|
||
const [only] = selection.ids;
|
||
switch (action) {
|
||
case "clear":
|
||
selection.clear();
|
||
syncSelection();
|
||
return grid.restore(true);
|
||
case "all":
|
||
selection.set(rows.map((v) => v.id));
|
||
return syncSelection();
|
||
case "play":
|
||
return play(rows.find((v) => v.id === only));
|
||
case "download":
|
||
return download(rows.find((v) => v.id === only));
|
||
}
|
||
button.disabled = true;
|
||
try {
|
||
if (action === "copy") await copyVideos([...selection.ids]);
|
||
else if (action === "delete") await deleteVideos([...selection.ids]);
|
||
} finally {
|
||
if (button.isConnected) drawMass();
|
||
}
|
||
}
|
||
|
||
function download(v) {
|
||
if (!v || downloadBlock(v)) return;
|
||
const a = document.createElement("a");
|
||
a.href = fileUrl(v);
|
||
a.download = v.fileName ?? "";
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
a.remove();
|
||
}
|
||
|
||
/** One video-copy job for the selection; the server checks every copy against its render's hash. */
|
||
async function copyVideos(ids) {
|
||
let result;
|
||
try {
|
||
result = await api.post("/api/v1/videos/copy", { ids });
|
||
} catch (err) {
|
||
// videos_folder_unset: the folder went since the page read it; Copy says why from now on.
|
||
if (err.code === "videos_folder_unset") folder = "";
|
||
toast(errorText(err), true);
|
||
return;
|
||
}
|
||
toast(t("Admin.Videos.Copy.Queued", formatNumber(ids.length)), false,
|
||
{ label: t("Admin.Convert.OpenJob"), tip: t("Admin.Convert.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(result.jobId)}` });
|
||
}
|
||
|
||
/**
|
||
* The dry run (what goes, its bytes, what stays and why), the confirmation saying the videos folder's copies stay, then
|
||
* the move into the trash with the plan's fingerprint: a plan that changed meanwhile (409 plan_changed) moves nothing.
|
||
*/
|
||
async function deleteVideos(ids) {
|
||
let plan;
|
||
try {
|
||
plan = await api.post("/api/v1/videos/delete", { ids, dryRun: true, fingerprint: null });
|
||
} catch (err) {
|
||
toast(errorText(err), true);
|
||
return;
|
||
}
|
||
const known = new Map(rows.map((v) => [v.id, v]));
|
||
const name = (id) => {
|
||
const v = known.get(id);
|
||
return v ? `${v.sequenceTitle} · ${v.fileName ?? v.presetName}` : id;
|
||
};
|
||
const blocked = plan.blocked.map((b) => t("Admin.Library.BlockedItem", name(b.id), blockedText(b.reason)));
|
||
if (plan.items.length === 0) {
|
||
toast(blocked.join(" · ") || t("Admin.Videos.Empty"), true);
|
||
return;
|
||
}
|
||
const going = plan.items.map((i) => i.missing
|
||
? t("Admin.Library.BlockedItem", `${i.sequenceTitle} · ${i.fileName ?? "—"}`, t("Admin.Videos.Delete.Missing"))
|
||
: t("Admin.Trash.PlanItem", i.sequenceTitle, i.fileName ?? "—", formatBytes(i.bytes)));
|
||
const confirmed = await confirmDialog({
|
||
title: t("Admin.Videos.Delete.Title"),
|
||
body: [t("Admin.Videos.Delete.Summary", formatNumber(plan.items.length), formatBytes(plan.bytes)),
|
||
plan.blocked.length > 0 ? t("Admin.Videos.Delete.Blocked", formatNumber(plan.blocked.length)) : "",
|
||
t("Admin.Videos.Delete.CopiesStay")].filter(Boolean).join(" "),
|
||
// Those that stay first, with their reasons; the summary counts what goes.
|
||
list: listed([...blocked, ...going]),
|
||
confirm: t("Admin.Videos.Delete.Confirm"),
|
||
confirmTip: t("Admin.Videos.Delete.Confirm.Tip"),
|
||
cancel: t("Admin.Common.Keep"),
|
||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||
});
|
||
if (!confirmed) return;
|
||
let result;
|
||
try {
|
||
result = await api.post("/api/v1/videos/delete", { ids, dryRun: false, fingerprint: plan.fingerprint });
|
||
} catch (err) {
|
||
toast(errorText(err), true);
|
||
if (err.code === "plan_changed") await load();
|
||
return;
|
||
}
|
||
toast(t("Admin.Videos.Delete.Done", formatNumber(result.items.length)), false,
|
||
{ label: t("Admin.Library.Trash"), tip: t("Admin.Videos.Trash.Tip"), href: "#/library?view=trash" });
|
||
selection.clear();
|
||
await load();
|
||
}
|
||
|
||
/**
|
||
* The player: a <video> with its controls for MP4, MOV and WebM (the session cookie authorises its range requests), an
|
||
* image for stills, GIF and APNG, else (or when the browser cannot decode it) a sentence and the download. Esc closes.
|
||
*/
|
||
function play(v) {
|
||
if (!v) return;
|
||
const opener = document.activeElement;
|
||
const dialog = document.createElement("dialog");
|
||
dialog.className = "dialog viewer player";
|
||
dialog.setAttribute("aria-labelledby", "player-title");
|
||
const type = fileType(v);
|
||
const media = v.state === "missing" ? "" : VIDEO_TYPES.has(type) ? `<video controls autoplay preload="metadata" src="${attr(fileUrl(v))}"></video>`
|
||
: IMAGE_TYPES.has(type) ? `<img alt="${attr(v.fileName ?? "")}" src="${attr(fileUrl(v))}">` : "";
|
||
const fact = (key, value, ltr = false) => value ? `<div><dt data-i18n="${key}"></dt><dd ${ltr ? 'dir="ltr" class="mono"' : 'dir="auto"'}>${escapeHtml(value)}</dd></div>` : "";
|
||
dialog.innerHTML = `
|
||
<div class="viewer-head"><h2 id="player-title" class="ellipsis" dir="auto">${escapeHtml(v.sequenceTitle)}</h2>
|
||
<span class="muted ellipsis" dir="ltr">${escapeHtml(v.fileName ?? "")}</span><span class="spacer"></span>
|
||
${downloadBlock(v)
|
||
? `<button class="btn icon" type="button" disabled data-i18n-title="${downloadBlock(v)}">${icons.download}</button>`
|
||
: `<a class="btn icon" href="${attr(fileUrl(v))}" download="${attr(v.fileName ?? "")}" data-i18n-title="Admin.Videos.Download.Tip">${icons.download}</a>`}
|
||
<button class="btn icon" type="button" data-close data-i18n-title="Admin.Videos.Player.Close.Tip">${icons.close}</button></div>
|
||
<div class="viewer-stage" dir="ltr">${media}<p class="player-note" ${media ? "hidden" : ""}>${escapeHtml(v.state === "missing"
|
||
? t("Admin.Videos.State.Missing.Tip") : t("Admin.Videos.Player.NoPlay"))}</p></div>
|
||
<dl class="viewer-meta">${[
|
||
fact("Admin.Videos.Column.Preset", presetText(v)),
|
||
fact("Admin.Videos.Column.Kind", kindText(videoKind(v))),
|
||
fact("Admin.Videos.Column.Format", formatText(v), true),
|
||
fact("Admin.Videos.Column.Duration", videoKind(v) === "still" ? "" : clock(v.durationSeconds), true),
|
||
fact("Admin.Videos.Column.Size", formatBytes(v.bytes)),
|
||
fact("Admin.Videos.Column.Date", formatDateTime(v.created)),
|
||
fact("Admin.Videos.Column.Hash", v.sha256 ?? "", true),
|
||
fact("Admin.Videos.State.Copied", (v.copies ?? []).map((c) => c.path).join("\n"), true),
|
||
].join("")}</dl>`;
|
||
applyStrings(dialog);
|
||
document.body.appendChild(dialog);
|
||
const shown = dialog.querySelector("video, img");
|
||
// A file the browser cannot decode (HEVC without its decoder, a TIFF still) says so, and the download stays.
|
||
shown?.addEventListener("error", () => {
|
||
shown.remove();
|
||
dialog.querySelector(".player-note").hidden = false;
|
||
});
|
||
dialog.querySelector("[data-close]").addEventListener("click", () => dialog.close());
|
||
dialog.addEventListener("close", () => {
|
||
const video = dialog.querySelector("video");
|
||
if (video) {
|
||
// Stops the playback and its range requests at once.
|
||
video.pause();
|
||
video.removeAttribute("src");
|
||
video.load();
|
||
}
|
||
dialog.remove();
|
||
const item = itemsHost.querySelector(`[data-key="${CSS.escape(v.id)}"]`);
|
||
(item ?? opener)?.focus?.();
|
||
});
|
||
dialog.showModal();
|
||
}
|
||
|
||
// A copy that ended adds its copies, a render job adds videos, a deletion or a restore elsewhere takes them away.
|
||
onEvent((e) => {
|
||
if (e.type === "jobState" && JOB_ENDED.has(e.state)) refreshSoon(1500);
|
||
else if (e.type === "sequenceChanged") refreshSoon(800);
|
||
else if (e.type === "reconnected") refreshSoon(0);
|
||
});
|
||
drawFilters();
|
||
await load();
|
||
}
|
||
|
||
/** The library kind of a render, as RenderKind.Of: its kind when recorded, else sequence for an image-sequence codec, else video. */
|
||
export function videoKind(v) {
|
||
if (v.kind) return v.kind;
|
||
return String(v.codec ?? "").toLowerCase().endsWith("sequence") ? "sequence" : "video";
|
||
}
|
||
|
||
/** Why a video has no download: an image sequence is a folder, not one file, and a missing file is gone; null when it has. */
|
||
export function downloadBlock(v) {
|
||
if (!v) return null;
|
||
if (videoKind(v) === "sequence") return "Admin.Videos.Download.Folder.Tip";
|
||
if (v.state === "missing") return "Admin.Videos.Download.Missing.Tip";
|
||
return null;
|
||
}
|
||
|
||
/** A kind in words; a newer server's kind as it is. */
|
||
export function kindText(kind) {
|
||
if (kind === "still") return t("Admin.Videos.Kind.Still.Label");
|
||
if (kind === "sequence") return t("Admin.Videos.Kind.Sequence.Label");
|
||
if (kind === "video") return t("Admin.Videos.Kind.Video.Label");
|
||
return kind;
|
||
}
|
||
|
||
/** "H.264", "HEVC", "PNG" for pngsequence, as users know them. */
|
||
export function codecLabel(codec) {
|
||
const c = String(codec ?? "").toLowerCase();
|
||
if (!c) return "";
|
||
if (CODECS[c]) return CODECS[c];
|
||
return (c.endsWith("sequence") ? c.slice(0, -"sequence".length) : c).toUpperCase();
|
||
}
|
||
|
||
/** The first twelve hex digits of a hash (the whole one in the tooltip); a dash when it is not hashed yet. */
|
||
export function shortHash(sha256) {
|
||
return sha256 ? sha256.slice(0, 12) : "—";
|
||
}
|
||
|
||
function formatText(v) {
|
||
const parts = [`${v.width} × ${v.height}`];
|
||
if (v.codec) parts.push(codecLabel(v.codec));
|
||
if (videoKind(v) !== "still" && v.fps > 0) parts.push(`${formatNumber(Math.round(v.fps * 100) / 100)} fps`);
|
||
return parts.join(" · ");
|
||
}
|
||
|
||
function presetText(v) {
|
||
return v.projectName ? `${v.presetName} · ${v.projectName}${v.projectVersionNumber ? ` v${v.projectVersionNumber}` : ""}` : v.presetName;
|
||
}
|
||
|
||
function stateChips(v) {
|
||
const chips = [];
|
||
if (v.state === "missing") chips.push(`<span class="st warn" title="${attr(t("Admin.Videos.State.Missing.Tip"))}"><span aria-hidden="true">▲</span> ${escapeHtml(t("Admin.Videos.State.Missing"))}</span>`);
|
||
const copies = v.copies ?? [];
|
||
if (copies.length > 0) {
|
||
chips.push(`<span class="st ok" title="${attr(t("Admin.Videos.State.Copied.Tip", copies.map((c) => c.path).join(", ")))}"><span aria-hidden="true">✓</span> ${escapeHtml(t("Admin.Videos.State.Copied"))}</span>`);
|
||
}
|
||
return chips.join("");
|
||
}
|
||
|
||
function blockedText(reason) {
|
||
if (reason === "busy") return t("Admin.Videos.Blocked.Busy");
|
||
if (reason === "not_found") return t("Admin.Videos.Blocked.NotFound");
|
||
return reason;
|
||
}
|
||
|
||
function fileUrl(v) {
|
||
return `/api/v1/renders/${encodeURIComponent(v.id)}/file`;
|
||
}
|
||
|
||
/** A still the browser shows is its own poster; anything else shows its sequence's cover. */
|
||
function posterUrl(v) {
|
||
if (videoKind(v) === "still" && v.state !== "missing" && IMAGE_TYPES.has(fileType(v))) return fileUrl(v);
|
||
return `/api/v1/sequences/${encodeURIComponent(v.sequenceId)}/thumb`;
|
||
}
|
||
|
||
function fileType(v) {
|
||
const name = String(v.fileName ?? "");
|
||
const dot = name.lastIndexOf(".");
|
||
return dot < 0 ? "" : name.slice(dot + 1).toLowerCase();
|
||
}
|
||
|
||
/** A video length as 1:05 or 1:02:05. */
|
||
function clock(seconds) {
|
||
const s = Math.max(0, Math.round(seconds ?? 0));
|
||
const hh = Math.floor(s / 3600);
|
||
const mm = Math.floor((s % 3600) / 60);
|
||
const ss = String(s % 60).padStart(2, "0");
|
||
return hh > 0 ? `${hh}:${String(mm).padStart(2, "0")}:${ss}` : `${mm}:${ss}`;
|
||
}
|
||
|
||
function storedView() {
|
||
try {
|
||
return localStorage.getItem(VIEW_KEY) === "list" ? "list" : "cards";
|
||
} catch {
|
||
return "cards";
|
||
}
|
||
}
|
||
|
||
function cap(s) {
|
||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||
}
|