The web panel now manages the library without editing it: the owner can browse and view sequences and photos, delete sequences and photos into the archive's trash, restore or empty the trash and run mass operations, as R6 asks, on top of the engine endpoints of the previous commit. - Library page right after the Dashboard: search, Year/Camera/Status/Tag filters fed by a new GET /api/v1/sequences/facets, sort, cards or list (remembered per browser), lazy cover thumbnails, Load more by cursor, multi-select with Shift ranges and "Select all N" of the filter, and a sticky bar for the selection: Analyse, Proxies, Thumbnails, Verify, Tags (add/remove), Export CSV (client-side) and Delete (dry run, list of what moves to the trash, then the move). Filters live in the address, so Back from a sequence finds them again. - Sequence view (#/library?id=): inline title, tags, rating and notes, facts, photos in pages of 500 with content-visibility, a photo viewer (proxy, arrows, Esc, Exif facts), Set cover, Download original, Delete photos (typing the count above 20 photos), Delete sequence, renders to download. No video editing controls. - Trash view (#/library?view=trash, also linked from Archive): entries, Restore, and Empty (dry run, list, the localised word typed, the plan's fingerprint sent back, the job followed to its end). - Live updates from sequenceChanged and jobState; keyboard grid (one tab stop, arrows, Space, Shift+Space, Enter, Ctrl+A, Esc); RTL, dark theme. - GET /sequences takes rendered=true|false for the Status filter. - ui.js: confirmDialog's typed confirmation by name, word or count, with a list of what the action concerns; formDialog. api.js: putBytes for the web upload, which the Library imports on demand (upload.js, optional). - New web icons from icons.py (Image for the Library, trash, grid/list, arrows, stars, cover); directional glyphs mirror in right-to-left pages. - Strings in en and it; tests for the facets (both dialects), the rendered filter, the menu, the modules and the on-demand upload import. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 029cf334f66cb6fa1265b96a6f8faff2964c11ea)
292 lines
15 KiB
C#
292 lines
15 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Security.Cryptography.X509Certificates;
|
|
using System.Text.RegularExpressions;
|
|
using Microsoft.AspNetCore.Hosting.Server;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Chronos.Protocol;
|
|
using Chronos.Server.Hosting;
|
|
using Chronos.Testing;
|
|
|
|
namespace Chronos.Server.Tests.Hosting;
|
|
|
|
[Category("server")]
|
|
public sealed partial class SystemEndpointTests(TestContext context)
|
|
{
|
|
[Test]
|
|
public async Task HealthReportsOk()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var health = await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus);
|
|
Assert.Equal("ok", Assert.NotNull(health).Status);
|
|
Assert.Equal("ok", health.Checks["archive"]);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ServerInfoCarriesFingerprintAndApiHeader()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
using var response = await server.Client.GetAsync("/api/v1/server/info");
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.Equal("1", response.Headers.GetValues(ApiVersion.Header).Single());
|
|
var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo);
|
|
Assert.Equal(1, Assert.NotNull(info).ApiVersion);
|
|
Assert.Equal(95, Assert.NotNull(info.TlsFingerprint).Length); // 32 bytes as XX: pairs
|
|
}
|
|
|
|
[Test]
|
|
public async Task HttpsServesTheAdvertisedCertificate()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var info = await server.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo);
|
|
string? seen = null;
|
|
using var handler = new HttpClientHandler
|
|
{
|
|
ServerCertificateCustomValidationCallback = (_, cert, _, _) =>
|
|
{
|
|
seen = cert is null ? null : string.Join(':', cert.GetCertHash(System.Security.Cryptography.HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
|
|
return true;
|
|
},
|
|
};
|
|
using var https = new HttpClient(handler) { BaseAddress = Assert.NotNull(server.HttpsBase) };
|
|
using var response = await https.GetAsync("/health");
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.Equal(Assert.NotNull(info).TlsFingerprint, seen);
|
|
}
|
|
|
|
[Test]
|
|
public async Task CertificateIsReusedAcrossRestarts()
|
|
{
|
|
var root = context.CreateTempDirectory("restart");
|
|
string? first;
|
|
await using (var a = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data")))
|
|
first = (await a.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint;
|
|
await using var b = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data"));
|
|
var second = (await b.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint;
|
|
Assert.Equal(first, second);
|
|
}
|
|
|
|
[Test]
|
|
public async Task UnknownApiRouteReturnsJsonError()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
using var response = await server.Client.GetAsync("/api/v1/does-not-exist");
|
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
|
var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError);
|
|
Assert.Equal("not_found", Assert.NotNull(error).Code);
|
|
}
|
|
|
|
[Test]
|
|
public async Task AdminPanelIsServedWithEtags()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
using var redirect = await new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = server.HttpBase }.GetAsync("/admin");
|
|
Assert.Equal(HttpStatusCode.Redirect, redirect.StatusCode);
|
|
using var page = await server.Client.GetAsync("/admin/");
|
|
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
|
|
Assert.Contains("app.js", await page.Content.ReadAsStringAsync());
|
|
var etag = page.Headers.ETag;
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin/");
|
|
request.Headers.IfNoneMatch.Add(Assert.NotNull(etag));
|
|
using var cached = await server.Client.SendAsync(request);
|
|
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
|
|
}
|
|
|
|
[Test]
|
|
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
|
|
{
|
|
// The container listens on 8443, published on the host as 18443 (BRIEF §19.6: the template's ports are editable).
|
|
await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 18443);
|
|
var kestrel = server.Services.GetRequiredService<IServer>();
|
|
var request = AdminRequest(IPAddress.Parse("10.0.0.7"));
|
|
Assert.Equal("https://10.0.0.5:18443/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
|
|
|
|
server.Options.PublicHttpsPort = null;
|
|
Assert.Equal($"https://10.0.0.5:{Assert.NotNull(server.HttpsBase).Port}/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
|
|
Assert.Null(AdminPanel.HttpsLocation(AdminRequest(IPAddress.Loopback), server.Options, kestrel));
|
|
}
|
|
|
|
private static DefaultHttpContext AdminRequest(IPAddress from)
|
|
{
|
|
var request = new DefaultHttpContext();
|
|
request.Connection.RemoteIpAddress = from;
|
|
request.Request.Scheme = "http";
|
|
request.Request.Host = new HostString("10.0.0.5", 18080);
|
|
request.Request.Path = "/admin/";
|
|
request.Request.QueryString = new QueryString("?page=jobs");
|
|
return request;
|
|
}
|
|
|
|
[Test]
|
|
public async Task AdminPanelRunsUnderAStrictPolicyAndIsNeverFramed()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
foreach (var path in new[] { "/admin/", "/admin/app.js", "/admin/admin.css" })
|
|
{
|
|
using var response = await server.Client.GetAsync(path);
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
var policy = string.Join(' ', response.Headers.GetValues("Content-Security-Policy"));
|
|
foreach (var directive in new[] { "default-src 'self'", "script-src 'self'", "style-src 'self'", "frame-ancestors 'none'" })
|
|
Assert.Contains(directive, policy);
|
|
Assert.True(!policy.Contains("unsafe-inline", StringComparison.Ordinal), policy);
|
|
Assert.Equal("DENY", response.Headers.GetValues("X-Frame-Options").Single());
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public async Task AdminPanelModulesAllResolve()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var index = await server.Client.GetStringAsync("/admin/");
|
|
// The page container is not a live region: only toasts and form errors announce themselves.
|
|
Assert.True(!index.Contains("aria-live", StringComparison.Ordinal), index);
|
|
var seen = await ModulesAsync(server);
|
|
Assert.True(seen.Count >= 17, string.Join(", ", seen.Keys));
|
|
// The Library's views (owner review 2, R6) are modules of their own under pages/library.
|
|
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js" })
|
|
Assert.True(seen.ContainsKey(module), module);
|
|
}
|
|
|
|
[Test]
|
|
public async Task AdminPanelListsTheLibraryAndLoadsTheWebUploadOnlyWhenItIsThere()
|
|
{
|
|
// Owner review 2, R6: the Library comes right after the Dashboard. The web upload (R3) is a module of its own that the
|
|
// Library imports on demand, so the panel works with or without it.
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var app = await server.Client.GetStringAsync("/admin/app.js");
|
|
var top = MenuPages(app)[0];
|
|
Assert.SequenceEqual(["dashboard", "library"], top.Take(2));
|
|
var icons = await server.Client.GetStringAsync("/admin/icons.js");
|
|
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
|
|
foreach (var page in MenuPages(app).SelectMany(group => group))
|
|
{
|
|
Assert.Contains($" {page}: `<svg", icons);
|
|
var name = $"Admin.Nav.{char.ToUpperInvariant(page[0])}{page[1..]}";
|
|
Assert.True(strings.ContainsKey(name) && strings.ContainsKey(name + ".Tip"), name);
|
|
}
|
|
|
|
var modules = await ModulesAsync(server);
|
|
Assert.Contains(@"import(""../upload.js"")", modules["pages/library.js"]);
|
|
foreach (var (module, source) in modules)
|
|
{
|
|
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
|
|
foreach (Match import in StaticImport().Matches(source))
|
|
Assert.True(Resolve(folder, import.Groups[1].Value) != "upload.js", $"{module} imports upload.js statically");
|
|
}
|
|
using var upload = await server.Client.GetAsync("/admin/upload.js");
|
|
if (upload.StatusCode == HttpStatusCode.OK)
|
|
Assert.True(Regex.IsMatch(await upload.Content.ReadAsStringAsync(), @"export (?:async )?function openUpload\("), "upload.js exports openUpload");
|
|
else
|
|
Assert.Equal(HttpStatusCode.NotFound, upload.StatusCode);
|
|
}
|
|
|
|
/// <summary>The admin panel's modules from app.js and the menu's pages along their static imports, with their source.</summary>
|
|
private static async Task<Dictionary<string, string>> ModulesAsync(TestServer server)
|
|
{
|
|
var app = await server.Client.GetStringAsync("/admin/app.js");
|
|
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("app.js"));
|
|
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
|
|
while (pending.TryDequeue(out var module))
|
|
{
|
|
if (seen.ContainsKey(module)) continue;
|
|
using var response = await server.Client.GetAsync("/admin/" + module);
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode, module);
|
|
var source = await response.Content.ReadAsStringAsync();
|
|
seen[module] = source;
|
|
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
|
|
foreach (Match import in StaticImport().Matches(source))
|
|
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
|
|
}
|
|
return seen;
|
|
}
|
|
|
|
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
|
|
private static partial Regex StaticImport();
|
|
|
|
[Test]
|
|
public async Task AdminPanelDocksSettingsAtTheFootAndFoldsAboutIntoIt()
|
|
{
|
|
// Owner review 2: Settings below the other pages, About its last group; old #/about bookmarks open it there.
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var app = await server.Client.GetStringAsync("/admin/app.js");
|
|
var groups = MenuPages(app);
|
|
Assert.Count(2, groups);
|
|
Assert.SequenceEqual(new[] { "settings" }, groups[1]);
|
|
Assert.DoesNotContain("about", groups[0]);
|
|
Assert.Contains(@"about: ""settings?group=about""", app);
|
|
using var about = await server.Client.GetAsync("/admin/pages/about.js");
|
|
Assert.Equal(HttpStatusCode.NotFound, about.StatusCode);
|
|
var settings = await server.Client.GetStringAsync("/admin/pages/settings.js");
|
|
Assert.Contains(@"id=""about-title""", settings);
|
|
// The page draws before the dashboard aggregate answers; these two rows fill in afterwards.
|
|
Assert.Contains(@"id=""about-database""", settings);
|
|
Assert.Contains(@"id=""about-uptime""", settings);
|
|
}
|
|
|
|
/// <summary>The menu's page groups as app.js lists them: the top pages, then the ones docked at the foot.</summary>
|
|
private static List<string[]> MenuPages(string app) =>
|
|
[.. Regex.Matches(app, @"const (?:top|bottom)Pages = \[([^\]]*)\]")
|
|
.Select(m => m.Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"')).ToArray())];
|
|
|
|
private static string Resolve(string folder, string relative)
|
|
{
|
|
var parts = (folder + relative).Split('/').ToList();
|
|
for (var i = 0; i < parts.Count; i++)
|
|
{
|
|
if (parts[i] == ".") parts.RemoveAt(i--);
|
|
else if (parts[i] == ".." && i > 0) parts.RemoveRange(--i, 2);
|
|
}
|
|
return string.Join('/', parts.Where(p => p.Length > 0));
|
|
}
|
|
|
|
[Test]
|
|
public async Task I18nEndpointFallsBackToEnglish()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var it = await server.Client.GetFromJsonAsync("/api/v1/i18n/it-IT", ProtocolJson.Default.DictionaryStringString);
|
|
Assert.Equal("Accedi", Assert.NotNull(it)["Admin.Login.SignIn"]);
|
|
var unknown = await server.Client.GetFromJsonAsync("/api/v1/i18n/xx", ProtocolJson.Default.DictionaryStringString);
|
|
Assert.Equal("Sign in", Assert.NotNull(unknown)["Admin.Login.SignIn"]);
|
|
}
|
|
|
|
[Test]
|
|
public async Task I18nEndpointMarksRightToLeftLanguages()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
foreach (var (culture, rtl) in new[] { ("ar", "true"), ("he", "true"), ("it", "false"), ("en", "false") })
|
|
{
|
|
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync($"/api/v1/i18n/{culture}", ProtocolJson.Default.DictionaryStringString));
|
|
Assert.Equal((culture, rtl), (strings["$culture"], strings["$rtl"]));
|
|
// Count strings reach the panel in their plural forms.
|
|
Assert.True(strings.ContainsKey("Admin.Users.Accounts.one") && strings.ContainsKey("Admin.Users.Accounts.other"), culture);
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public void LinuxRefusesSqlite()
|
|
{
|
|
if (OperatingSystem.IsWindows()) TestContext.Skip("SQLite is allowed on Windows");
|
|
var options = new Chronos.Server.Configuration.ServerOptions { Database = Chronos.Server.Configuration.DatabaseKind.Sqlite };
|
|
Assert.Throws<InvalidOperationException>(options.Validate);
|
|
}
|
|
|
|
[Test]
|
|
public void EnvironmentOverridesDefaults()
|
|
{
|
|
var root = context.CreateTempDirectory("env");
|
|
var env = new Dictionary<string, string?>
|
|
{
|
|
["CHRONOS_DATA_PATH"] = root,
|
|
["CHRONOS_HTTP_PORT"] = "9090",
|
|
["CHRONOS_TLS_MODE"] = "proxy",
|
|
["CHRONOS_DB"] = "postgres",
|
|
["CHRONOS_SERVER_NAME"] = "Studio NAS",
|
|
};
|
|
var options = Chronos.Server.Configuration.ServerOptions.Load(env);
|
|
Assert.Equal(9090, options.HttpPort);
|
|
Assert.Equal(Chronos.Server.Configuration.TlsMode.Proxy, options.TlsMode);
|
|
Assert.Equal("Studio NAS", options.ServerName);
|
|
}
|
|
}
|