Files
Chronos/tests/Chronos.Server.Tests/Hosting/AdminVideosTests.cs
T
Alby96andClaude Opus 5.5 ac1d6f69a1 feat(P4): admin panel Videos page, trash videos kind, videos folder setting
The panel gains the videos library page (owner review 1, R9, decision 22) so
every render of the server can be played, downloaded, copied into the videos
folder and deleted into the trash without editing anything (owner review 2, R6).

- pages/videos.js: cards and list, search, kind, codec, year and sort filters
  kept in the address (#/videos?sequence=<id>), multi-select, Play in a
  <video>/<img> dialog with a "cannot play" fallback, Download, Copy to folder
  (disabled with a reason without Edit or without a folder), Delete with the
  dry-run plan, blocked items and "copies stay", then the fingerprinted delete.
- Menu entry after Library; Trash lists, restores and names "videos" entries;
  a sequence's renders show kind and hash and link to "All videos".
- Settings: Videos folder row, read-only when CHRONOS_VIDEOS_PATH locks it,
  sent only when changed (empty clears it).
- AdminVideosTests: module loads, imports, API calls limited to the videos
  endpoints, delete order, disabled reasons, strings in en and it.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:07:04 +01:00

162 lines
11 KiB
C#

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();
}