using System.Text.Json; using System.Text.Json.Serialization; using Titano.Core.Localization; using Titano.Core.Model; using Titano.Data.Jobs; namespace Titano.Data.Sync; /// /// Parameters of upload and download jobs. The job's target is the local sequence for an upload and the server /// sequence for a download. /// /// Archive that receives downloaded originals when the sequence has no local copy yet. internal sealed record SyncJobParameters(string Server, SyncDownloadMode? Mode = null, Guid? ArchiveId = null); [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(SyncJobParameters))] internal sealed partial class SyncJobJson : JsonSerializerContext; /// Runs upload and download jobs with a connection to their server; the job fails with a reason when this PC is not connected to it. internal sealed class SyncJobHandler(JobKind kind, SyncTransfers transfers, ISyncConnector connector) : IJobHandler { public JobKind Kind => kind; public async Task RunAsync(JobContext context) { var parameters = (context.Job.ParametersJson is { } json ? JsonSerializer.Deserialize(json, SyncJobJson.Default.SyncJobParameters) : null) ?? throw new InvalidDataException("The job has no sync parameters."); if (context.Job.TargetIds is not [var target, ..]) throw new InvalidDataException("The job has no target sequence."); using var remote = await connector.ConnectAsync(parameters.Server, context.Cancellation).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected")); switch (kind, parameters.Mode) { case (JobKind.UploadCommit, _): await transfers.UploadAsync(context, remote, target).ConfigureAwait(false); break; case (JobKind.Download, SyncDownloadMode.Proxies): await transfers.DownloadProxiesAsync(context, remote, target).ConfigureAwait(false); break; default: await transfers.DownloadOriginalsAsync(context, remote, target, parameters.ArchiveId).ConfigureAwait(false); break; } } }