diff --git a/src/c#/GeneralUpdate.Core/Configuration/BlackListConfig.cs b/src/c#/GeneralUpdate.Core/Configuration/BlackListConfig.cs new file mode 100644 index 00000000..2f5a3930 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Configuration/BlackListConfig.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; + +namespace GeneralUpdate.Core.Configuration; + +public sealed record BlackListConfig( + IReadOnlyList? BlackFiles = null, + IReadOnlyList? BlackFormats = null, + IReadOnlyList? SkipDirectorys = null +) +{ + public static BlackListConfig Empty { get; } = new(); + public bool HasRules => + (BlackFiles?.Count > 0) || (BlackFormats?.Count > 0) || (SkipDirectorys?.Count > 0); +} diff --git a/src/c#/GeneralUpdate.Core/Configuration/DiffMode.cs b/src/c#/GeneralUpdate.Core/Configuration/DiffMode.cs new file mode 100644 index 00000000..7dca9aec --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Configuration/DiffMode.cs @@ -0,0 +1,3 @@ +namespace GeneralUpdate.Core.Configuration; + +public enum DiffMode { Serial, Parallel } diff --git a/src/c#/GeneralUpdate.Core/Configuration/HubConfig.cs b/src/c#/GeneralUpdate.Core/Configuration/HubConfig.cs new file mode 100644 index 00000000..ab799556 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Configuration/HubConfig.cs @@ -0,0 +1,10 @@ +using System; + +namespace GeneralUpdate.Core.Configuration; + +public sealed class HubConfig +{ + public string Url { get; set; } = string.Empty; + public TimeSpan ReconnectDelay { get; set; } = TimeSpan.FromSeconds(5); + public int MaxReconnectAttempts { get; set; } = 10; +} diff --git a/src/c#/GeneralUpdate.Core/Download/Abstractions/IDownloadSource.cs b/src/c#/GeneralUpdate.Core/Download/Abstractions/IDownloadSource.cs new file mode 100644 index 00000000..f5a989a1 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Abstractions/IDownloadSource.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using GeneralUpdate.Core.Download.Models; + +namespace GeneralUpdate.Core.Download.Abstractions; + +/// Source of download assets (e.g. HTTP API, OSS bucket, SignalR Hub). +public interface IDownloadSource +{ + Task> ListAsync(CancellationToken token = default); +} + +/// Post-download processing pipeline (verify, decompress, decrypt). +public interface IDownloadPipeline +{ + Task ProcessAsync(string downloadedPath, CancellationToken token = default); +} diff --git a/src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs b/src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs new file mode 100644 index 00000000..acb67bf8 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; + +namespace GeneralUpdate.Core.Download.Abstractions; + +/// Server-side packet descriptor DTO (mirrors server contract). +public record PacketDTO +{ + public string? Name { get; set; } + public string? Hash { get; set; } + public DateTime? ReleaseDate { get; set; } + public string? Url { get; set; } + public string? Version { get; set; } + public int? AppType { get; set; } + public int? Platform { get; set; } + public string? ProductId { get; set; } + public bool? IsForcibly { get; set; } + public bool? IsFreeze { get; set; } + public string? Format { get; set; } + public long? Size { get; set; } + public string? FromVersion { get; set; } + public bool? IsCrossVersion { get; set; } + public string? MinClientVersion { get; set; } + public string? SourceArchiveHash { get; set; } + public string? TargetArchiveHash { get; set; } +} + +public record VersionRequest( + string AppName, + string ClientVersion, + string? UpgradeClientVersion, + int? Platform, + string? ProductId +); + +public record VersionResponse( + bool HasUpdate, + IReadOnlyList? Packets +); diff --git a/src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs b/src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs new file mode 100644 index 00000000..8119e84d --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using GeneralUpdate.Core.Download.Abstractions; +using GeneralUpdate.Core.Download.Models; + +namespace GeneralUpdate.Core.Download.Executors; + +/// OSS-based download executor. Delegates to HTTP GET for OSS signed URLs. +public class OssDownloadExecutor : IDownloadExecutor +{ + private readonly HttpClient _client; + + public OssDownloadExecutor(HttpClient client) + => _client = client ?? throw new ArgumentNullException(nameof(client)); + + public async Task ExecuteAsync( + string url, string destPath, + IProgress? progress = null, + CancellationToken token = default) + { + var sw = System.Diagnostics.Stopwatch.StartNew(); + long lastReport = 0; + try + { + using var response = await _client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token) + .ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + var total = response.Content.Headers.ContentLength ?? -1; + Directory.CreateDirectory(Path.GetDirectoryName(destPath)!); + using var fs = new FileStream(destPath, FileMode.Create); + using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + var buffer = new byte[8192]; + long downloaded = 0; + int read; + while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0) + { + await fs.WriteAsync(buffer, 0, read, token).ConfigureAwait(false); + downloaded += read; + var now = sw.ElapsedMilliseconds; + if (now - lastReport >= 250 || downloaded == total) + { + lastReport = now; + var pct = total > 0 ? (double)downloaded / total * 100 : -1; + progress?.Report(new DownloadProgress( + Path.GetFileName(destPath), downloaded, total > 0 ? total : null, pct, DownloadStatus.Downloading)); + } + } + sw.Stop(); + progress?.Report(new DownloadProgress(Path.GetFileName(destPath), downloaded, total > 0 ? total : null, 100, DownloadStatus.Completed)); + return new DownloadResult(url, destPath, downloaded, sw.Elapsed, 0, true, null); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + sw.Stop(); + return new DownloadResult(url, null, 0, sw.Elapsed, 0, false, ex.Message); + } + } +} diff --git a/src/c#/GeneralUpdate.Core/Download/Models/DownloadAsset.cs b/src/c#/GeneralUpdate.Core/Download/Models/DownloadAsset.cs new file mode 100644 index 00000000..b14ee548 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Models/DownloadAsset.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +namespace GeneralUpdate.Core.Download.Models; + +/// Download resource descriptor — maps from server PacketDTO. +public record DownloadAsset( + string Name, + string Url, + long Size, + string? SHA256, + string Version, + DownloadPriority Priority = DownloadPriority.Normal, + bool IsCrossVersion = false, + string? FromVersion = null, + string? MinClientVersion = null, + string? SourceArchiveHash = null, + string? TargetArchiveHash = null, + bool IsForcibly = false, + bool IsFreeze = false +); + +/// Ordered download plan built from server response. +public record DownloadPlan(IReadOnlyList Assets, bool IsForcibly) +{ + public static DownloadPlan Empty { get; } = new(new List(), false); + public bool HasAssets => Assets.Count > 0; +} diff --git a/src/c#/GeneralUpdate.Core/Download/Pipeline/DefaultDownloadPipeline.cs b/src/c#/GeneralUpdate.Core/Download/Pipeline/DefaultDownloadPipeline.cs new file mode 100644 index 00000000..de5610d8 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Pipeline/DefaultDownloadPipeline.cs @@ -0,0 +1,36 @@ +using System.IO; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; +using GeneralUpdate.Core.Download.Abstractions; + +namespace GeneralUpdate.Core.Download.Pipeline; + +/// Default download pipeline: SHA256 verify the downloaded file. +public class DefaultDownloadPipeline : IDownloadPipeline +{ + private readonly string? _expectedHash; + + public DefaultDownloadPipeline(string? expectedHash = null) + => _expectedHash = expectedHash; + + public async Task ProcessAsync(string downloadedPath, CancellationToken token = default) + { + if (!string.IsNullOrEmpty(_expectedHash)) + { + var actual = await ComputeSha256Async(downloadedPath, token).ConfigureAwait(false); + if (!string.Equals(actual, _expectedHash, System.StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException( + $"SHA256 mismatch for {downloadedPath}: expected {_expectedHash}, got {actual}"); + } + return downloadedPath; + } + + private static async Task ComputeSha256Async(string path, CancellationToken token) + { + using var sha = SHA256.Create(); + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + var hash = await Task.Run(() => sha.ComputeHash(fs), token).ConfigureAwait(false); + return System.BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); + } +} diff --git a/src/c#/GeneralUpdate.Core/Download/Progress/DownloadProgressReporter.cs b/src/c#/GeneralUpdate.Core/Download/Progress/DownloadProgressReporter.cs new file mode 100644 index 00000000..8ffb65eb --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Progress/DownloadProgressReporter.cs @@ -0,0 +1,33 @@ +using System; +using IProgress = System.IProgress; + +namespace GeneralUpdate.Core.Download.Progress; + +/// Bridges IProgress to event-based callbacks for download status. +public class DownloadProgressReporter : IProgress +{ + private readonly Action? _onProgress; + private readonly Action? _onCompleted; + private readonly Action? _onAllCompleted; + + public DownloadProgressReporter( + Action? onProgress = null, + Action? onCompleted = null, + Action? onAllCompleted = null) + { + _onProgress = onProgress; + _onCompleted = onCompleted; + _onAllCompleted = onAllCompleted; + } + + public void Report(Download.Models.DownloadProgress value) + { + _onProgress?.Invoke(value); + if (value.Status == Download.Models.DownloadStatus.Completed) + { + _onCompleted?.Invoke(); + if (value.Percentage >= 100) + _onAllCompleted?.Invoke(); + } + } +} diff --git a/src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs b/src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs new file mode 100644 index 00000000..8d3d7436 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using GeneralUpdate.Core; +using GeneralUpdate.Core.Event; +using GeneralUpdate.Core.Pipeline; + +namespace GeneralUpdate.Core.Strategy; + +/// macOS update strategy — follows Linux conventions. +public class MacStrategy : AbstractStrategy +{ + public override void Execute() + { + GeneralTracer.Info("MacStrategy: executing macOS update"); + try + { + if (!string.IsNullOrEmpty(_configinfo.MainAppName)) + { + var mainApp = Path.Combine( + _configinfo.InstallPath ?? string.Empty, + _configinfo.MainAppName); + if (File.Exists(mainApp)) + StartApp(); + } + } + catch (Exception ex) + { + GeneralTracer.Error("MacStrategy.Execute failed", ex); + EventManager.Instance.Dispatch(this, new ExceptionEventArgs(ex, ex.Message)); + } + } + + public override async Task ExecuteAsync() + { + GeneralTracer.Info("MacStrategy: executing pipeline"); + await base.ExecuteAsync().ConfigureAwait(false); + } + + public override void StartApp() + { + var mainApp = Path.Combine( + _configinfo.InstallPath ?? string.Empty, + _configinfo.MainAppName ?? string.Empty); + + if (!string.IsNullOrEmpty(_configinfo.MainAppName) && File.Exists(mainApp)) + { + GeneralTracer.Info($"MacStrategy: starting {mainApp}"); + System.Diagnostics.Process.Start(mainApp); + } + } + + public override void Create(GlobalConfigInfo configInfo) => _configinfo = configInfo; + + protected override PipelineBuilder BuildPipeline(PipelineContext context) + { + var builder = new PipelineBuilder(context); + builder.Use(new HashMiddleware()); + builder.Use(new CompressMiddleware()); + builder.Use(new PatchMiddleware()); + return builder; + } +}