feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
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
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>
This commit was merged in pull request #27.
This commit is contained in:
1 parent
188b2c2e55
commit
728ffa35cb
729 files changed
+26954
-1652
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). */
|
||||
|
||||
@@ -29,4 +29,10 @@ export const icons = {
|
||||
hero: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 4.8 L8.9 6.9 L11.1 7.1 L9.4 8.5 L9.9 10.7 L8 9.5 L6.1 10.7 L6.6 8.5 L4.9 7.1 L7.1 6.9 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
image: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
warning: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L14.8 13.8 H1.2 Z M8 6.2 V9.6 M8 11.7 V11.8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
videos: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.5 6.5 L9.5 9 L5.5 11.5 Z" fill="currentColor"/><path d="M3.0 4 H11.0 A1.5 1.5 0 0 1 12.5 5.5 V12.5 A1.5 1.5 0 0 1 11.0 14 H3.0 A1.5 1.5 0 0 1 1.5 12.5 V5.5 A1.5 1.5 0 0 1 3.0 4 Z M4.5 1.5 H13 A1.5 1.5 0 0 1 14.5 3 V11.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
play: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M4.5 2.8 L13 8 L4.5 13.2 Z" fill="currentColor"/></svg>`,
|
||||
copyToFolder: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M1.5 4 A1 1 0 0 1 2.5 3 H6 L7.5 4.5 H13.5 A1 1 0 0 1 14.5 5.5 V12.5 A1 1 0 0 1 13.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z M8 6.5 V11 M6 9 L8 11 L10 9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
stillFrame: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6.5 5.5 H9.5 A0.5 0.5 0 0 1 10 6.0 V10.0 A0.5 0.5 0 0 1 9.5 10.5 H6.5 A0.5 0.5 0 0 1 6 10.0 V6.0 A0.5 0.5 0 0 1 6.5 5.5 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M4.5 2.5 V13.5 M11.5 2.5 V13.5 M1.5 6 H4.5 M1.5 10 H4.5 M11.5 6 H14.5 M11.5 10 H14.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
fade: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 12 L13 4 V12 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
boomerang: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 5 H11 A3 3 0 0 1 11 11 H3 M5 8.8 L2.8 11 L5 13.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
};
|
||||
@@ -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,638 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -24,7 +24,7 @@ public static class Dto
|
||||
f.FocalLength, f.Orientation, f.Width, f.Height, f.Format.ToString().ToLowerInvariant(), (long)f.Flags, f.PreviewWidth, f.PreviewHeight);
|
||||
|
||||
public static RenderDto Render(Render r) => new(r.Id, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy,
|
||||
r.ProjectId, r.ProjectVersionId);
|
||||
r.ProjectId, r.ProjectVersionId, r.Sha256, r.Kind);
|
||||
|
||||
public static JobDto Job(Job j) => new(
|
||||
j.Id, JobWire.Kind(j.Kind), j.TargetIds, j.TargetLabel, JobWire.State(j.State), JobWire.Priority(j.Priority), j.ProgressDone,
|
||||
|
||||
@@ -107,7 +107,7 @@ public sealed class ServerState
|
||||
public string Database { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>What this server offers clients (<see cref="ServerInfo.Capabilities"/>; <see cref="ServerCapabilities"/> names those clients act on).</summary>
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects];
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects, ServerCapabilities.Videos];
|
||||
|
||||
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
@@ -15,7 +16,7 @@ namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/archive/trash</c> (owner review 2, R6; administrators of the archive): the entries of the archive's trash —
|
||||
/// deleted sequences and photos deleted from sequences —, restoring one, and emptying it: a dry run that measures the
|
||||
/// deleted sequences, photos deleted from sequences and deleted videos (owner review 1, R9) —, restoring one, and emptying it: a dry run that measures the
|
||||
/// entries and fingerprints them, then an <c>empty-trash</c> job that erases exactly those entries and refuses when the
|
||||
/// trash changed since (BRIEF §0.2 rule 8: the only erase of user files, always an explicit, confirmed action).
|
||||
/// </summary>
|
||||
@@ -29,8 +30,11 @@ public static partial class TrashEndpoints
|
||||
trash.MapPost("/empty", EmptyAsync);
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>): never a path.</summary>
|
||||
public static bool IsEntryName(string? name) => name is not null && EntryName().IsMatch(name);
|
||||
/// <summary>
|
||||
/// Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>, or a videos entry
|
||||
/// <c>videos-<render id>-<ticks></c>, owner review 1, R9): never a path.
|
||||
/// </summary>
|
||||
public static bool IsEntryName(string? name) => name is not null && (EntryName().IsMatch(name) || VideoTrashNames.IsEntryName(name));
|
||||
|
||||
public static TrashEntryDto Entry(TrashEntry e) =>
|
||||
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt, e.ConversionDeleted);
|
||||
@@ -55,9 +59,11 @@ public static partial class TrashEndpoints
|
||||
/// a sequence, <c>frames</c> for photos.
|
||||
/// </summary>
|
||||
private static async Task<IResult> RestoreAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, JobEngineHost host, AuditLog audit, EventHub events,
|
||||
IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (!IsEntryName(name)) return ApiErrors.NotFound(context, "trash_entry");
|
||||
if (VideoTrashNames.IsEntryName(name)) return await RestoreVideoAsync(context, caller, name, db, archive, VideoEndpoints.Library(videos, archives, db), audit, events, lifetime);
|
||||
TrashRestoreResult result;
|
||||
try
|
||||
{
|
||||
@@ -107,6 +113,49 @@ public static partial class TrashEndpoints
|
||||
result.Kept.Count == 0 ? null : string.Join(" ", KeptPhoto.Sentences(result.Kept, culture))), ProtocolJson.Default.TrashRestoreDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings a deleted video back (owner review 1, R9, decision 18): the trashed file re-hashed against its record, moved back
|
||||
/// into its sequence's folder (a free name when its own is taken) and its entry recorded again with the same render id.
|
||||
/// 404 <c>not_found</c> (<c>trash_entry</c>); 409 <c>sequence_gone</c> (restore the sequence first), <c>sequence_busy</c>,
|
||||
/// <c>folder_in_use</c>; 422 <c>trash_hash_mismatch</c> (it stays in the trash); 503 <c>archive_offline</c>. Publishes
|
||||
/// <c>sequenceChanged</c> (<c>renders</c>).
|
||||
/// </summary>
|
||||
private static async Task<IResult> RestoreVideoAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
|
||||
IVideoLibrary library, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (!library.IsAvailable) return ApiErrors.NotFound(context, "trash_entry");
|
||||
Render render;
|
||||
try
|
||||
{
|
||||
render = await library.RestoreAsync(archive.Id, name, lifetime.ApplicationStopping);
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "trash_entry");
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return VideoEndpoints.Refused(context, ex);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return Offline(context);
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_busy");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "trash_restored", "render", render.Id.ToString(), $"{name} · {Path.GetFileName(render.OutputPath.TrimEnd('/', '\\'))}");
|
||||
if (await db.Sequences.GetAsync(render.SequenceId, CancellationToken.None) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "renders", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
return Results.Json(new TrashRestoreDto(name, TrashKind.Videos.ToString().ToLowerInvariant(), render.SequenceId, 1, [], NewSequence: false),
|
||||
ProtocolJson.Default.TrashRestoreDto);
|
||||
}
|
||||
|
||||
/// <summary>The code of why a photo stayed in the trash (<see cref="TrashRestoreDto.KeptReasons"/>).</summary>
|
||||
private static string ReasonCode(KeptReason reason) => reason switch
|
||||
{
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/videos</c> (owner review 1, R9; capability <see cref="ServerCapabilities.Videos"/>): every render of the
|
||||
/// server in one list, read by anyone who may read; deleting renders into the archive's trash (Delete), always a dry run
|
||||
/// first whose fingerprint the delete itself must give back, and restored through <c>/archive/trash/{name}/restore</c>;
|
||||
/// and copying them, hash-verified, into the server's videos folder as one <c>video-copy</c> job (Edit). The files
|
||||
/// themselves are <c>GET /api/v1/renders/{id}/file</c>. Deletes and copies are audited (<c>videos_deleted</c>,
|
||||
/// <c>videos_copied</c>). The panel manages and never edits (owner review 2, R6): nothing here changes a project or starts a render.
|
||||
/// </summary>
|
||||
public static class VideoEndpoints
|
||||
{
|
||||
/// <summary>The most renders one delete or copy names.</summary>
|
||||
public const int MaxIds = VideoQuery.MaxLimit;
|
||||
|
||||
/// <summary>Renders an audit entry names by file, the rest counted.</summary>
|
||||
private const int AuditNames = 5;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var videos = api.MapGroup("/videos").Requires(Permissions.Read);
|
||||
videos.MapGet("", ListAsync);
|
||||
videos.MapGet("/{id:guid}", GetAsync);
|
||||
videos.MapPost("/delete", DeleteAsync).Requires(Permissions.Delete);
|
||||
videos.MapPost("/copy", CopyAsync).Requires(Permissions.Edit);
|
||||
}
|
||||
|
||||
/// <summary>The videos library behind these endpoints: the host's, or that of an archive engine of its own (a test host that replaces the archive module).</summary>
|
||||
internal static IVideoLibrary Library(IVideoLibrary? videos, ArchiveService? archives, ChronosDatabase db) =>
|
||||
videos ?? LibraryEndpoints.Engine(archives, db).Videos;
|
||||
|
||||
public static VideoDto Video(VideoItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var r = item.Render;
|
||||
return new VideoDto(r.Id, r.SequenceId, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy,
|
||||
r.ProjectId, r.ProjectVersionId, r.Sha256, item.Kind, item.SequenceTitle, item.SequenceFirstCapture, item.ProjectName, item.ProjectVersionNumber,
|
||||
item.State, [.. item.Copies.Select(c => new VideoCopyDto(c.Path, c.CopiedAt))], item.FileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One page of videos: <c>q</c> (sequence title, preset or file name), <c>kind</c> (<c>video</c>, <c>still</c>,
|
||||
/// <c>sequence</c>), <c>codec</c>, <c>year</c>, <c>sequence</c>, <c>sort</c> (<see cref="VideoSorts"/>), <c>cursor</c>,
|
||||
/// <c>limit</c> (1–500). 400 <c>invalid_filter</c> (details: the filter).
|
||||
/// </summary>
|
||||
private static async Task<IResult> ListAsync(HttpContext context, string? q, string? kind, string? codec, int? year, Guid? sequence, string? sort,
|
||||
string? cursor, int? limit, ChronosDatabase db, [FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos)
|
||||
{
|
||||
kind = Blank(kind)?.ToLowerInvariant();
|
||||
sort = Blank(sort)?.ToLowerInvariant();
|
||||
if (kind is not null and not (RenderKind.Video or RenderKind.Still or RenderKind.Sequence)) return ApiErrors.BadRequest(context, "invalid_filter", "kind");
|
||||
if (sort is not null && !VideoSorts.All.Contains(sort)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
|
||||
if (year is < 1 or > 9999) return ApiErrors.BadRequest(context, "invalid_filter", "year");
|
||||
var query = VideoQuery.From(new VideoQueryDto(Blank(q), kind, Blank(codec), year, sequence, sort, Blank(cursor), limit));
|
||||
VideoPage page;
|
||||
try
|
||||
{
|
||||
page = await Library(videos, archives, db).ListAsync(query, context.RequestAborted);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or FormatException)
|
||||
{
|
||||
// A cursor of another listing, or one this server never gave.
|
||||
return ApiErrors.BadRequest(context, "invalid_cursor");
|
||||
}
|
||||
return Results.Json(new VideoPageDto([.. page.Items.Select(Video)], page.Next, page.Total), ProtocolJson.Default.VideoPageDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAsync(HttpContext context, Guid id, ChronosDatabase db, [FromServices] ArchiveService? archives,
|
||||
[FromServices] IVideoLibrary? videos) =>
|
||||
await Library(videos, archives, db).GetAsync(id, context.RequestAborted) is { } item
|
||||
? Results.Json(Video(item), ProtocolJson.Default.VideoDto)
|
||||
: ApiErrors.NotFound(context, "render");
|
||||
|
||||
/// <summary>
|
||||
/// With <c>dryRun</c> the plan of moving <c>ids</c> into the archive's trash: the renders that go (one whose file is
|
||||
/// missing loses only its entry), their bytes, those left where they are (<c>busy</c>, <c>not_found</c>) and the plan's
|
||||
/// fingerprint; nothing moves. Otherwise the request carries that fingerprint and the renders move as planned, each
|
||||
/// into a trash entry (<see cref="VideoDeletePlanDto.TrashEntries"/>); copies in the videos folder are never touched.
|
||||
/// 400 <c>bad_request</c> (<c>ids</c>, <c>fingerprint</c>); 409 <c>plan_changed</c> (nothing moved), <c>video_busy</c>,
|
||||
/// <c>sequence_busy</c>, <c>folder_in_use</c>; 503 <c>archive_offline</c>. Publishes <c>sequenceChanged</c>
|
||||
/// (<c>renders</c>) for every sequence that lost a render.
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, VideoDeleteRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
var library = Library(videos, archives, db);
|
||||
if (!library.IsAvailable) return Unavailable(context);
|
||||
try
|
||||
{
|
||||
if (request.DryRun)
|
||||
{
|
||||
var plan = await library.PlanDeleteAsync(ids, context.RequestAborted);
|
||||
return Results.Json(new VideoDeletePlanDto([.. plan.Items.Select(Item)], plan.Bytes, [.. plan.Blocked.Select(Blocked)], plan.Fingerprint, DryRun: true),
|
||||
ProtocolJson.Default.VideoDeletePlanDto);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
|
||||
// Files move into the trash: the delete runs to the end even if the client disconnects meanwhile.
|
||||
var result = await library.DeleteAsync(ids, request.Fingerprint, caller.User.Username, lifetime.ApplicationStopping);
|
||||
var moved = result.Deleted.Where(i => !i.Missing).Sum(i => i.Render.Bytes);
|
||||
if (result.Deleted.Count > 0)
|
||||
{
|
||||
await audit.WriteAsync(caller, context, "videos_deleted", "videos", result.Deleted.Count == 1 ? result.Deleted[0].Render.Id.ToString() : null,
|
||||
Summary(result.Deleted.Count, moved, result.Deleted.Select(i => i.FileName)));
|
||||
}
|
||||
foreach (var sequenceId in result.Deleted.Select(i => i.Render.SequenceId).Distinct())
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sequenceId, CancellationToken.None) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "renders", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
}
|
||||
return Results.Json(new VideoDeletePlanDto([.. result.Deleted.Select(Item)], moved, [.. result.Blocked.Select(Blocked)], request.Fingerprint,
|
||||
DryRun: false, result.TrashEntries), ProtocolJson.Default.VideoDeletePlanDto);
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return Refused(context, ex);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_busy");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A file is open elsewhere: nothing of it moved.
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues one <c>video-copy</c> job copying <c>ids</c> into the server's videos folder (<see cref="ServerOptions.VideosPath"/>),
|
||||
/// each copy hash-verified before it takes its name (a free one, " (2)" on a collision); the renders are never touched.
|
||||
/// 202 with the job. 400 <c>bad_request</c> (<c>ids</c>); 404 <c>not_found</c> (<c>render</c>, details); 409
|
||||
/// <c>videos_folder_unset</c>, <c>job_unavailable</c>; 422 <c>videos_folder_invalid</c> (inside the archive or the data
|
||||
/// folder); 507 <c>videos_no_space</c> (the folder's volume cannot take the renders' bytes).
|
||||
/// </summary>
|
||||
private static async Task<IResult> CopyAsync(HttpContext context, Caller caller, VideoCopyRequest request, ChronosDatabase db, ServerOptions options,
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, JobEngineHost host, VolumeSpace volumes, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
var folder = Blank(options.VideosPath);
|
||||
var library = Library(videos, archives, db);
|
||||
if (folder is null) return ApiErrors.Conflict(context, VideoErrors.FolderUnset);
|
||||
if (!ServerSettingsStore.IsVideosFolder(folder, options) || (library.FolderProblem(folder) is { } problem && problem != VideoErrors.FolderUnset))
|
||||
return Refused(context, VideoErrors.FolderInvalid);
|
||||
var renders = new List<Render>(ids.Count);
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await db.Renders.GetAsync(id, ct) is not { } render) return ApiErrors.NotFound(context, "render");
|
||||
renders.Add(render);
|
||||
}
|
||||
if (!library.IsAvailable || !host.CanRun(JobKind.VideoCopy)) return Unavailable(context);
|
||||
if (volumes.Measure(folder) is { } volume && volume.FreeBytes < renders.Sum(r => r.Bytes)) return Refused(context, VideoErrors.NoSpace);
|
||||
ArchiveJobRequest job;
|
||||
try
|
||||
{
|
||||
job = library.CopyJob(new VideoCopyParameters(ids, folder, FromServer: false, caller.User.Username));
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return Refused(context, ex);
|
||||
}
|
||||
var queued = await host.Engine.EnqueueAsync(job, caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "videos_copied", "job", queued.Id.ToString(),
|
||||
Summary(renders.Count, renders.Sum(r => r.Bytes), renders.Select(r => Path.GetFileName(r.OutputPath.TrimEnd('/', '\\')))));
|
||||
return Results.Json(new VideoCopyResultDto(queued.Id), ProtocolJson.Default.VideoCopyResultDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>The answer of a library refusal: its code with its status.</summary>
|
||||
internal static IResult Refused(HttpContext context, VideoLibraryException ex) => Refused(context, ex.Code);
|
||||
|
||||
private static IResult Refused(HttpContext context, string code) => ApiErrors.Result(context, code switch
|
||||
{
|
||||
VideoErrors.FolderInvalid or VideoErrors.HashMismatch => StatusCodes.Status422UnprocessableEntity,
|
||||
VideoErrors.NoSpace => StatusCodes.Status507InsufficientStorage,
|
||||
_ => StatusCodes.Status409Conflict,
|
||||
}, code);
|
||||
|
||||
/// <summary>This server's archive engine has no videos library (a build before it): nothing can be deleted or copied.</summary>
|
||||
private static IResult Unavailable(HttpContext context) => ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.VideoCopy));
|
||||
|
||||
/// <summary>The ids of a request, each once in order; null when there are none, too many, or an empty one.</summary>
|
||||
private static List<Guid>? Ids(IReadOnlyList<Guid>? ids)
|
||||
{
|
||||
if (ids is null || ids.Count is 0 or > MaxIds || ids.Contains(Guid.Empty)) return null;
|
||||
return [.. ids.Distinct()];
|
||||
}
|
||||
|
||||
private static VideoDeleteItemDto Item(VideoItem item) =>
|
||||
new(item.Render.Id, item.Render.SequenceId, item.SequenceTitle, item.FileName, item.Missing ? 0 : item.Render.Bytes, item.Missing);
|
||||
|
||||
private static VideoBlockedDto Blocked(VideoBlocked blocked) => new(blocked.RenderId, blocked.Reason);
|
||||
|
||||
/// <summary>An audit entry's details: how many, their bytes, and the first file names.</summary>
|
||||
private static string Summary(int count, long bytes, IEnumerable<string> names) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{count} · {bytes} · {string.Join(", ", names.Take(AuditNames))}");
|
||||
|
||||
private static string? Blank(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
|
||||
}
|
||||
@@ -40,6 +40,7 @@ public sealed class ServerOptions
|
||||
("CHRONOS_SERVER_NAME", nameof(ServerName), (o, v) => o.ServerName = v),
|
||||
("CHRONOS_ARCHIVE_PATH", nameof(ArchivePath), (o, v) => o.ArchivePath = v),
|
||||
("CHRONOS_SPACE_PATH", nameof(SpacePath), (o, v) => o.SpacePath = v),
|
||||
("CHRONOS_VIDEOS_PATH", nameof(VideosPath), (o, v) => o.VideosPath = v),
|
||||
("CHRONOS_ADMIN_USER", nameof(AdminUser), (o, v) => o.AdminUser = v),
|
||||
("CHRONOS_ADMIN_PASSWORD", nameof(AdminPassword), (o, v) => o.AdminPassword = v),
|
||||
("CHRONOS_DB", nameof(Database), (o, v) => o.ApplyDatabase(v)),
|
||||
@@ -106,6 +107,14 @@ public sealed class ServerOptions
|
||||
/// </summary>
|
||||
public string? SpacePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The folder "Copy to videos folder" copies renders into, hash-verified, flat, " (2)" on a collision (owner review 1,
|
||||
/// R9; key <c>VideosPath</c>, variable <c>CHRONOS_VIDEOS_PATH</c>, which locks it). Docker: the <c>/videos</c> volume.
|
||||
/// Unset by default, which turns copying off (<c>videos_folder_unset</c>); an absolute folder outside the archive and
|
||||
/// the data folder (<see cref="ServerSettingsStore.IsVideosFolder"/>). Chronos never deletes what it copied there.
|
||||
/// </summary>
|
||||
public string? VideosPath { get; set; }
|
||||
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Chronos Server") : "/data";
|
||||
public string? AdminUser { get; set; }
|
||||
public string? AdminPassword { get; set; }
|
||||
@@ -394,6 +403,8 @@ public sealed class ServerOptions
|
||||
{
|
||||
throw new InvalidOperationException($"CHRONOS_TRUSTED_PROXIES must list IP addresses (such as 172.30.0.10) or networks in CIDR form: {ex.Message}", ex);
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(VideosPath) && !Path.IsPathFullyQualified(VideosPath.Trim()))
|
||||
throw new InvalidOperationException("CHRONOS_VIDEOS_PATH must be an absolute folder, such as /videos.");
|
||||
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Chronos.Server.Configuration;
|
||||
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (only the
|
||||
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
|
||||
/// parallelism and the priority queue included (owner review 1), and the log settings through <see cref="ServerLogging"/>
|
||||
/// (owner review 2, R11), and the public ports clients use (owner review 3); the listening ports, TLS and chunk size wait for
|
||||
/// (owner review 2, R11), the public ports clients use (owner review 3) and the videos folder (owner review 1, R9; checked by
|
||||
/// <see cref="IsVideosFolder"/>); the listening ports, TLS and chunk size wait for
|
||||
/// a restart. In a container the listening ports are locked: the template maps them. Job history is what the housekeeping system
|
||||
/// schedule is reset to (owner review 2, R10): the schedule's own value applies. The audit retention kept here is what the
|
||||
/// audit clean-up schedule is reset to; the endpoint shows that schedule's age limit in its place and puts a new one there
|
||||
@@ -27,9 +28,11 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup,
|
||||
JobKind.EmptyTrash, JobKind.Convert,
|
||||
JobKind.EmptyTrash, JobKind.Convert, JobKind.VideoCopy,
|
||||
];
|
||||
|
||||
private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private ServerSettingsDto? _saved;
|
||||
|
||||
@@ -52,8 +55,9 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
Logs = request.Logs ?? before.Logs,
|
||||
PublicHttpPort = Public(request.PublicHttpPort, before.PublicHttpPort),
|
||||
PublicHttpsPort = Public(request.PublicHttpsPort, before.PublicHttpsPort),
|
||||
VideosPath = Videos(request.VideosPath, before.VideosPath),
|
||||
};
|
||||
if (Validate(request, before) is { } invalid) return ("invalid_setting", invalid);
|
||||
if (Validate(request, before, options) is { } invalid) return ("invalid_setting", invalid);
|
||||
lock (_gate)
|
||||
{
|
||||
var current = _saved ?? Snapshot(options, restartRequired: false);
|
||||
@@ -100,6 +104,8 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
// Read by LAN discovery and the admin redirect at every use: they apply at once.
|
||||
options.PublicHttpPort = request.PublicHttpPort;
|
||||
options.PublicHttpsPort = request.PublicHttpsPort;
|
||||
// Read by every copy request: it applies at once.
|
||||
options.VideosPath = request.VideosPath;
|
||||
logging.Apply(options);
|
||||
var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
@@ -123,7 +129,41 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Parallelism, o.PriorityQueue,
|
||||
Priorities(PriorityQueue(o)), o.Discovery, o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours,
|
||||
Logs(o), LockedSettings(o), LockedBy(o), restartRequired, ProxyWarning: false, o.PublicHttpPort, o.PublicHttpsPort, o.InContainer);
|
||||
Logs(o), LockedSettings(o), LockedBy(o), restartRequired, ProxyWarning: false, o.PublicHttpPort, o.PublicHttpsPort, o.InContainer,
|
||||
string.IsNullOrWhiteSpace(o.VideosPath) ? null : o.VideosPath.Trim());
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="folder"/> may be the videos folder (owner review 1, R9): an absolute folder that is neither the
|
||||
/// archive nor the data folder nor inside either, so a copy never lands among the files the server indexes or keeps.
|
||||
/// </summary>
|
||||
public static bool IsVideosFolder(string folder, ServerOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (string.IsNullOrWhiteSpace(folder) || folder.Contains('\0', StringComparison.Ordinal) || !Path.IsPathFullyQualified(folder.Trim())) return false;
|
||||
string full;
|
||||
try
|
||||
{
|
||||
full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder.Trim()));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
foreach (var root in new[] { options.ArchivePath, options.DataPath })
|
||||
{
|
||||
var rootFull = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
|
||||
if (string.Equals(full, rootFull, PathComparison) || full.StartsWith(rootFull + Path.DirectorySeparatorChar, PathComparison)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The videos folder as a request sets it: null keeps <paramref name="current"/>, an empty text clears it.</summary>
|
||||
private static string? Videos(string? requested, string? current) => requested switch
|
||||
{
|
||||
null => current,
|
||||
_ when string.IsNullOrWhiteSpace(requested) => null,
|
||||
_ => requested.Trim(),
|
||||
};
|
||||
|
||||
/// <summary>The listening ports, which a container's template maps (owner review 3).</summary>
|
||||
private static readonly string[] ContainerPorts = [nameof(ServerOptions.HttpPort), nameof(ServerOptions.HttpsPort)];
|
||||
@@ -177,8 +217,10 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
/// The first setting of <paramref name="r"/> out of range, or null. Listening ports are checked only when they change,
|
||||
/// so a value the panel cannot change (a container's, the test server's 0) never blocks saving the others.
|
||||
/// </summary>
|
||||
private static string? Validate(ServerSettingsDto r, ServerSettingsDto current)
|
||||
private static string? Validate(ServerSettingsDto r, ServerSettingsDto current, ServerOptions options)
|
||||
{
|
||||
// Checked when it changes, so a folder an environment variable sets never blocks saving the others.
|
||||
if (r.VideosPath is { } videos && videos != current.VideosPath && !IsVideosFolder(videos, options)) return nameof(ServerOptions.VideosPath);
|
||||
if (string.IsNullOrWhiteSpace(r.ServerName) || r.ServerName.Trim().Length > 60) return nameof(ServerOptions.ServerName);
|
||||
var portsChanged = r.HttpPort != current.HttpPort || r.HttpsPort != current.HttpsPort;
|
||||
if (portsChanged && r.HttpPort is < 1 or > 65535) return nameof(ServerOptions.HttpPort);
|
||||
@@ -244,6 +286,8 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
Add(nameof(ServerOptions.LogRotation), Rotation(a.Logs.Rotation), Rotation(b.Logs.Rotation), v => JsonValue.Create(v.ToString()));
|
||||
Add(nameof(ServerOptions.AuditRetentionDays), a.Logs.AuditRetentionDays, b.Logs.AuditRetentionDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.DiagnosticsLogMb), a.Logs.DiagnosticsLogMb, b.Logs.DiagnosticsLogMb, v => JsonValue.Create(v));
|
||||
// A cleared videos folder is stored as null, so server.json no longer sets one.
|
||||
Add(nameof(ServerOptions.VideosPath), a.VideosPath, b.VideosPath, v => v is null ? null : JsonValue.Create(v));
|
||||
return changes;
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,8 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_TLS_CERT CHRONOS_TLS_KEY CHRONOS_LANG
|
||||
CHRONOS_SPACE_PATH folder whose volume's free space the admin panel shows (default: the archive's); on
|
||||
Unraid the share's array view (/mnt/user0/<share>) mapped read-only to /space
|
||||
CHRONOS_VIDEOS_PATH folder "Copy to videos folder" copies renders into, hash-verified (default: none, copying
|
||||
off); in a container the /videos volume
|
||||
CHRONOS_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
|
||||
cores); CHRONOS_WORKERS, its former name, still sets it
|
||||
CHRONOS_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
|
||||
|
||||
@@ -187,6 +187,7 @@ public static class ServerHost
|
||||
ProjectEndpoints.Map(api);
|
||||
LibraryEndpoints.Map(api);
|
||||
FileEndpoints.Map(api);
|
||||
VideoEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
JobEndpoints.Map(api);
|
||||
ScheduleEndpoints.Map(api);
|
||||
|
||||
@@ -3,6 +3,7 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
@@ -37,7 +38,7 @@ public static class ArchiveModule
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
var volumes = sp.GetService<VolumeSpace>();
|
||||
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
|
||||
return new ArchiveService(db, new ArchiveServiceOptions
|
||||
var service = new ArchiveService(db, new ArchiveServiceOptions
|
||||
{
|
||||
// A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3).
|
||||
SequenceChanged = async (id, change, ct) =>
|
||||
@@ -71,9 +72,14 @@ public static class ArchiveModule
|
||||
// Next to the index in the data folder, where the daily backups always went.
|
||||
BackupDirectory = Path.Combine(options.DataPath, DatabaseBackups.DirectoryName),
|
||||
});
|
||||
// A copy job checks its folder again when it runs: the data folder is refused there too, as the settings refuse it.
|
||||
service.Videos.ProtectedFolders = () => [options.DataPath];
|
||||
return service;
|
||||
});
|
||||
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
|
||||
// The videos library of the archive's index (owner review 1, R9): /api/v1/videos.
|
||||
services.AddSingleton<IVideoLibrary>(sp => sp.GetRequiredService<ArchiveService>().Videos);
|
||||
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ public static class FileResponses
|
||||
[".jpg"] = "image/jpeg",
|
||||
[".jpeg"] = "image/jpeg",
|
||||
[".png"] = "image/png",
|
||||
[".apng"] = "image/apng",
|
||||
[".gif"] = "image/gif",
|
||||
[".tif"] = "image/tiff",
|
||||
[".tiff"] = "image/tiff",
|
||||
@@ -22,6 +23,9 @@ public static class FileResponses
|
||||
[".mp4"] = "video/mp4",
|
||||
[".mov"] = "video/quicktime",
|
||||
[".avi"] = "video/x-msvideo",
|
||||
// The admin panel's player (owner review 1, R9) plays what a browser's <video> takes.
|
||||
[".webm"] = "video/webm",
|
||||
[".m4v"] = "video/mp4",
|
||||
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public static string ContentTypeOf(string fileName) =>
|
||||
|
||||
@@ -66,11 +66,29 @@ public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeP
|
||||
ProducedBy = producedBy,
|
||||
ProjectId = projectId,
|
||||
ProjectVersionId = projectVersionId,
|
||||
// Verified against the bytes when the upload completed (owner review 1, R9: every single-file render hashed).
|
||||
Sha256 = UploadRules.IsSha256(output.Sha256) ? output.Sha256.ToLowerInvariant() : null,
|
||||
Kind = KindOf(output.Kind),
|
||||
};
|
||||
await db.Renders.InsertAsync(render, cancellationToken);
|
||||
return (Render?)render;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>The longest kind a render is recorded with.</summary>
|
||||
private const int MaxKindLength = 32;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="Render.Kind"/> a client or a render node names, as recorded: null for a video or an image sequence (told
|
||||
/// apart by the codec) and for anything that is not a plain lower-case word; a newer Chronos's kind as it is.
|
||||
/// </summary>
|
||||
public static string? KindOf(string? kind)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(kind)) return null;
|
||||
var word = kind.Trim().ToLowerInvariant();
|
||||
if (word.Length > MaxKindLength || !word.All(c => c is (>= 'a' and <= 'z') or '-')) return null;
|
||||
return word is RenderKind.Video or RenderKind.Sequence ? null : word;
|
||||
}
|
||||
|
||||
private static string Unique(string folder, string fileName)
|
||||
{
|
||||
var candidate = Path.Combine(folder, fileName);
|
||||
|
||||
@@ -98,8 +98,9 @@ public sealed class RenderUploads(
|
||||
|
||||
if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome<RenderDto>.Fail(422, "hash_mismatch");
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken);
|
||||
// The hash just verified and the kind (a still, owner review 1, R9) are recorded with the render.
|
||||
var result = new RenderResultRequest(output.FileName, output.Size, output.Sha256, output.PresetName, output.Codec, output.Width, output.Height, output.Fps,
|
||||
output.DurationSeconds);
|
||||
output.DurationSeconds, output.Kind);
|
||||
Render? render;
|
||||
try
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user