Owner review 2, R7 asks to rename and move sequences after import, on the web panel too. The Library's mass bar gets Reorganize… for the selection (every sequence after Select all without a filter, else at most a thousand ids), and saving a changed folder or file template on the Archive page offers it for all sequences in the save toast. The dialog (reorganize.js) has a switch and a field for the folder, file and title templates, prefilled from the archive settings; each change asks POST /archive/reorganize for a dry run, one request at a time, and the table shows every step before and after (title, folder, renamed files with samples, photos that keep their names and why). Apply confirms with the counts of sequences, folders and photos, sends the shown plan's fingerprint back, and the toast links to the queued job; a plan_changed refusal plans again. Server refusals land on the field they name. Toasts can carry an action; the audit entry archive_reorganized reads as a sentence. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 13939dff9a1e8a23ce7802ac38f2ded7fdbc2a74)
203 lines
12 KiB
C#
203 lines
12 KiB
C#
using System.Globalization;
|
|
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using Chronos.Core.Codecs.Jpeg;
|
|
using Chronos.Core.Localization;
|
|
using Chronos.Core.Model;
|
|
using Chronos.Protocol;
|
|
using Chronos.Server.Storage;
|
|
using Chronos.Testing;
|
|
|
|
namespace Chronos.Server.Tests.Hosting;
|
|
|
|
/// <summary>
|
|
/// Reorganize on the admin panel (owner review 2, R7; <c>Admin/web/reorganize.js</c>): where the panel offers it (the
|
|
/// Library's mass bar, the Archive page's save toast), the dialog module and its strings, and the requests the dialog
|
|
/// writes, sent through the cookie session as <c>api.js</c> sends them and read back by the names the dialog reads.
|
|
/// </summary>
|
|
[Category("server")]
|
|
public sealed partial class AdminReorganizeTests(TestContext context)
|
|
{
|
|
private const string Url = "/api/v1/archive/reorganize";
|
|
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
|
|
|
|
[Test]
|
|
public async Task TheLibraryAndTheArchivePageOpenTheReorganizeDialog()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var library = await server.Client.GetStringAsync("/admin/pages/library.js");
|
|
Assert.Contains(@"from ""../reorganize.js""", library);
|
|
Assert.Contains(@"data-mass=""reorganize"" data-i18n=""Admin.Reorganize.Action"" data-i18n-title=""Admin.Reorganize.Action.Tip""", library);
|
|
Assert.Contains(@"if (action === ""reorganize"") return reorganize();", library);
|
|
// The selection: every sequence after Select all without a filter, else the ids (one request takes a thousand).
|
|
Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }", library);
|
|
Assert.Contains("selection.size > BULK_LIMIT", library);
|
|
var archive = await server.Client.GetStringAsync("/admin/pages/archive.js");
|
|
Assert.Contains(@"from ""../reorganize.js""", archive);
|
|
Assert.Contains("target: { all: true }", archive);
|
|
|
|
using var response = await server.Client.GetAsync("/admin/reorganize.js");
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType);
|
|
var dialog = await response.Content.ReadAsStringAsync();
|
|
Assert.True(Regex.IsMatch(dialog, @"export function openReorganize\(\{ api, target, "), "reorganize.js exports openReorganize({ api, target, … })");
|
|
var imports = StaticImport().Matches(dialog).Select(m => m.Groups[1].Value).ToList();
|
|
Assert.SequenceEqual(["./i18n.js", "./ui.js"], imports);
|
|
foreach (var module in imports)
|
|
{
|
|
using var imported = await server.Client.GetAsync("/admin/" + module[2..]);
|
|
Assert.Equal(HttpStatusCode.OK, imported.StatusCode, module);
|
|
}
|
|
// A dry run at every change; Apply sends that plan's fingerprint back and links the job it queued.
|
|
Assert.Contains("api.post(ENDPOINT, { ...body, dryRun: true })", dialog);
|
|
Assert.Contains("api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint })", dialog);
|
|
Assert.Contains("#/jobs?job=", dialog);
|
|
Assert.True(!Regex.IsMatch(dialog, @"\son[a-z]+="""), "inline handler");
|
|
|
|
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));
|
|
foreach (var key in Regex.Matches(dialog + library + archive, @"""(Admin\.Reorganize\.[A-Za-z.]+)""").Select(m => m.Groups[1].Value).Distinct())
|
|
{
|
|
var name = en.ContainsKey(key) ? key : key + ".other";
|
|
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
|
|
}
|
|
Assert.Equal("Riorganizza…", it["Admin.Reorganize.Action"]);
|
|
}
|
|
|
|
[Test]
|
|
public async Task TheDialogsRequestsPlanAndQueueAReorganize()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
|
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
|
Guid id = default;
|
|
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
|
await UntilIdleAsync(server);
|
|
var browser = await Browser.SignInAsync(server);
|
|
|
|
// The body the dialog writes: the selection's ids and the parts switched on, then dryRun.
|
|
StringContent Body(string tail) =>
|
|
Json($$"""{"all":false,"sequenceIds":["{{id}}"],"folderTemplate":"reorganized/{title}","fileTemplate":"{title}_{n:000}","titleTemplate":"Roof",{{tail}}}""");
|
|
string fingerprint;
|
|
using (var dry = await browser.SendAsync(HttpMethod.Post, Url, Body("\"dryRun\":true")))
|
|
{
|
|
await dry.ExpectAsync(HttpStatusCode.OK);
|
|
using var plan = JsonDocument.Parse(await dry.Content.ReadAsStringAsync());
|
|
var root = plan.RootElement;
|
|
Assert.Equal((1, 2, 0), (root.GetProperty("sequences").GetInt32(), root.GetProperty("files").GetInt32(), root.GetProperty("kept").GetInt32()));
|
|
fingerprint = root.GetProperty("fingerprint").GetString()!;
|
|
Assert.Equal(64, fingerprint.Length);
|
|
var step = root.GetProperty("steps").EnumerateArray().Single();
|
|
Assert.Equal(id, step.GetProperty("sequenceId").GetGuid());
|
|
Assert.True(step.GetProperty("fromFolder").GetString()!.Length > 0, "fromFolder");
|
|
Assert.Equal("reorganized/Roof", step.GetProperty("toFolder").GetString());
|
|
Assert.Equal("Roof", step.GetProperty("toTitle").GetString());
|
|
Assert.False(step.GetProperty("carried").GetBoolean());
|
|
Assert.Equal(2, step.GetProperty("fileChanges").GetInt32());
|
|
var sample = step.GetProperty("fileSamples").EnumerateArray().First();
|
|
Assert.True(sample.GetProperty("from").GetString()!.StartsWith("originals/", StringComparison.Ordinal), "from");
|
|
Assert.Equal("originals/Roof_001.JPG", sample.GetProperty("to").GetString());
|
|
Assert.Equal(0, step.GetProperty("blocked").GetArrayLength());
|
|
}
|
|
|
|
// A template the server refuses names its field, in the page's language: the dialog marks that field.
|
|
using (var bad = await browser.SendAsync(HttpMethod.Post, Url, Json("""{"all":true,"fileTemplate":"{nope}","dryRun":true}""")))
|
|
{
|
|
var error = await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template");
|
|
Assert.Equal("fileTemplate", error.Details);
|
|
Assert.Equal(Loc.Get("Server.Error.InvalidTemplate", CultureInfo.GetCultureInfo("it")), error.Message);
|
|
}
|
|
// A plan that no longer matches is refused with the one there is now: the dialog plans again.
|
|
using (var stale = await browser.SendAsync(HttpMethod.Post, Url, Body($"\"dryRun\":false,\"fingerprint\":\"{new string('0', 64)}\"")))
|
|
Assert.Equal(fingerprint, (await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
|
|
|
|
Guid job;
|
|
using (var applied = await browser.SendAsync(HttpMethod.Post, Url, Body($"\"dryRun\":false,\"fingerprint\":\"{fingerprint}\"")))
|
|
{
|
|
await applied.ExpectAsync(HttpStatusCode.Accepted);
|
|
using var queued = JsonDocument.Parse(await applied.Content.ReadAsStringAsync());
|
|
Assert.Equal("move", queued.RootElement.GetProperty("kind").GetString());
|
|
job = queued.RootElement.GetProperty("id").GetGuid();
|
|
}
|
|
await UntilJobAsync(browser, job);
|
|
var sequence = Assert.NotNull(await server.Database.Sequences.GetAsync(id));
|
|
Assert.Equal(("reorganized/Roof", "Roof"), (sequence.Folder, sequence.Title));
|
|
|
|
// Every sequence (Select all without a filter) with the same templates: nothing is left to change.
|
|
using var again = await browser.SendAsync(HttpMethod.Post, Url,
|
|
Json("""{"all":true,"folderTemplate":"reorganized/{title}","fileTemplate":"{title}_{n:000}","dryRun":true}"""));
|
|
await again.ExpectAsync(HttpStatusCode.OK);
|
|
using var none = JsonDocument.Parse(await again.Content.ReadAsStringAsync());
|
|
Assert.Equal(0, none.RootElement.GetProperty("sequences").GetInt32());
|
|
Assert.Equal(0, none.RootElement.GetProperty("steps").GetArrayLength());
|
|
}
|
|
|
|
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
|
|
private static partial Regex StaticImport();
|
|
|
|
private static async Task UntilJobAsync(Browser browser, Guid id)
|
|
{
|
|
var until = DateTime.UtcNow + Wait;
|
|
while (true)
|
|
{
|
|
using var response = await browser.SendAsync(HttpMethod.Get, $"/api/v1/jobs/{id}");
|
|
var job = await response.ReadAsync(ProtocolJson.Default.JobDto);
|
|
if (job.State == "done") return;
|
|
if (job.State is "failed" or "cancelled") Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
|
|
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State}");
|
|
await Task.Delay(50);
|
|
}
|
|
}
|
|
|
|
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
|
|
private static async Task UntilIdleAsync(TestServer server)
|
|
{
|
|
var until = DateTime.UtcNow + Wait;
|
|
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
|
|
{
|
|
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
|
|
{
|
|
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
|
|
await Task.Delay(50);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
|
|
|
|
private static byte[] Photo(int seed)
|
|
{
|
|
const int width = 96, height = 64;
|
|
var pixels = new byte[width * height * 3];
|
|
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
|
|
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
|
}
|
|
|
|
/// <summary>The bootstrap administrator signed in to the panel (a cookie session over HTTPS), calling as <c>api.js</c> does.</summary>
|
|
private sealed class Browser(HttpClient client, string csrfToken)
|
|
{
|
|
public static async Task<Browser> SignInAsync(TestServer server)
|
|
{
|
|
await server.AdminAsync();
|
|
var cookies = new CookieContainer();
|
|
var client = server.NewCookieClient(cookies);
|
|
using var login = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
|
|
ProtocolJson.Default.LoginRequest);
|
|
await login.ExpectAsync(HttpStatusCode.OK);
|
|
return new Browser(client, Assert.NotNull(cookies.GetCookies(Assert.NotNull(server.HttpsBase))["chronos_csrf"]).Value);
|
|
}
|
|
|
|
/// <summary>JSON accepted, the page's language (Italian here), and the CSRF header on every call but a GET.</summary>
|
|
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string url, HttpContent? content = null)
|
|
{
|
|
using var request = new HttpRequestMessage(method, url) { Content = content };
|
|
request.Headers.Accept.ParseAdd("application/json");
|
|
request.Headers.AcceptLanguage.ParseAdd("it");
|
|
if (method != HttpMethod.Get) request.Headers.Add("X-CSRF-Token", csrfToken);
|
|
return await client.SendAsync(request);
|
|
}
|
|
}
|
|
}
|