using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Repositories;
namespace Chronos.Data.Archiving.Jobs;
/// Resolves the archive a job targets (its first target id).
internal static class JobArchive
{
public static async Task LoadAsync(ChronosDatabase db, Job job, CancellationToken cancellationToken) =>
job.TargetIds.Count > 0 && await db.Archives.GetAsync(job.TargetIds[0], cancellationToken).ConfigureAwait(false) is { } archive
? archive
: throw new InvalidOperationException($"{job.Kind} job {job.Id} does not target a known archive.");
}
///
/// (incremental, or full with ) and
/// . Checkpoint: after:<folder>, the last folder indexed. When anything was
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
/// queued for it, and for a background deep analysis too when asks. On the
/// server (, ) the sequences it indexed
/// without thumbnails or proxies are queued for them too, one pass per sequence as after an upload. Sequences waiting for
/// their first frame () have nothing to analyse or draw yet and are left out.
///
internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, JobKind kind, bool imagesAfterScan = false) : IJobHandler
{
private const string Prefix = "after:";
public JobKind Kind => kind;
public async Task RunAsync(JobContext context)
{
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ScanParameters, new ScanParameters(false));
var mode = kind == JobKind.Rebuild ? ScanMode.Rebuild : parameters.Full ? ScanMode.Full : ScanMode.Incremental;
var resume = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) ? checkpoint[Prefix.Length..] : null;
var summary = await indexer.ScanAsync(archive, mode, resume, async p =>
{
if (p.Changed) await context.CheckpointAsync(Prefix + p.Folder, p.FoldersDone, p.FoldersTotal).ConfigureAwait(false);
else await context.ReportAsync(p.FoldersDone, p.FoldersTotal, p.Folder).ConfigureAwait(false);
}, context.Cancellation).ConfigureAwait(false);
foreach (var (folder, error) in summary.Failed) context.Log(Loc.L("Archive.Log.FolderFailed", folder, error));
context.Log(Loc.L("Archive.Log.ScanDone", summary.Folders, summary.Indexed, summary.Adopted, summary.Removed));
// A resumed scan may have indexed its folders before the interruption.
if (summary.Indexed > 0 || resume is not null)
{
var awaiting = await indexer.AwaitingFolderAsync(new ArchivePaths(archive.RootPath),
await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation).ConfigureAwait(false), context.Cancellation).ConfigureAwait(false);
var unanalysed = (await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false))
.Where(id => !awaiting.Contains(id)).ToList();
await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false);
if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false);
if (imagesAfterScan)
{
var resumed = resume is not null;
await QueueImagesAsync(context, archive, JobKind.Thumbs, SequenceStatus.ThumbsBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
// An archive whose policy makes no proxies would get a pass that does nothing.
if (archive.ProxyLongEdge != ProxyPolicy.Disabled)
await QueueImagesAsync(context, archive, JobKind.Proxies, SequenceStatus.ProxiesBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
}
}
}
///
/// Queues a background (thumbnails or proxies) of each sequence this run indexed whose
/// flag is clear: new and adopted sequences, and those whose photos changed (the scan clears the
/// flag then, in this server's own row when another writer listed them in the sidecar itself). After a resumed run,
/// which may have indexed sequences before the interruption, of every sequence of the archive without the flag but
/// those in . One pass per sequence, as after an upload: a folder renamed, deleted or
/// damaged before its pass runs fails that pass alone, and the other sequences still get their images. A sequence
/// whose own pass of that kind is already queued is left out.
///
private async Task QueueImagesAsync(JobContext context, Archive archive, JobKind pass, SequenceStatus built, IReadOnlyList indexed,
bool resumed, IReadOnlySet awaiting)
{
var missing = new Dictionary();
var query = new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = built, Sort = SequenceSort.Oldest, Limit = 1000 };
do
{
var page = await db.Sequences.ListAsync(query, context.Cancellation).ConfigureAwait(false);
foreach (var sequence in page.Items) missing[sequence.Id] = sequence;
query = query with { Cursor = page.NextCursor };
}
while (query.Cursor is not null);
var targets = resumed ? missing.Values.ToList() : indexed.Distinct().Where(missing.ContainsKey).Select(id => missing[id]).ToList();
foreach (var sequence in targets)
{
if (awaiting.Contains(sequence.Id) || await db.Jobs.IsQueuedAsync(pass, sequence.Id, context.Cancellation).ConfigureAwait(false)) continue;
var request = pass == JobKind.Thumbs
? ArchiveJobs.Thumbnails([sequence.Id], sequence.DisplayTitle)
: ArchiveJobs.Proxies([sequence.Id], sequence.DisplayTitle);
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
}
}