Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/c#/GeneralUpdate.Core/Configuration/BlackListConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Collections.Generic;

namespace GeneralUpdate.Core.Configuration;

public sealed record BlackListConfig(
IReadOnlyList<string>? BlackFiles = null,
IReadOnlyList<string>? BlackFormats = null,
IReadOnlyList<string>? SkipDirectorys = null
)
{
public static BlackListConfig Empty { get; } = new();
public bool HasRules =>
(BlackFiles?.Count > 0) || (BlackFormats?.Count > 0) || (SkipDirectorys?.Count > 0);
}
3 changes: 3 additions & 0 deletions src/c#/GeneralUpdate.Core/Configuration/DiffMode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace GeneralUpdate.Core.Configuration;

public enum DiffMode { Serial, Parallel }
10 changes: 10 additions & 0 deletions src/c#/GeneralUpdate.Core/Configuration/HubConfig.cs
Original file line number Diff line number Diff line change
@@ -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;
}
18 changes: 18 additions & 0 deletions src/c#/GeneralUpdate.Core/Download/Abstractions/IDownloadSource.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>Source of download assets (e.g. HTTP API, OSS bucket, SignalR Hub).</summary>
public interface IDownloadSource
{
Task<IReadOnlyList<DownloadAsset>> ListAsync(CancellationToken token = default);
}

/// <summary>Post-download processing pipeline (verify, decompress, decrypt).</summary>
public interface IDownloadPipeline
{
Task<string> ProcessAsync(string downloadedPath, CancellationToken token = default);
}
39 changes: 39 additions & 0 deletions src/c#/GeneralUpdate.Core/Download/Abstractions/PacketDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;

namespace GeneralUpdate.Core.Download.Abstractions;

/// <summary>Server-side packet descriptor DTO (mirrors server contract).</summary>
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; }
Comment on lines +19 to +25
}

public record VersionRequest(
string AppName,
string ClientVersion,
string? UpgradeClientVersion,
int? Platform,
string? ProductId
);

public record VersionResponse(
bool HasUpdate,
IReadOnlyList<PacketDTO>? Packets
);
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>OSS-based download executor. Delegates to HTTP GET for OSS signed URLs.</summary>
public class OssDownloadExecutor : IDownloadExecutor
{
private readonly HttpClient _client;

public OssDownloadExecutor(HttpClient client)
=> _client = client ?? throw new ArgumentNullException(nameof(client));

public async Task<DownloadResult> ExecuteAsync(
string url, string destPath,
IProgress<DownloadProgress>? 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);
}
}
}
27 changes: 27 additions & 0 deletions src/c#/GeneralUpdate.Core/Download/Models/DownloadAsset.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System.Collections.Generic;

namespace GeneralUpdate.Core.Download.Models;

/// <summary>Download resource descriptor — maps from server PacketDTO.</summary>
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
);

/// <summary>Ordered download plan built from server response.</summary>
public record DownloadPlan(IReadOnlyList<DownloadAsset> Assets, bool IsForcibly)
{
public static DownloadPlan Empty { get; } = new(new List<DownloadAsset>(), false);
public bool HasAssets => Assets.Count > 0;
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>Default download pipeline: SHA256 verify the downloaded file.</summary>
public class DefaultDownloadPipeline : IDownloadPipeline
{
private readonly string? _expectedHash;

public DefaultDownloadPipeline(string? expectedHash = null)
=> _expectedHash = expectedHash;

public async Task<string> 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<string> 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();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;
using IProgress = System.IProgress<GeneralUpdate.Core.Download.Models.DownloadProgress>;

namespace GeneralUpdate.Core.Download.Progress;

/// <summary>Bridges IProgress to event-based callbacks for download status.</summary>
public class DownloadProgressReporter : IProgress
{
private readonly Action<Download.Models.DownloadProgress>? _onProgress;
private readonly Action? _onCompleted;
private readonly Action? _onAllCompleted;

public DownloadProgressReporter(
Action<Download.Models.DownloadProgress>? 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();
}
}
}
63 changes: 63 additions & 0 deletions src/c#/GeneralUpdate.Core/Strategy/MacStrategy.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>macOS update strategy — follows Linux conventions.</summary>
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;
}
}