-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathGeneralUpdateBootstrap.cs
More file actions
346 lines (284 loc) · 12.9 KB
/
Copy pathGeneralUpdateBootstrap.cs
File metadata and controls
346 lines (284 loc) · 12.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
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.Common.FileBasic;
using GeneralUpdate.Common.Download;
using GeneralUpdate.Common.Internal;
using GeneralUpdate.Common.Internal.Bootstrap;
using GeneralUpdate.Common.Internal.Event;
using GeneralUpdate.Common.Internal.JsonContext;
using GeneralUpdate.Common.Internal.Strategy;
using GeneralUpdate.Common.Shared;
using GeneralUpdate.Common.Shared.Object;
using GeneralUpdate.Common.Shared.Object.Enum;
using GeneralUpdate.Common.Shared.Service;
using GeneralUpdate.Core.Strategys;
namespace GeneralUpdate.Core
{
public class GeneralUpdateBootstrap : AbstractBootstrap<GeneralUpdateBootstrap, IStrategy>
{
private GlobalConfigInfo _configInfo = new();
private IStrategy? _strategy;
private Func<bool>? _customSkipOption;
public GeneralUpdateBootstrap()
{
InitializeFromEnvironment();
}
#region Launch
public override async Task<GeneralUpdateBootstrap> LaunchAsync()
{
GeneralTracer.Debug("GeneralUpdateBootstrap Launch.");
StrategyFactory();
switch (GetOption(UpdateOption.Mode) ?? UpdateMode.Default)
{
case UpdateMode.Default:
ApplyRuntimeOptions();
_strategy!.Create(_configInfo);
await DownloadAsync();
await _strategy.ExecuteAsync();
break;
case UpdateMode.Scripts:
await ExecuteWorkflowAsync();
break;
default:
throw new ArgumentOutOfRangeException();
}
return this;
}
#endregion
#region Configuration
/// <summary>
/// Configure the update bootstrap with user-provided configuration.
/// Uses ConfigurationMapper to ensure consistent field mapping and reduce maintenance burden.
/// </summary>
/// <param name="configInfo">User-provided configuration containing update parameters</param>
/// <returns>This bootstrap instance for method chaining</returns>
public GeneralUpdateBootstrap SetConfig(Configinfo configInfo)
{
// Use ConfigurationMapper instead of manual field mapping
// This ensures all fields are consistently mapped and reduces maintenance burden
_configInfo = ConfigurationMapper.MapToGlobalConfigInfo(configInfo);
// Set runtime-specific values that are not part of user configuration
_configInfo.TempPath = StorageManager.GetTempDirectory("upgrade_temp");
_configInfo.DriveEnabled = GetOption(UpdateOption.Drive) ?? false;
_configInfo.PatchEnabled = GetOption(UpdateOption.Patch) ?? true;
InitBlackList();
return this;
}
public GeneralUpdateBootstrap SetFieldMappings(Dictionary<string, string> fieldMappings)
{
_configInfo.FieldMappings = fieldMappings;
return this;
}
public GeneralUpdateBootstrap SetCustomSkipOption(Func<bool>? func)
{
_customSkipOption = func;
return this;
}
#endregion
#region Workflow
private async Task ExecuteWorkflowAsync()
{
try
{
var mainResp = await VersionService.Validate(
_configInfo.UpdateUrl,
_configInfo.ClientVersion,
AppType.ClientApp,
_configInfo.AppSecretKey,
GetPlatform(),
_configInfo.ProductId,
_configInfo.Scheme,
_configInfo.Token);
_configInfo.IsMainUpdate = CheckUpgrade(mainResp);
if (CanSkip(CheckForcibly(mainResp.Body)))
return;
InitBlackList();
ApplyRuntimeOptions();
_configInfo.TempPath = StorageManager.GetTempDirectory("main_temp");
_configInfo.BackupDirectory = Path.Combine(
_configInfo.InstallPath,
$"{StorageManager.DirectoryName}{_configInfo.ClientVersion}");
_configInfo.UpdateVersions = mainResp.Body!
.OrderBy(x => x.ReleaseDate)
.ToList();
if (GetOption(UpdateOption.BackUp) ?? true)
{
StorageManager.Backup(
_configInfo.InstallPath,
_configInfo.BackupDirectory,
BlackListManager.Instance.SkipDirectorys);
}
_strategy!.Create(_configInfo);
if (_configInfo.IsMainUpdate)
{
await DownloadAsync();
await _strategy.ExecuteAsync();
}
else
{
_strategy.StartApp();
}
}
catch (Exception ex)
{
GeneralTracer.Error(
"The ExecuteWorkflowAsync method in the GeneralUpdateBootstrap class throws an exception.",
ex);
EventManager.Instance.Dispatch(this, new ExceptionEventArgs(ex, ex.Message));
}
}
#endregion
#region Download
private async Task DownloadAsync()
{
var manager = new DownloadManager(
_configInfo.TempPath,
_configInfo.Format,
_configInfo.DownloadTimeOut);
manager.MultiAllDownloadCompleted += OnMultiAllDownloadCompleted;
manager.MultiDownloadCompleted += OnMultiDownloadCompleted;
manager.MultiDownloadError += OnMultiDownloadError;
manager.MultiDownloadStatistics += OnMultiDownloadStatistics;
foreach (var version in _configInfo.UpdateVersions)
manager.Add(new DownloadTask(manager, version));
await manager.LaunchTasksAsync();
}
#endregion
#region 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.AddBlackFileFormats(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,
DriveEnabled = GetOption(UpdateOption.Drive) ?? false,
PatchEnabled = GetOption(UpdateOption.Patch) ?? true,
Script = processInfo.Script,
DriverDirectory = processInfo.DriverDirectory
};
}
private void ApplyRuntimeOptions()
{
_configInfo.Encoding = GetOption(UpdateOption.Encoding) ?? Encoding.Default;
_configInfo.Format = GetOption(UpdateOption.Format) ?? Format.ZIP;
_configInfo.DownloadTimeOut = GetOption(UpdateOption.DownloadTimeOut) ?? 60;
_configInfo.DriveEnabled = GetOption(UpdateOption.Drive) ?? false;
_configInfo.PatchEnabled = GetOption(UpdateOption.Patch) ?? true;
}
private void InitBlackList()
{
BlackListManager.Instance.AddBlackFiles(_configInfo.BlackFiles);
BlackListManager.Instance.AddBlackFileFormats(_configInfo.BlackFormats);
BlackListManager.Instance.AddSkipDirectorys(_configInfo.SkipDirectorys);
}
private bool CanSkip(bool isForcibly)
{
if (isForcibly)
{
return false;
}
// Treat a null custom skip option as "do not skip".
if (_customSkipOption is null)
{
return false;
}
return _customSkipOption();
}
private static bool CheckUpgrade(VersionRespDTO? response)
=> response?.Code == 200 && response.Body?.Count > 0;
private static bool CheckForcibly(IEnumerable<VersionInfo>? versions)
=> versions?.Any(v => v.IsForcibly == true) == true;
private static int GetPlatform()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return PlatformType.Windows;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return PlatformType.Linux;
throw new PlatformNotSupportedException("The current operating system is not supported!");
}
#endregion
#region Strategy & Events
protected override GeneralUpdateBootstrap StrategyFactory()
{
_strategy = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? new WindowsStrategy()
: RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? new LinuxStrategy()
: throw new PlatformNotSupportedException("The current operating system is not supported!");
return 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);
private void OnMultiDownloadStatistics(object sender, MultiDownloadStatisticsEventArgs e)
{
GeneralTracer.Info(
$"Multi download statistics, {ObjectTranslator.GetPacketHash(e.Version)} " +
$"[BytesReceived]:{e.BytesReceived} [ProgressPercentage]:{e.ProgressPercentage} " +
$"[Remaining]:{e.Remaining} [TotalBytesToReceive]:{e.TotalBytesToReceive} [Speed]:{e.Speed}");
EventManager.Instance.Dispatch(sender, e);
}
private void OnMultiDownloadCompleted(object sender, MultiDownloadCompletedEventArgs e)
{
GeneralTracer.Info(
$"Multi download completed, {ObjectTranslator.GetPacketHash(e.Version)} [IsCompleted]:{e.IsComplated}");
EventManager.Instance.Dispatch(sender, e);
}
private void OnMultiDownloadError(object sender, MultiDownloadErrorEventArgs e)
{
GeneralTracer.Error(
$"Multi download error {ObjectTranslator.GetPacketHash(e.Version)}.",
e.Exception);
EventManager.Instance.Dispatch(sender, e);
}
private void OnMultiAllDownloadCompleted(object sender, MultiAllDownloadCompletedEventArgs e)
{
GeneralTracer.Info($"Multi all download completed {e.IsAllDownloadCompleted}.");
EventManager.Instance.Dispatch(sender, e);
}
#endregion
}
}