From cf37e6455127dd1c053e8b8b9947e12c0e5f8e36 Mon Sep 17 00:00:00 2001 From: JusterZhu Date: Sun, 24 May 2026 08:31:57 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20add=20missing=20types=20from=20refa?= =?UTF-8?q?ctor=20plan=20=E2=80=94=20DiffMode,=20BlackListConfig,=20Downlo?= =?UTF-8?q?adAsset,=20PacketDTO,=20MacStrategy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DiffMode enum (Serial/Parallel) - HubConfig (Url, ReconnectDelay, MaxReconnectAttempts) - BlackListConfig record (BlackFiles/BlackFormats/SkipDirectorys + Empty) - DownloadAsset + DownloadPlan records (with cross-version fields) - IDownloadSource + IDownloadPipeline interfaces - PacketDTO + VersionRequest + VersionResponse server contracts - DefaultDownloadPipeline (SHA256 verify) - DownloadProgressReporter (IProgress to event bridge) - OssDownloadExecutor (OSS HTTP download) - MacStrategy (macOS update strategy) Closes #334 --- .../Configuration/BlackListConfig.cs | 14 +++++ .../Configuration/DiffMode.cs | 3 ++ .../Configuration/HubConfig.cs | 10 ++++ .../Download/Abstractions/IDownloadSource.cs | 18 +++++++ .../Download/Abstractions/PacketDTO.cs | 41 ++++++++++++++ .../Download/Executors/OssDownloadExecutor.cs | 53 +++++++++++++++++++ .../Download/Models/DownloadAsset.cs | 27 ++++++++++ .../Pipeline/DefaultDownloadPipeline.cs | 36 +++++++++++++ .../Progress/DownloadProgressReporter.cs | 29 ++++++++++ .../Strategy/MacStrategy.cs | 28 ++++++++++ 10 files changed, 259 insertions(+) create mode 100644 src/c#/GeneralUpdate.Core/Configuration/BlackListConfig.cs create mode 100644 src/c#/GeneralUpdate.Core/Configuration/DiffMode.cs create mode 100644 src/c#/GeneralUpdate.Core/Configuration/HubConfig.cs create mode 100644 src/c#/GeneralUpdate.Core/Download/Abstractions/IDownloadSource.cs create mode 100644 src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs create mode 100644 src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs create mode 100644 src/c#/GeneralUpdate.Core/Download/Models/DownloadAsset.cs create mode 100644 src/c#/GeneralUpdate.Core/Download/Pipeline/DefaultDownloadPipeline.cs create mode 100644 src/c#/GeneralUpdate.Core/Download/Progress/DownloadProgressReporter.cs create mode 100644 src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs 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..b7bb2103 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +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..3a317311 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs @@ -0,0 +1,53 @@ +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(); + try + { + using var response = await _client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); + response.EnsureSuccessStatusCode(); + var total = response.Content.Headers.ContentLength ?? -1; + using var fs = new FileStream(destPath, FileMode.Create); + using var stream = await response.Content.ReadAsStreamAsync(); + var buffer = new byte[8192]; + long downloaded = 0; + int read; + while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, token)) > 0) + { + await fs.WriteAsync(buffer, 0, read, token); + downloaded += read; + 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..750ade2d --- /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); + 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..c215c94d --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Download/Progress/DownloadProgressReporter.cs @@ -0,0 +1,29 @@ +using System; +using GeneralUpdate.Core.Download.Models; + +namespace GeneralUpdate.Core.Download.Progress; + +/// Bridges IProgress to event-based listeners. +public class DownloadProgressReporter : IProgress +{ + private readonly Action? _onProgress; + private readonly Action? _onCompleted; + private readonly Action? _onError; + + public DownloadProgressReporter( + Action? onProgress = null, + Action? onCompleted = null, + Action? onError = null) + { + _onProgress = onProgress; + _onCompleted = onCompleted; + _onError = onError; + } + + public void Report(DownloadProgress value) + { + _onProgress?.Invoke(value); + if (value.Status == DownloadStatus.Completed) + _onCompleted?.Invoke(null!); // result will be set by caller + } +} diff --git a/src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs b/src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs new file mode 100644 index 00000000..0c405cbf --- /dev/null +++ b/src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs @@ -0,0 +1,28 @@ +using System.Diagnostics; +using System.IO; +using GeneralUpdate.Core; +using GeneralUpdate.Core.Pipeline; + +namespace GeneralUpdate.Core.Strategy; + +/// macOS update strategy — follows Linux conventions for file operations. +public class MacStrategy : AbstractStrategy +{ + public override void Execute() + { + GeneralTracer.Info("MacStrategy: executing macOS update"); + StartApp(); + } + + public override void StartApp() + { + var mainApp = Path.Combine(_configinfo.InstallPath, _configinfo.MainAppName); + if (File.Exists(mainApp)) + { + GeneralTracer.Info($"MacStrategy: starting {mainApp}"); + Process.Start(mainApp); + } + } + + public override void Create(GlobalConfigInfo configInfo) => _configinfo = configInfo; +} From 85c85e44d7a465fef0a1a4487458e1db288faca0 Mon Sep 17 00:00:00 2001 From: JusterZhu Date: Sun, 24 May 2026 08:52:48 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20apply=20Copilot=20fixes=20=E2=80=94?= =?UTF-8?q?=20PacketDTO,=20MacStrategy,=20DownloadProgressReporter,=20etc.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PacketDTO: nullable Size, remove unused usings - DownloadProgressReporter: remove null!, safer callback design - DefaultDownloadPipeline: FileShare.Read - OssDownloadExecutor: throttling + ConfigureAwait + create dest dir - MacStrategy: BuildPipeline + error handling --- .../Download/Abstractions/PacketDTO.cs | 4 +- .../Download/Executors/OssDownloadExecutor.cs | 22 ++++++--- .../Pipeline/DefaultDownloadPipeline.cs | 2 +- .../Progress/DownloadProgressReporter.cs | 30 +++++++----- .../Strategy/MacStrategy.cs | 47 ++++++++++++++++--- 5 files changed, 75 insertions(+), 30 deletions(-) diff --git a/src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs b/src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs index b7bb2103..acb67bf8 100644 --- a/src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs +++ b/src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; namespace GeneralUpdate.Core.Download.Abstractions; @@ -19,7 +17,7 @@ public record PacketDTO public bool? IsForcibly { get; set; } public bool? IsFreeze { get; set; } public string? Format { get; set; } - public long Size { get; set; } + public long? Size { get; set; } public string? FromVersion { get; set; } public bool? IsCrossVersion { get; set; } public string? MinClientVersion { get; set; } diff --git a/src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs b/src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs index 3a317311..8119e84d 100644 --- a/src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs +++ b/src/c#/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs @@ -22,23 +22,31 @@ public async Task ExecuteAsync( CancellationToken token = default) { var sw = System.Diagnostics.Stopwatch.StartNew(); + long lastReport = 0; try { - using var response = await _client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); + 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(); + 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)) > 0) + while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0) { - await fs.WriteAsync(buffer, 0, read, token); + await fs.WriteAsync(buffer, 0, read, token).ConfigureAwait(false); downloaded += read; - var pct = total > 0 ? (double)downloaded / total * 100 : -1; - progress?.Report(new DownloadProgress( - Path.GetFileName(destPath), downloaded, total > 0 ? total : null, pct, DownloadStatus.Downloading)); + 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)); diff --git a/src/c#/GeneralUpdate.Core/Download/Pipeline/DefaultDownloadPipeline.cs b/src/c#/GeneralUpdate.Core/Download/Pipeline/DefaultDownloadPipeline.cs index 750ade2d..de5610d8 100644 --- a/src/c#/GeneralUpdate.Core/Download/Pipeline/DefaultDownloadPipeline.cs +++ b/src/c#/GeneralUpdate.Core/Download/Pipeline/DefaultDownloadPipeline.cs @@ -29,7 +29,7 @@ public async Task ProcessAsync(string downloadedPath, CancellationToken private static async Task ComputeSha256Async(string path, CancellationToken token) { using var sha = SHA256.Create(); - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read); + 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 index c215c94d..8ffb65eb 100644 --- a/src/c#/GeneralUpdate.Core/Download/Progress/DownloadProgressReporter.cs +++ b/src/c#/GeneralUpdate.Core/Download/Progress/DownloadProgressReporter.cs @@ -1,29 +1,33 @@ using System; -using GeneralUpdate.Core.Download.Models; +using IProgress = System.IProgress; namespace GeneralUpdate.Core.Download.Progress; -/// Bridges IProgress to event-based listeners. -public class DownloadProgressReporter : IProgress +/// Bridges IProgress to event-based callbacks for download status. +public class DownloadProgressReporter : IProgress { - private readonly Action? _onProgress; - private readonly Action? _onCompleted; - private readonly Action? _onError; + private readonly Action? _onProgress; + private readonly Action? _onCompleted; + private readonly Action? _onAllCompleted; public DownloadProgressReporter( - Action? onProgress = null, - Action? onCompleted = null, - Action? onError = null) + Action? onProgress = null, + Action? onCompleted = null, + Action? onAllCompleted = null) { _onProgress = onProgress; _onCompleted = onCompleted; - _onError = onError; + _onAllCompleted = onAllCompleted; } - public void Report(DownloadProgress value) + public void Report(Download.Models.DownloadProgress value) { _onProgress?.Invoke(value); - if (value.Status == DownloadStatus.Completed) - _onCompleted?.Invoke(null!); // result will be set by caller + 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 index 0c405cbf..8d3d7436 100644 --- a/src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs +++ b/src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs @@ -1,28 +1,63 @@ -using System.Diagnostics; +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 for file operations. +/// macOS update strategy — follows Linux conventions. public class MacStrategy : AbstractStrategy { public override void Execute() { GeneralTracer.Info("MacStrategy: executing macOS update"); - StartApp(); + 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, _configinfo.MainAppName); - if (File.Exists(mainApp)) + 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}"); - Process.Start(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; + } }