merge: phase 5 parcel P4
This commit is contained in:
commit
a0335ec18a
7 files changed
+835
-18
No files matched your search
@@ -386,7 +386,7 @@ textarea.input.notes { height: auto; min-height: 64px; padding: 6px 10px; resize
|
||||
.frame-badge { position: absolute; top: 4px; inset-inline-end: 4px; display: grid; place-items: center; width: 22px; height: 22px; border-radius: 11px; background: var(--on-photo); color: #fff; }
|
||||
.frame-badge.hero { color: var(--sun); }
|
||||
.frame-badge.warn { top: auto; bottom: 4px; inset-inline: 4px auto; color: var(--warning); }
|
||||
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content; }
|
||||
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content max-content max-content; }
|
||||
/* A sequence's projects (owner review 2, R8) and, under one opened, its versions. Their table sits in a wrapper, a grid item
|
||||
of the panel: it may be narrower than the table, so the table's columns fit (fitColumns) instead of the panel scrolling. */
|
||||
.panel > .table-host { min-width: 0; }
|
||||
@@ -417,6 +417,24 @@ dialog.viewer .buttons { grid-column: 1 / -1; }
|
||||
.seq-card[aria-selected="true"], .frame[aria-selected="true"], .seq-row[aria-selected="true"] { outline: 3px solid Highlight; }
|
||||
}
|
||||
|
||||
/* Videos (owner review 1, R9; pages/videos.js): the Library's cards and rows with their own columns (title and preset,
|
||||
kind, format, duration, size, date, hash, state), a missing file dimmed, and the player: the photo viewer's layout with
|
||||
a <video> or an image on its stage, or a sentence when the browser cannot play the file. */
|
||||
.seq-items.rows.video-items { grid-template-columns: max-content 64px minmax(160px, 2fr) max-content max-content max-content max-content max-content minmax(0, max-content) minmax(60px, max-content); }
|
||||
.video-items .missing .thumb { opacity: .45; }
|
||||
.video-items .seq-card .info .num { font-size: 12px; color: var(--text-muted); }
|
||||
.viewer-stage video { display: block; max-width: 100%; max-height: 72vh; }
|
||||
.viewer-stage .player-note { margin: 0; padding: 24px; color: #fff; text-align: center; }
|
||||
dialog.player .viewer-head .ellipsis { flex: 0 1 auto; }
|
||||
@media (max-width: 1200px) {
|
||||
.seq-items.rows.video-items { grid-template-columns: max-content 64px minmax(140px, 2fr) max-content max-content max-content max-content minmax(60px, max-content); }
|
||||
.video-items .col-hash, .video-items .col-date { display: none; }
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.seq-items.rows.video-items { grid-template-columns: max-content 64px minmax(120px, 1fr) max-content minmax(60px, max-content); }
|
||||
.video-items .col-kind, .video-items .col-format, .video-items .col-duration { display: none; }
|
||||
}
|
||||
|
||||
/* Upload dialog (owner review 2, R3, upload.js): the target, a drop zone, the photos with their state, the total. */
|
||||
dialog.dialog.upload { width: 640px; }
|
||||
.upload-choice { border: 0; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 20px; }
|
||||
|
||||
@@ -6,8 +6,9 @@ import { escapeHtml, attr, errorText, nativeName, formatNumber, fitColumns } fro
|
||||
|
||||
const app = document.getElementById("app");
|
||||
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2). The Library
|
||||
// manages sequences and photos without editing them (owner review 2, R6).
|
||||
const topPages = ["dashboard", "library", "users", "archive", "jobs", "logs"];
|
||||
// manages sequences and photos without editing them (owner review 2, R6); Videos lists every render after it (owner
|
||||
// review 1, R9).
|
||||
const topPages = ["dashboard", "library", "videos", "users", "archive", "jobs", "logs"];
|
||||
const bottomPages = ["settings"];
|
||||
const pages = [...topPages, ...bottomPages];
|
||||
/** Routes of old bookmarks and where they open now: About is the last group of Settings (owner review 2). */
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
// A sequence on the panel (owner review 2, R6): its title, tags, rating and notes, its facts, its photos in pages of 500
|
||||
// with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, its projects (R8: listed,
|
||||
// renamed and deleted, projects.js), the originals and the renders to download. Nothing here edits the video: its settings,
|
||||
// its projects' versions and its renders are the desktop editor's.
|
||||
// renamed and deleted, projects.js), the originals and the renders to download, with their kind and hash and a link to
|
||||
// this sequence's videos on the Videos page (owner review 1, R9). Nothing here edits the video: its settings, its projects'
|
||||
// versions and its renders are the desktop editor's.
|
||||
import { t, plural, applyStrings } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, escapeReverts, redraw } from "../../ui.js";
|
||||
import { icons } from "../../icons.js";
|
||||
import { captureText, cameraLabel, spanText, statusChips, lazyImage, watchImages, retryImages, Selection, selectableGrid, tagList, coverUrl, listed, JOB_ENDED } from "./shared.js";
|
||||
import { projectsSection } from "./projects.js";
|
||||
import { videoKind, kindText, shortHash } from "../videos.js";
|
||||
|
||||
const FRAME_PAGE = 500;
|
||||
/** Deleting more photos than this asks for their number to be typed. */
|
||||
@@ -87,7 +89,8 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
|
||||
<div id="projects" class="table-host"></div>
|
||||
</section>
|
||||
<section class="panel flush" aria-labelledby="renders-title">
|
||||
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2></div>
|
||||
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2>
|
||||
<a class="btn small" href="#/videos?sequence=${attr(encodeURIComponent(id))}" data-i18n="Admin.Videos.AllVideos" data-i18n-title="Admin.Videos.AllVideos.Tip"></a></div>
|
||||
<div id="renders"></div>
|
||||
</section>`;
|
||||
applyStrings(root);
|
||||
@@ -435,15 +438,19 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
|
||||
host.innerHTML = renders.length === 0 ? emptyState("Admin.Sequence.NoRenders") : `
|
||||
<div class="table renders" role="table" aria-labelledby="renders-title">
|
||||
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Sequence.Render.Preset"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Sequence.Render.Video"></span><span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Length"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Size"></span><span role="columnheader" data-i18n="Admin.Sequence.Render.Created"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Sequence.Render.Video"></span><span role="columnheader" data-i18n="Admin.Videos.Column.Kind"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Length"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Size"></span><span role="columnheader" data-i18n="Admin.Videos.Column.Hash"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Sequence.Render.Created"></span>
|
||||
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
|
||||
<div role="rowgroup">${renders.map((r) => `
|
||||
<div class="row" role="row" data-key="${attr(r.id)}">
|
||||
<span class="ellipsis" role="cell" dir="auto" title="${attr(r.producedBy ?? "")}">${escapeHtml(r.presetName)}</span>
|
||||
<span class="num nowrap" role="cell" dir="ltr">${escapeHtml(`${r.width} × ${r.height} · ${formatNumber(r.fps)} fps${r.codec ? ` · ${r.codec.toUpperCase()}` : ""}`)}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(clock(r.durationSeconds))}</span>
|
||||
<span class="nowrap" role="cell">${escapeHtml(kindText(videoKind(r)))}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(videoKind(r) === "still" ? "—" : clock(r.durationSeconds))}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(r.bytes))}</span>
|
||||
<span class="mono muted nowrap" role="cell" dir="ltr" title="${attr(r.sha256 ?? "")}">${escapeHtml(shortHash(r.sha256))}</span>
|
||||
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(r.created))}</span>
|
||||
<span class="row-actions" role="cell"><a class="btn small" href="/api/v1/renders/${encodeURIComponent(r.id)}/file" download
|
||||
data-i18n-title="Admin.Sequence.Render.Download.Tip">${icons.download}<span data-i18n="Admin.Sequence.Render.Download"></span></a></span>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// The archive's trash on the panel (owner review 2, R6; #/library?view=trash, reached from the Library and the Archive):
|
||||
// deleted sequences and photos deleted from sequences, each restorable; emptying it is the panel's only erase of user
|
||||
// files, so it measures the trash first (dry run), names what goes, asks for the word "empty" to be typed and sends the
|
||||
// plan's fingerprint, which the server's job checks again before it erases anything.
|
||||
// deleted sequences, photos deleted from sequences and videos deleted from the Videos page (owner review 1, R9), each
|
||||
// restorable; emptying it is the panel's only erase of user files, so it measures the trash first (dry run), names what
|
||||
// goes, asks for the word "empty" to be typed and sends the plan's fingerprint, which the server's job checks again before
|
||||
// it erases anything.
|
||||
import { t, plural, applyStrings } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns } from "../../ui.js";
|
||||
import { icons } from "../../icons.js";
|
||||
@@ -73,7 +74,7 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
<span class="nowrap" role="cell">${escapeHtml(kindLabel(e.kind))}</span>
|
||||
<span class="stack" role="cell"><strong class="ellipsis" dir="auto" title="${attr(e.title)}">${escapeHtml(e.title)}</strong>
|
||||
<small dir="ltr" class="mono" title="${attr(e.folder)}">${escapeHtml(e.folder)}</small></span>
|
||||
<span class="num end" role="cell">${formatNumber(e.photos)}</span>
|
||||
<span class="num end" role="cell">${e.kind === "videos" ? "—" : formatNumber(e.photos)}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(e.bytes))}</span>
|
||||
<span class="col-by ellipsis" role="cell" dir="auto">${escapeHtml(e.deletedBy ?? "—")}</span>
|
||||
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(e.deletedAt))}</span>
|
||||
@@ -105,7 +106,9 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
return;
|
||||
}
|
||||
// A replaced entry (owner review 2, R7) swaps back: its originals take their conversions' place, which go to the trash.
|
||||
const lines = [result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
|
||||
// A video goes back into its sequence's folder after its hash matched its record (the server refuses it otherwise).
|
||||
const lines = [result.kind === "videos" ? t("Admin.Trash.RestoredVideo", videoFile(entry), entry.title)
|
||||
: result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
|
||||
: result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos)
|
||||
: result.kind === "replaced" ? plural("Admin.Trash.RestoredOriginals", result.photos, entry.title)
|
||||
: plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)];
|
||||
@@ -218,11 +221,21 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
await load();
|
||||
}
|
||||
|
||||
/** What Restore does to an entry of this kind: a sequence's folder back, photos back, or originals back in place of their conversions. */
|
||||
/**
|
||||
* What Restore does to an entry of this kind: a sequence's folder back, photos back, originals back in place of their
|
||||
* conversions, or a video back into its sequence.
|
||||
*/
|
||||
function restoreTip(kind) {
|
||||
return kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : kind === "replaced" ? "Admin.Trash.RestoreReplaced.Tip" : "Admin.Trash.RestorePhotos.Tip";
|
||||
return kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : kind === "replaced" ? "Admin.Trash.RestoreReplaced.Tip"
|
||||
: kind === "videos" ? "Admin.Trash.RestoreVideos.Tip" : "Admin.Trash.RestorePhotos.Tip";
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced" : "Admin.Trash.Kind.Photos");
|
||||
return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced"
|
||||
: kind === "videos" ? "Admin.Trash.Kind.Videos" : "Admin.Trash.Kind.Photos");
|
||||
}
|
||||
|
||||
/** A video entry's file name: the last part of the path it was deleted from (its folder). */
|
||||
function videoFile(entry) {
|
||||
return String(entry.folder ?? "").split(/[\\/]/).filter(Boolean).pop() ?? entry.title;
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
// in a container the listening ports are the container's, read-only. Client address is what to type in the Uploader and
|
||||
// in Chronos: this host as the browser reached it, on the HTTPS port this page came through (else the public HTTPS port;
|
||||
// the proxy's address in TLS mode proxy). When that port is not the saved one, a button fills it in; saving a public HTTPS
|
||||
// port other than the page's asks first, as the HTTPS redirect follows it at once.
|
||||
// port other than the page's asks first, as the HTTPS redirect follows it at once. Videos folder (owner review 1, R9) is
|
||||
// where the Videos page's Copy to folder puts renders: read-only when CHRONOS_VIDEOS_PATH fixes it, empty turns copying off.
|
||||
import { t, applyStrings, languages } from "../i18n.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, confirmDialog, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel } from "../jobs.js";
|
||||
@@ -82,6 +83,7 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
${field("language", `<select class="input" name="language" ${lock("language")}>${languages().concat(languages().includes(settings.language) ? [] : [settings.language])
|
||||
.map((code) => `<option value="${attr(code)}" ${code === settings.language ? "selected" : ""}>${escapeHtml(nativeName(code))}</option>`).join("")}</select>`)}
|
||||
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
|
||||
${text("videosPath", settings.videosPath, 'dir="ltr" spellcheck="false" autocomplete="off"')}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="jobs-title">
|
||||
<h2 id="jobs-title" data-i18n="Admin.Settings.Jobs"></h2>
|
||||
@@ -214,6 +216,17 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The videos folder to send (owner review 1, R9): null keeps it (locked by CHRONOS_VIDEOS_PATH, or not changed), an empty
|
||||
* text clears it and turns copying off, else the folder, which the server checks (not inside the archive).
|
||||
*/
|
||||
function videosPath() {
|
||||
const input = root.querySelector('[name="videosPath"]');
|
||||
if (!input || input.disabled) return null;
|
||||
const next = input.value.trim();
|
||||
return next === (settings.videosPath ?? "") ? null : next;
|
||||
}
|
||||
|
||||
async function save(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
@@ -259,6 +272,7 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
tlsMode: String(value("tlsMode", settings.tlsMode)),
|
||||
tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null,
|
||||
tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null,
|
||||
videosPath: videosPath(),
|
||||
maxUploadBytes: Math.round(Number(data.get("maxUploadMb")) * MB),
|
||||
chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB),
|
||||
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
|
||||
|
||||
@@ -0,0 +1,603 @@
|
||||
// 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();
|
||||
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.Library.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.
|
||||
const title = filters.sequence ? rows.find((v) => v.sequenceId === filters.sequence)?.sequenceTitle : null;
|
||||
root.querySelector("#sequence-filter").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>` : "";
|
||||
setMeta(title ?? "");
|
||||
}
|
||||
|
||||
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 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>
|
||||
${one ? `<button class="btn small" id="mass-play" data-mass="play" data-i18n-title="Admin.Videos.Play.Tip">${icons.play}<span data-i18n="Admin.Videos.Play"></span></button>` : ""}
|
||||
<button class="btn small" id="mass-download" data-mass="download" data-i18n-title="${one ? "Admin.Videos.Download.Tip" : "Admin.Videos.Download.One.Tip"}"
|
||||
${one ? "" : "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) 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.Library.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>
|
||||
<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";
|
||||
}
|
||||
|
||||
/** 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");
|
||||
if (kind === "video") return t("Admin.Sequence.Render.Video");
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The Videos page of the admin panel (owner review 1, R9, decision 22; <c>Admin/web/pages/videos.js</c>): in the menu after
|
||||
/// the Library, what it imports and calls (the videos API, never an edit or a render: owner review 2, R6), the delete's dry
|
||||
/// run before the move with the plan's fingerprint, Copy's reasons when it is off, the player, and its strings; and what the
|
||||
/// Trash, a sequence and Settings show of the videos library.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed partial class AdminVideosTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheVideosPageIsInTheMenuAfterTheLibraryAndLoads()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var app = await server.Client.GetStringAsync("/admin/app.js");
|
||||
var top = Regex.Match(app, @"const topPages = \[([^\]]*)\]").Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"')).ToList();
|
||||
Assert.Equal(top.IndexOf("library") + 1, top.IndexOf("videos"));
|
||||
Assert.Contains(" videos: `<svg", await server.Client.GetStringAsync("/admin/icons.js"));
|
||||
|
||||
using var response = await server.Client.GetAsync("/admin/pages/videos.js");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType);
|
||||
var page = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("export async function render(root, { api, setMeta, actions, onEvent })", page);
|
||||
var imports = StaticImport().Matches(page).Select(m => m.Groups[1].Value).ToList();
|
||||
Assert.SequenceEqual(["../i18n.js", "../ui.js", "../icons.js", "./library/shared.js"], imports);
|
||||
// The panel runs under a strict CSP: no inline handlers or styles.
|
||||
Assert.True(!Regex.IsMatch(page, @"\son[a-z]+="""), "inline handler");
|
||||
Assert.True(!page.Contains(" style=", StringComparison.Ordinal), "inline style");
|
||||
// A sequence's renders name their kind and hash as the Videos page does.
|
||||
foreach (var helper in new[] { "videoKind(v)", "kindText(kind)", "codecLabel(codec)", "shortHash(sha256)" })
|
||||
Assert.Contains($"export function {helper}", page);
|
||||
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
|
||||
Assert.Contains(@"import { videoKind, kindText, shortHash } from ""../videos.js"";", sequence);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheVideosPageManagesAndNeverEdits()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
|
||||
var calls = ApiCall().Matches(page).Select(m => (Method: m.Groups[1].Value, Target: m.Groups[2].Value)).ToList();
|
||||
Assert.True(calls.Count >= 4, string.Join(", ", calls));
|
||||
// Reads the list and the server's videos folder; writes only the videos' delete and copy: no settings, no project,
|
||||
// no render, no job of its own.
|
||||
foreach (var (method, target) in calls)
|
||||
{
|
||||
Assert.True(method is "get" or "post", $"api.{method}({target}");
|
||||
if (method == "get") Assert.True(target is "listQuery(" or @"""/api/v1/server/settings""", target);
|
||||
else Assert.True(target is @"""/api/v1/videos/copy""" or @"""/api/v1/videos/delete""", target);
|
||||
}
|
||||
Assert.Contains("return `/api/v1/videos?${p}`;", page);
|
||||
foreach (var never in new[] { "settingsJson", "/projects", "/jobs\"", "api.put(", "api.patch(", "api.del(" })
|
||||
Assert.False(page.Contains(never, StringComparison.Ordinal), never);
|
||||
// A render's file is read (play, download); nothing asks for a render.
|
||||
Assert.False(Regex.IsMatch(page, "/render(?!s/)"), "a render request");
|
||||
|
||||
// Delete: the dry run, the confirmation (copies stay), then the delete with the plan's fingerprint; a changed plan reloads.
|
||||
var dryRun = page.IndexOf(@"api.post(""/api/v1/videos/delete"", { ids, dryRun: true, fingerprint: null })", StringComparison.Ordinal);
|
||||
var confirm = page.IndexOf("const confirmed = await confirmDialog({", Math.Max(0, dryRun), StringComparison.Ordinal);
|
||||
var delete = page.IndexOf(@"api.post(""/api/v1/videos/delete"", { ids, dryRun: false, fingerprint: plan.fingerprint })", StringComparison.Ordinal);
|
||||
Assert.True(dryRun > 0 && confirm > dryRun && delete > confirm, "dry run, confirmation, delete");
|
||||
Assert.Contains(@"t(""Admin.Videos.Delete.CopiesStay"")", page);
|
||||
Assert.Contains("list: listed([...blocked, ...going]),", page);
|
||||
Assert.Contains(@"if (err.code === ""plan_changed"") await load();", page);
|
||||
// Copy is off, saying why, without the right or without a videos folder; a folder unset since says so from then on.
|
||||
Assert.Contains(@"const copyWhy = !may(EDIT) ? ""Admin.Videos.Copy.NoRight.Tip"" : folder === """" ? ""Admin.Videos.Copy.NoFolder.Tip"" : null;", page);
|
||||
Assert.Contains(@"const deleteWhy = may(DELETE) ? null : ""Admin.Videos.Delete.NoRight.Tip"";", page);
|
||||
Assert.Contains(@"if (err.code === ""videos_folder_unset"") folder = """";", page);
|
||||
Assert.Contains("const EDIT = 4;", page);
|
||||
Assert.Contains("const DELETE = 8;", page);
|
||||
Assert.Equal(4L, (long)Chronos.Core.Model.Permissions.Edit);
|
||||
Assert.Equal(8L, (long)Chronos.Core.Model.Permissions.Delete);
|
||||
// The player: a <video> for the formats a browser plays, an image for stills, GIF and APNG, the file by its render.
|
||||
Assert.Contains(@"<video controls autoplay preload=""metadata"" src=""${attr(fileUrl(v))}""></video>", page);
|
||||
Assert.Contains("return `/api/v1/renders/${encodeURIComponent(v.id)}/file`;", page);
|
||||
Assert.Contains(@"shown?.addEventListener(""error"", () => {", page);
|
||||
// The list follows the jobs that end (a copy, a render), the sequences that change and a reconnection.
|
||||
Assert.Contains(@"if (e.type === ""jobState"" && JOB_ENDED.has(e.state)) refreshSoon(1500);", page);
|
||||
Assert.Contains(@"else if (e.type === ""reconnected"") refreshSoon(0);", page);
|
||||
// The wire values the page sends are the API's.
|
||||
Assert.Contains($"const SORTS = [{string.Join(", ", VideoSorts.All.Select(s => $@"""{s}"""))}];", page);
|
||||
Assert.Contains(@"if (reason === ""busy"")", page);
|
||||
Assert.Equal("busy", VideoBlockReasons.Busy);
|
||||
Assert.Contains(@"if (reason === ""not_found"")", page);
|
||||
Assert.Equal("not_found", VideoBlockReasons.NotFound);
|
||||
Assert.Contains(@"v.state === ""missing""", page);
|
||||
Assert.Equal("missing", VideoStates.Missing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheVideosStringsAreInEnglishAndItalian()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
|
||||
var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js");
|
||||
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
|
||||
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
|
||||
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
|
||||
var keys = Regex.Matches(page, @"""(Admin\.[A-Za-z]+(?:\.[A-Za-z]+)*)""").Select(m => m.Groups[1].Value).Distinct().ToList();
|
||||
Assert.Greater(keys.Count, 50);
|
||||
// The keys the pages build from a value.
|
||||
keys.AddRange(VideoSorts.All.Select(s => $"Admin.Videos.Sort.{char.ToUpperInvariant(s[0])}{s[1..]}"));
|
||||
keys.AddRange(["Admin.Videos.Kind.Video", "Admin.Videos.Kind.Still", "Admin.Videos.Kind.Sequence", "Admin.Trash.Kind.Videos", "Admin.Nav.Videos", "Admin.Nav.Videos.Tip",
|
||||
"Admin.Settings.VideosPath", "Admin.Settings.VideosPath.Tip", "Admin.Job.Kind.VideoCopy"]);
|
||||
keys.AddRange(Regex.Matches(trash + sequence, @"""(Admin\.(?:Trash\.[A-Za-z]*Video[A-Za-z]*|Videos\.[A-Za-z.]+)(?:\.[A-Za-z]+)*)""").Select(m => m.Groups[1].Value));
|
||||
Assert.Contains("Admin.Trash.RestoredVideo", keys);
|
||||
Assert.Contains("Admin.Videos.AllVideos.Tip", keys);
|
||||
foreach (var key in keys.Distinct())
|
||||
{
|
||||
var name = en.ContainsKey(key) ? key : key + ".other";
|
||||
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
|
||||
}
|
||||
Assert.Equal("Video", it["Admin.Nav.Videos"]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheTrashASequenceAndSettingsKnowTheVideosLibrary()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
// The trash lists a deleted video as "videos" (TrashKind.Videos), restores it after its hash check and says where it went.
|
||||
var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js");
|
||||
Assert.Contains(@"kind === ""videos"" ? ""Admin.Trash.Kind.Videos""", trash);
|
||||
Assert.Contains(@"kind === ""videos"" ? ""Admin.Trash.RestoreVideos.Tip""", trash);
|
||||
Assert.Contains(@"result.kind === ""videos"" ? t(""Admin.Trash.RestoredVideo"", videoFile(entry), entry.title)", trash);
|
||||
Assert.Contains(@"e.kind === ""videos"" ? ""—"" : formatNumber(e.photos)", trash);
|
||||
Assert.True(Chronos.Data.Videos.VideoTrashNames.IsEntryName(Chronos.Data.Videos.VideoTrashNames.EntryName(Guid.NewGuid(), DateTimeOffset.UtcNow)));
|
||||
|
||||
// A sequence's renders: kind and hash, and every video of the sequence on the Videos page.
|
||||
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
|
||||
Assert.Contains(@"href=""#/videos?sequence=${attr(encodeURIComponent(id))}"" data-i18n=""Admin.Videos.AllVideos""", sequence);
|
||||
Assert.Contains(@"data-i18n=""Admin.Videos.Column.Kind""", sequence);
|
||||
Assert.Contains(@"data-i18n=""Admin.Videos.Column.Hash""", sequence);
|
||||
Assert.Contains(@"title=""${attr(r.sha256 ?? """")}"">${escapeHtml(shortHash(r.sha256))}", sequence);
|
||||
// The Videos page reads its sequence filter from the address the link writes.
|
||||
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
|
||||
Assert.Contains(@"const FILTERS = [""q"", ""kind"", ""codec"", ""year"", ""sequence"", ""sort""];", page);
|
||||
Assert.Contains("history.replaceState(null, \"\", `#/videos${query.size ? `?${query}` : \"\"}`);", page);
|
||||
|
||||
// Settings: the videos folder, read-only when an environment variable fixes it (lock), sent only when changed.
|
||||
var settings = await server.Client.GetStringAsync("/admin/pages/settings.js");
|
||||
Assert.Contains(@"${text(""videosPath"", settings.videosPath, 'dir=""ltr"" spellcheck=""false"" autocomplete=""off""')}", settings);
|
||||
Assert.Contains("videosPath: videosPath(),", settings);
|
||||
Assert.Contains("if (!input || input.disabled) return null;", settings);
|
||||
Assert.Contains(@"return next === (settings.videosPath ?? """") ? null : next;", settings);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
|
||||
private static partial Regex StaticImport();
|
||||
|
||||
/// <summary>A call of the panel's api object: its method and the start of its first argument.</summary>
|
||||
[GeneratedRegex(@"(?<![\w$.])api\.(\w+)\((""[^""]*""|`[^`]*`|\w+\()")]
|
||||
private static partial Regex ApiCall();
|
||||
}
|
||||
Reference in new issue
Block a user