-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathGeneralUpdateBootstrap.cs
More file actions
352 lines (304 loc) · 14.9 KB
/
Copy pathGeneralUpdateBootstrap.cs
File metadata and controls
352 lines (304 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using GeneralUpdate.Core.FileSystem;
using GeneralUpdate.Core.Download;
using GeneralUpdate.Core.Event;
using GeneralUpdate.Core.Configuration;
using GeneralUpdate.Core.JsonContext;
using GeneralUpdate.Core.Strategy;
using GeneralUpdate.Core.Network;
using GeneralUpdate.Core.Hooks;
using GeneralUpdate.Core.Download.Reporting;
namespace GeneralUpdate.Core;
/// <summary>
/// Unified update bootstrap — single entry point for Client, Upgrade, and OSS roles.
/// Use <see cref="AppType"/> to select the workflow:
/// <list type="bullet">
/// <item><see cref="AppType.ClientApp"/> — validate versions, download, start upgrade process</item>
/// <item><see cref="AppType.UpgradeApp"/> — receive ProcessInfo, apply updates, start main app</item>
/// <item><see cref="AppType.OSSApp"/> — OSS-based cloud storage update</item>
/// </list>
/// </summary>
/// <remarks>
/// For Client mode, use <c>Option(UpdateOptions.AppType, AppType.ClientApp)</c>.
/// </remarks>
public class GeneralUpdateBootstrap : AbstractBootstrap<GeneralUpdateBootstrap, IStrategy>
{
private GlobalConfigInfo _configInfo = new();
private Func<bool>? _customSkipOption;
private Func<UpdateInfoEventArgs, bool>? _updatePrecheck;
private readonly List<Func<bool>> _customOptions = new();
public GeneralUpdateBootstrap()
{
InitializeFromEnvironment();
}
// ════════════════════════════════════════════════════════════════
// Launch — AppType dispatch via role strategies
// ════════════════════════════════════════════════════════════════
public override async Task<GeneralUpdateBootstrap> LaunchAsync()
{
int appType = GetOption(UpdateOptions.AppType);
return appType switch
{
AppType.ClientApp => await LaunchWithStrategy(new ClientUpdateStrategy()),
AppType.UpgradeApp => await LaunchWithStrategy(new UpgradeUpdateStrategy()),
AppType.OSSApp => await LaunchOssAsync(),
_ => await LaunchWithStrategy(new ClientUpdateStrategy())
};
}
private async Task<GeneralUpdateBootstrap> LaunchWithStrategy(IStrategy roleStrategy)
{
try
{
ApplyRuntimeOptions();
// Resolve hooks and reporter from extensions
var hooks = ResolveExtension<Hooks.IUpdateHooks>() ?? new Hooks.NoOpUpdateHooks();
var reporter = ResolveExtension<Download.Reporting.IUpdateReporter>() ?? new Download.Reporting.NoOpUpdateReporter();
// Configure client-specific callbacks
if (roleStrategy is ClientUpdateStrategy clientStrat)
{
clientStrat.Hooks = hooks;
clientStrat.Reporter = reporter;
if (_updatePrecheck != null)
clientStrat.UseUpdatePrecheck(_updatePrecheck);
foreach (var opt in _customOptions)
clientStrat.UseCustomOption(opt);
await CallSmallBowlHomeAsync(_configInfo.Bowl).ConfigureAwait(false);
}
else if (roleStrategy is UpgradeUpdateStrategy upgradeStrat)
{
upgradeStrat.Hooks = hooks;
upgradeStrat.Reporter = reporter;
}
else if (roleStrategy is OSSUpdateStrategy ossStrat)
{
ossStrat.Hooks = hooks;
ossStrat.Reporter = reporter;
}
roleStrategy.Create(_configInfo);
await roleStrategy.ExecuteAsync();
}
catch (Exception ex)
{
GeneralTracer.Error("LaunchWithStrategy failed.", ex);
EventManager.Instance.Dispatch(this, new ExceptionEventArgs(ex, ex.Message));
}
return this;
}
/// <summary>OSS workflow: download packages from cloud storage, apply updates.</summary>
private async Task<GeneralUpdateBootstrap> LaunchOssAsync()
{
try
{
GeneralTracer.Debug("LaunchOssAsync start.");
var json = Environments.GetEnvironmentVariable("GlobalConfigInfoOSS");
if (!string.IsNullOrWhiteSpace(json))
{
var strategy = new OSSUpdateStrategy();
strategy.Create(_configInfo);
await strategy.ExecuteAsync();
return this;
}
// Client-side OSS
var basePath = AppDomain.CurrentDomain.BaseDirectory;
var versionFileName = $"{_configInfo.MainAppName ?? _configInfo.AppName}_versions.json";
var versionsFilePath = Path.Combine(basePath, versionFileName);
DownloadOssFile(_configInfo.UpdateUrl, versionsFilePath);
if (!File.Exists(versionsFilePath)) return this;
var versions = StorageManager.GetJson<List<VersionOSS>>(versionsFilePath,
VersionOSSJsonContext.Default.ListVersionOSS);
if (versions == null || versions.Count == 0) return this;
versions = versions.OrderByDescending(x => x.PubTime).ToList();
var newVersion = versions.First();
if (!IsOssUpgrade(_configInfo.ClientVersion, newVersion.Version))
{
GeneralTracer.Info("LaunchOssAsync: no upgrade needed.");
return this;
}
var upgradeAppName = "GeneralUpdate.Upgrade.exe";
var appPath = Path.Combine(basePath, upgradeAppName);
if (!File.Exists(appPath))
throw new Exception($"Upgrade application not found: {upgradeAppName}");
var ossConfig = new GlobalConfigInfoOSS
{
AppName = _configInfo.MainAppName ?? _configInfo.AppName,
CurrentVersion = _configInfo.ClientVersion,
VersionFileName = versionFileName,
Encoding = (_configInfo.Encoding?.CodePage ?? Encoding.UTF8.CodePage).ToString(),
Url = _configInfo.UpdateUrl
};
var serialized = JsonSerializer.Serialize(ossConfig,
GlobalConfigInfoOSSJsonContext.Default.GlobalConfigInfoOSS);
Environments.SetEnvironmentVariable("GlobalConfigInfoOSS", serialized);
Process.Start(appPath);
await GracefulExit.CurrentProcessAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
GeneralTracer.Error("LaunchOssAsync failed.", ex);
EventManager.Instance.Dispatch(this, new ExceptionEventArgs(ex, ex.Message));
}
return this;
}
// ════════════════════════════════════════════════════════════════
// Configuration
// ════════════════════════════════════════════════════════════════
public GeneralUpdateBootstrap SetConfig(Configinfo configInfo)
{
_configInfo = ConfigurationMapper.MapToGlobalConfigInfo(configInfo);
var appType = GetOption(UpdateOptions.AppType);
if (appType != AppType.UpgradeApp)
{
_configInfo.TempPath = StorageManager.GetTempDirectory("upgrade_temp");
InitBlackList();
}
return this;
}
public GeneralUpdateBootstrap SetCustomSkipOption(Func<bool>? func)
{
_customSkipOption = func;
return this;
}
public GeneralUpdateBootstrap AddListenerUpdatePrecheck(Func<UpdateInfoEventArgs, bool> func)
{
_updatePrecheck = func ?? throw new ArgumentNullException(nameof(func));
return this;
}
public GeneralUpdateBootstrap AddCustomOption(List<Func<bool>> funcList)
{
Debug.Assert(funcList != null && funcList.Any());
_customOptions.AddRange(funcList);
return this;
}
// ════════════════════════════════════════════════════════════════
// Helpers
// ════════════════════════════════════════════════════════════════
private void InitializeFromEnvironment()
{
var json = Environments.GetEnvironmentVariable("ProcessInfo");
if (string.IsNullOrWhiteSpace(json)) return;
var processInfo = JsonSerializer.Deserialize(
json, ProcessInfoJsonContext.Default.ProcessInfo);
if (processInfo == null) return;
BlackListManager.Instance.AddBlackFormats(processInfo.BlackFileFormats);
BlackListManager.Instance.AddBlackFiles(processInfo.BlackFiles);
BlackListManager.Instance.AddSkipDirectorys(processInfo.SkipDirectorys);
_configInfo = new GlobalConfigInfo
{
MainAppName = processInfo.AppName,
InstallPath = processInfo.InstallPath,
ClientVersion = processInfo.CurrentVersion,
LastVersion = processInfo.LastVersion,
UpdateLogUrl = processInfo.UpdateLogUrl,
Encoding = Encoding.GetEncoding(processInfo.CompressEncoding),
Format = processInfo.CompressFormat,
DownloadTimeOut = processInfo.DownloadTimeOut,
AppSecretKey = processInfo.AppSecretKey,
UpdateVersions = processInfo.UpdateVersions,
TempPath = StorageManager.GetTempDirectory("upgrade_temp"),
ReportUrl = processInfo.ReportUrl,
BackupDirectory = processInfo.BackupDirectory,
Scheme = processInfo.Scheme,
Token = processInfo.Token,
Script = processInfo.Script,
DriverDirectory = processInfo.DriverDirectory
};
}
private void ApplyRuntimeOptions()
{
_configInfo.Encoding = GetOption(UpdateOptions.Encoding);
_configInfo.Format = GetOption(UpdateOptions.Format);
_configInfo.DownloadTimeOut = GetOption(UpdateOptions.DownloadTimeout) ?? 60;
}
private void InitBlackList()
{
BlackListManager.Instance.AddBlackFiles(_configInfo.BlackFiles);
BlackListManager.Instance.AddBlackFormats(_configInfo.BlackFormats);
BlackListManager.Instance.AddSkipDirectorys(_configInfo.SkipDirectorys);
}
private async Task CallSmallBowlHomeAsync(string processName)
{
if (string.IsNullOrWhiteSpace(processName)) return;
try
{
var processes = Process.GetProcessesByName(processName);
foreach (var process in processes)
{
GeneralTracer.Info($"Shutting down process {process.ProcessName} (ID: {process.Id})");
await GracefulExit.ShutdownAsync(process).ConfigureAwait(false);
}
}
catch (Exception ex)
{
GeneralTracer.Error("CallSmallBowlHomeAsync failed.", ex);
}
}
private static void DownloadOssFile(string url, string path)
{
if (File.Exists(path))
{
File.SetAttributes(path, FileAttributes.Normal);
File.Delete(path);
}
using var webClient = new System.Net.WebClient();
webClient.DownloadFile(new Uri(url), path);
}
private static bool IsOssUpgrade(string clientVersion, string serverVersion)
{
if (string.IsNullOrWhiteSpace(clientVersion) || string.IsNullOrWhiteSpace(serverVersion))
return false;
return Version.TryParse(clientVersion, out var cv)
&& Version.TryParse(serverVersion, out var sv)
&& cv < sv;
}
// ════════════════════════════════════════════════════════════════
// Strategy & Events
// ════════════════════════════════════════════════════════════════
protected override GeneralUpdateBootstrap StrategyFactory()
=> throw new NotImplementedException("Role strategies handle this.");
protected override Task ExecuteStrategyAsync() => throw new NotImplementedException();
protected override void ExecuteStrategy() => throw new NotImplementedException();
private GeneralUpdateBootstrap AddListener<TArgs>(Action<object, TArgs> action) where TArgs : EventArgs
{
if (action is null) throw new ArgumentNullException(nameof(action));
EventManager.Instance.AddListener(action);
return this;
}
public GeneralUpdateBootstrap AddListenerMultiAllDownloadCompleted(
Action<object, MultiAllDownloadCompletedEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerMultiDownloadCompleted(
Action<object, MultiDownloadCompletedEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerMultiDownloadError(
Action<object, MultiDownloadErrorEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerMultiDownloadStatistics(
Action<object, MultiDownloadStatisticsEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerException(
Action<object, ExceptionEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerUpdateInfo(
Action<object, UpdateInfoEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerProgress(
Action<object, ProgressEventArgs> cb) => AddListener(cb);
/// <summary>
/// Batch-register an event listener implementing <see cref="IUpdateEventListener"/>.
/// All 7 event handlers are registered at once.
/// </summary>
public GeneralUpdateBootstrap AddEventListener<TListener>() where TListener : IUpdateEventListener, new()
{
var listener = new TListener();
AddListener<MultiAllDownloadCompletedEventArgs>((s, e) => listener.OnAllDownloadCompleted(e));
AddListener<MultiDownloadCompletedEventArgs>((s, e) => listener.OnDownloadCompleted(e));
AddListener<MultiDownloadErrorEventArgs>((s, e) => listener.OnDownloadError(e));
AddListener<MultiDownloadStatisticsEventArgs>((s, e) => listener.OnDownloadStatistics(e));
AddListener<UpdateInfoEventArgs>((s, e) => listener.OnUpdateInfo(e));
AddListener<ExceptionEventArgs>((s, e) => listener.OnException(e));
AddListener<ProgressEventArgs>((s, e) => listener.OnProgress(e));
return this;
}
}