using System.IO;
using System.Net.Http;
using Chronos.App.Archiving;
using Chronos.App.Jobs;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.App.Library;
///
/// What the Library's quick and mass actions run (BRIEF §12.2): analyses, proxies, verifies and renders as jobs on
/// this PC's engine, or posted to the server for a sequence that only lives there; uploads, downloads and settings
/// exchanges through the sync engine (as the Server screen does); ratings through the archive engine (sidecar and
/// index together). Every queued job is announced with a toast that opens the Jobs screen.
///
public sealed class LibraryActions(ShellViewModel shell)
{
/// Wire names of the job kinds a remote card posts (POST /api/v1/jobs).
private const string RenderKind = "render";
private const string DeepAnalyseKind = "deep-analyse";
private Infrastructure.AppServices Services => shell.Services;
/// The signed-in server's sync engine and connection; null while signed out.
public RemoteSource? Remote() =>
Services.Sync is { Service: { } service, Server: { } server, Remote: { } remote } ? new RemoteSource(service, server, remote) : null;
/// What the signed-in account may do; nothing while signed out.
public SyncRights Rights => Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
/// A job can be posted to the server now (a remote card's Analyse and Render).
public bool CanPost => Services.Server is { IsConnected: true, Flow: { Address: not null, Token: not null } };
/// Deep analysis of sequences on this PC (one job), or of a remote card on the server.
public async Task AnalyseAsync(IReadOnlyList sequences)
{
if (sequences is [{ Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly } remote])
{
await PostAsync(() => Task.FromResult(new CreateJobRequest(DeepAnalyseKind, [remote.Id], null)), JobKind.DeepAnalyse, remote.DisplayTitle);
return;
}
await QueueAsync(ProcessingJobs.DeepAnalysis([.. sequences.Select(s => s.Id)], Label(sequences)));
}
public Task ProxiesAsync(IReadOnlyList sequences) => QueueAsync(ArchiveJobs.Proxies([.. sequences.Select(s => s.Id)], Label(sequences)));
/// Verification is an archive job: one per archive, naming its sequences.
public async Task VerifyAsync(IReadOnlyList sequences)
{
if (Services.Database is not { } db) return;
foreach (var group in sequences.GroupBy(s => s.ArchiveId))
{
if (await db.Archives.GetAsync(group.Key) is { } archive) await QueueAsync(ArchiveJobs.Verify(archive, [.. group.Select(s => s.Id)]));
}
}
///
/// The Render quick action: the sequence's own export with its project as stored — the preset chosen in the editor,
/// else the advisor's recommendation the analyses store in the project, else the default — on this PC's engine, or
/// posted to the server for a remote card, which renders it where the originals are.
///
public async Task RenderAsync(Sequence sequence)
{
if (sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly })
{
if (Remote() is not { } remote)
{
NotConnected();
return;
}
await PostAsync(async () =>
{
var (project, width, height) = await RemoteProjectAsync(remote, sequence.Id);
var export = project.Export with { Batch = [] };
// As the editor's Render: settings or proportions an older server would render otherwise are not posted.
if (ServerCannotRender(project, export, width, height, Services.Sync.SettingsFormat) is { } newer)
{
shell.Notify(Loc.L("Library.Post.Failed"), newer);
return null;
}
return ServerRender(sequence, project, export, width, height);
}, JobKind.Render, sequence.DisplayTitle);
return;
}
if (Services.Database is not { } db) return;
// The project as stored now: the editor may have changed it since the card was read.
var current = await db.Sequences.GetAsync(sequence.Id) ?? sequence;
var first = (await db.Frames.ListBySequenceAsync(sequence.Id, -1, 1)).FirstOrDefault();
var (w, h) = first is null ? (0, 0) : first.Orientation is >= 5 and <= 8 ? (first.Height, first.Width) : (first.Width, first.Height);
var export = Project(current.SettingsJson).Export with { Batch = [] };
await QueueAsync(ProcessingJobs.Render(current, export, w, h));
}
/// Runs one row action of the sync table on a sequence (the card's Sync, a mass Upload or Download); false when it could not start.
public async Task SyncAsync(SelectedSequence selected, SyncAction action)
{
if (Remote() is not { } remote || Services.Engine is not { } engine) return false;
var entry = selected.Sync;
switch (action)
{
case SyncAction.Upload when !selected.IsRemote:
await remote.Service.EnqueueUploadAsync(engine, remote.Server, selected.Sequence);
return true;
case SyncAction.SendExports when !selected.IsRemote:
await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence);
return true;
case SyncAction.DownloadOriginals when entry is not null:
if (await Services.Sync.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => shell.Notify(title, message, isError: isError)) is not { } archive) return false;
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
return true;
case SyncAction.GetExports when entry is not null:
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
return true;
case SyncAction.SyncSettings when entry is not null:
await remote.Service.SyncSettingsAsync(remote.Remote, entry.Id, Services.Sync.Policy, CancellationToken.None);
return true;
default:
return false;
}
}
///
/// Opens a remote card with proxies (BRIEF §14.5): at once when its proxies are cached here, otherwise after the
/// proxy download this queues. Returns that download job, or null when the editor opened (or nothing could start).
///
public async Task OpenRemoteAsync(Sequence sequence)
{
if (Remote() is not { } remote || Services.Engine is not { } engine)
{
NotConnected();
return null;
}
// The proxy cache is read off the UI thread: its manifest holds every frame.
if (await Task.Run(() => remote.Service.OpenRemote(remote.Server, sequence.Id)) is not null)
{
shell.OpenSequence(sequence.Id);
return null;
}
var job = await remote.Service.EnqueueDownloadAsync(engine, remote.Server, sequence.Id, sequence.DisplayTitle, SyncDownloadMode.Proxies, null);
Queued(JobKind.Download, sequence.DisplayTitle);
return job.Id;
}
///
/// Sets the rating of sequences on this PC (sidecar and index together), changing nothing else: the title, tags and
/// notes are those the sidecar holds then, not the Library's copy. Returns how many changed.
///
public async Task RateAsync(IReadOnlyList sequences, int rating)
{
if (Services.Archives is not { } archives || Services.Database is not { } db) return 0;
var changed = 0;
try
{
foreach (var s in sequences)
{
if (await db.Sequences.GetAsync(s.Id) is not { } current || current.Rating == rating) continue;
await Task.Run(() => archives.EditSequenceInfoAsync(s.Id, info => info with { Rating = rating }));
changed++;
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("library", "Rating failed", ex);
shell.Notify(Loc.L("Library.Rate.Failed"), ArchiveFailures.Cause(ex));
}
return changed;
}
/// "Deep analysis queued · Harbour sunset", with a way to the Jobs screen.
public void Queued(JobKind kind, string label) =>
shell.Notify(Loc.L("Library.Queued", JobText.Kind(kind), label), actionText: Loc.L("Shell.Nav.Jobs"), actionToolTip: Loc.L("Tooltips.Nav.Jobs"),
action: () => shell.Navigate(SectionKey.Jobs));
public static string Label(IReadOnlyList sequences) =>
sequences.Count == 1 ? sequences[0].DisplayTitle : Loc.Plural("Library.Selection.Count", sequences.Count);
private async Task QueueAsync(ArchiveJobRequest request)
{
if (request.Targets.Count == 0) return;
if (Services.Engine is not { } engine)
{
shell.Notify(Loc.L("Library.Blocked.NoIndex"));
return;
}
await engine.EnqueueAsync(request);
Queued(request.Kind, request.Label ?? string.Empty);
}
/// Posts a job to the signed-in server, which runs it or hands it to a render node (BRIEF §14.6, §14.7).
///
/// Why a server that reads settings up to cannot render with
/// as this Chronos would (), localised; null when it can.
///
internal static string? ServerCannotRender(ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight, int serverFormat) =>
Editor.ServerJobs.NeedsNewerServer(ProcessingJobs.RequiredFormat(project, export, sourceWidth, sourceHeight), serverFormat);
///
/// The server render of a remote card: sized on (the settings just read), which it does not
/// embed, so the server renders the sequence's settings as they are when a node takes the job (the read may come from
/// this PC's proxy cache, older than the server's).
///
internal static CreateJobRequest ServerRender(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight) =>
new(RenderKind, [sequence.Id], ProcessingJobs.Render(sequence with { SettingsJson = project.ToJson() }, export, sourceWidth, sourceHeight).ParametersJson);
/// Posts the job gives; nothing when it gives none (it said why).
private async Task PostAsync(Func> build, JobKind kind, string label)
{
var session = Services.Server;
if (!CanPost || session.Flow is not { Address: { } address, Token: { } token })
{
NotConnected();
return;
}
try
{
if (await build() is not { } request) return;
using var client = new ChronosClient(address, new CertificatePinning(session.Fingerprints), $"Chronos ({Environment.MachineName})") { Token = token };
await client.CreateJobAsync(request);
shell.Notify(Loc.L("Library.QueuedServer", JobText.Kind(kind), label));
}
// A certificate the server changed since sign-in is refused by the pin, not by the network (UntrustedCertificateException).
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
{
Log.Warning("library", $"Posting a {kind} job to {address} failed", ex);
shell.Notify(Loc.L("Library.Post.Failed"), ErrorText.ForServer(ex), isError: true);
}
}
/// A remote card's action could not start: the session ended since the card was drawn.
private void NotConnected() => shell.Notify(Loc.L("Library.Remote.Unavailable"), Loc.L("Library.Blocked.NotConnected"));
/// The project of a remote card: from its proxy cache when it was opened here, else from the server's manifest; and its frame size when cached.
private static async Task<(ProjectSettings Project, int Width, int Height)> RemoteProjectAsync(RemoteSource remote, Guid id)
{
if (await Task.Run(() => remote.Service.OpenRemote(remote.Server, id)) is { } cached)
{
var frame = cached.Frames.FirstOrDefault(f => f.Width > 0);
var size = frame is null ? (0, 0) : frame.Orientation is >= 5 and <= 8 ? (frame.Height, frame.Width) : (frame.Width, frame.Height);
return (Project(cached.Sequence.SettingsJson), size.Item1, size.Item2);
}
var manifest = await remote.Remote.GetManifestAsync(id, CancellationToken.None);
return (Project(manifest.SettingsJson), 0, 0);
}
private static ProjectSettings Project(string? json)
{
try
{
return json is null ? new ProjectSettings() : ProjectSettings.FromJson(json);
}
catch (System.Text.Json.JsonException ex)
{
Log.Warning("library", "Unreadable project settings; rendering the defaults", ex);
return new ProjectSettings();
}
}
}