-
-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathUpdate.cs
More file actions
420 lines (366 loc) · 16.2 KB
/
Update.cs
File metadata and controls
420 lines (366 loc) · 16.2 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
using Reloaded.Mod.Loader.Update.Providers.GitHub;
using Reloaded.Mod.Loader.Update.Providers.Index;
using Constants = Reloaded.Mod.Launcher.Lib.Misc.Constants;
using Version = Reloaded.Mod.Launcher.Lib.Utility.Version;
namespace Reloaded.Mod.Launcher.Lib;
/// <summary>
/// Contains static methods related to downloading loader, mods and updating them.
/// </summary>
public static class Update
{
private static IEnumerable<ModConfig> _modLoaderDependencies = new ModConfig[]
{
new()
{
ModId = "reloaded.mod.loader",
ModDependencies = new []{ "reloaded.sharedlib.hooks" },
PluginData = new Dictionary<string, object>()
{
// GitHub Dependency Resolver
{
GitHubReleasesDependencyMetadataWriter.PluginId,
new DependencyResolverMetadata<GitHubReleasesUpdateResolverFactory.GitHubConfig>()
{
IdToConfigMap = new()
{
{
"reloaded.sharedlib.hooks",
new DependencyResolverItem<GitHubReleasesUpdateResolverFactory.GitHubConfig>()
{
ReleaseMetadataName = "Sewer56.Update.ReleaseMetadata.json",
Config = new GitHubReleasesUpdateResolverFactory.GitHubConfig()
{
RepositoryName = "Reloaded.SharedLib.Hooks.ReloadedII",
UserName = "Sewer56",
UseReleaseTag = true,
AssetFileName = "reloaded.sharedlib.hooks.zip"
}
}
}
}
}
}
}
}
};
/* Strings */
/// <summary>
/// True if the user has an internet connection, else false.
/// </summary>
public static bool HasInternetConnection { get; set; } = CheckForInternetConnection();
/// <summary>
/// Checks if there are any updates for the mod loader.
/// </summary>
public static async Task CheckForLoaderUpdatesAsync()
{
if (!HasInternetConnection)
return;
// Check for loader updates.
UpdateManager<Empty>? manager = null;
try
{
var releaseVersion = Version.GetReleaseVersion()!;
var resolver = new GitHubReleaseResolver(new GitHubResolverConfiguration()
{
LegacyFallbackPattern = Constants.GitRepositoryReleaseName,
RepositoryName = Constants.GitRepositoryName,
UserName = Constants.GitRepositoryAccount
}, new CommonPackageResolverSettings()
{
AllowPrereleases = releaseVersion.IsPrerelease
});
var metadata = new ItemMetadata(releaseVersion, Constants.ApplicationPath, null);
manager = await UpdateManager<Empty>.CreateAsync(metadata, resolver, new SevenZipSharpExtractor());
// Check for new version and, if available, perform full update and restart
var result = await manager.CheckForUpdatesAsync();
if (result.CanUpdate)
{
Actions.SynchronizationContext.Send(_ =>
{
// ReSharper disable once AccessToDisposedClosure
Actions.ShowModLoaderUpdateDialog(new ModLoaderUpdateDialogViewModel(manager, result.LastVersion!));
}, null);
}
}
catch (Exception ex)
{
manager?.Dispose();
var errorMessage = $"{Resources.ErrorCheckUpdatesFailed.Get()}\n" +
$"{Resources.ErrorError.Get()}: {ex.Message}\n" +
$"{ex.StackTrace}";
Actions.SynchronizationContext.Send(_ =>
{
Actions.DisplayMessagebox.Invoke(Resources.ErrorError.Get(), errorMessage, new Actions.DisplayMessageBoxParams()
{
StartupLocation = Actions.WindowStartupLocation.CenterScreen
});
}, null);
}
}
/// <summary>
/// Checks if there are updates for any of the installed mods and/or new dependencies to fetch.
/// </summary>
public static async Task<bool> CheckForModUpdatesAsync()
{
if (!HasInternetConnection)
return false;
var loaderConfig = IoC.Get<LoaderConfig>();
var modConfigService = IoC.Get<ModConfigService>();
var modUserConfigService = IoC.Get<ModUserConfigService>();
try
{
var nugetFeeds = IoC.Get<AggregateNugetRepository>().Sources.Select(x => x.SourceUrl).ToList();
var resolverSettings = new CommonPackageResolverSettings() { AllowPrereleases = loaderConfig.ForceModPrereleases };
var updaterData = new UpdaterData(nugetFeeds, resolverSettings);
var updater = new Updater(modConfigService, modUserConfigService, updaterData);
var updateDetails = await updater.GetUpdateDetailsAsync();
if (updateDetails.HasUpdates())
{
Actions.SynchronizationContext.Send(_ =>
{
Actions.ShowModUpdateDialog.Invoke(new ModUpdateDialogViewModel(updater, updateDetails));
}, null);
return true;
}
}
catch (Exception e)
{
Actions.SynchronizationContext.Send(_ =>
{
Actions.DisplayMessagebox?.Invoke(Resources.ErrorError.Get(), e.Message + "|" + e.StackTrace, new Actions.DisplayMessageBoxParams()
{
StartupLocation = Actions.WindowStartupLocation.CenterScreen
});
}, null);
return false;
}
return false;
}
/// <summary>
/// Resolves a list of missing packages.
/// </summary>
/// <param name="token">Used to cancel the operation.</param>
public static async Task ResolveMissingPackagesAsync(CancellationToken token = default)
{
if (!HasInternetConnection)
return;
ModDependencyResolveResult? lastResolveResult = default;
ModDependencyResolveResult resolveResult;
do
{
resolveResult = await GetMissingDependenciesToDownload(token);
if (resolveResult.FoundDependencies.Count <= 0)
break;
if (IsSameAsLast(resolveResult, lastResolveResult))
{
ShowStuckInDownloadLoopDialog(resolveResult);
break;
}
lastResolveResult = resolveResult;
DownloadPackages(resolveResult, token);
}
while (true);
if (resolveResult.NotFoundDependencies.Count > 0)
ShowMissingPackagesDialog(resolveResult);
}
/// <summary>
/// Resolves a list of missing packages.
/// </summary>
public static void ResolveMissingPackages()
{
if (!HasInternetConnection)
return;
ModDependencyResolveResult? lastResolveResult = default;
ModDependencyResolveResult resolveResult;
do
{
resolveResult = Task.Run(async () => await GetMissingDependenciesToDownload(default)).GetAwaiter().GetResult();
if (resolveResult.FoundDependencies.Count <= 0)
break;
if (IsSameAsLast(resolveResult, lastResolveResult))
{
ShowStuckInDownloadLoopDialog(resolveResult);
break;
}
DownloadPackages(resolveResult);
lastResolveResult = resolveResult;
}
while (true);
if (resolveResult.NotFoundDependencies.Count > 0)
ShowMissingPackagesDialog(resolveResult);
}
/// <summary>
/// Displays the dialog indicating missing packages/dependencies.
/// </summary>
public static void ShowMissingPackagesDialog(ModDependencyResolveResult resolveResult)
{
// Note: This is slow, but it's ok in this rare case.
var notFoundDeps = resolveResult.NotFoundDependencies;
var list = new List<string>();
var modConfigService = IoC.Get<ModConfigService>();
foreach (var notFound in notFoundDeps)
foreach (var item in modConfigService.Items)
{
var conf = item.Config;
if (conf.ModDependencies.Contains(notFound))
list.Add($"{notFound} | Required by: {conf.ModId}");
}
ActionWrappers.ExecuteWithApplicationDispatcher(() =>
{
Actions.DisplayMessagebox(Resources.ErrorMissingDependency.Get(),
$"{Resources.FetchNugetNotFoundMessage.Get()}\n\n" +
$"{string.Join('\n', list)}\n\n" +
$"{Resources.FetchNugetNotFoundAdvice.Get()}",
new Actions.DisplayMessageBoxParams()
{
Type = Actions.MessageBoxType.Ok,
StartupLocation = Actions.WindowStartupLocation.CenterScreen
});
});
}
/// <summary>
/// Gets all missing dependencies to be downloaded.
/// </summary>
public static async Task<ModDependencyResolveResult> GetMissingDependenciesToDownload(CancellationToken token)
{
// Get missing dependencies for this update loop.
var missingDeps = CheckMissingDependencies();
if (missingDeps.AllAvailable)
return ModDependencyResolveResult.Combine(Enumerable.Empty<ModDependencyResolveResult>());
// Get Dependencies
var resolver = DependencyResolverFactory.GetInstance(IoC.Get<AggregateNugetRepository>());
var taskToDependencyMap = new Dictionary<Task<ModDependencyResolveResult>, string>();
foreach (var dependencyItem in missingDeps.Items)
foreach (var dependency in dependencyItem.Dependencies)
{
var task = resolver.ResolveAsync(dependency, dependencyItem.Mod.PluginData, token);
taskToDependencyMap[task] = dependency;
}
// Handle each result individually to avoid stopping on failures
var resolveResults = new List<ModDependencyResolveResult>();
foreach (var kvp in taskToDependencyMap)
{
try
{
var taskResult = await kvp.Key;
resolveResults.Add(taskResult);
}
catch (Exception ex)
{
// Create error result for unexpected exceptions that weren't caught by resolvers
resolveResults.Add(ModDependencyResolveResult.FromError(kvp.Value, ex, "UnknownResolver"));
}
}
// Merge Results
var result = ModDependencyResolveResult.Combine(resolveResults);
if (result.NotFoundDependencies.Count <= 0)
return result;
// Fallback to using Index Resolver if we couldn't find the package otherwise.
var indexResolver = new IndexDependencyResolver();
var indexResults = new List<ModDependencyResolveResult>();
foreach (var notFound in result.NotFoundDependencies)
indexResults.Add(await indexResolver.ResolveAsync(notFound, null, token));
indexResults.Add(result);
return ModDependencyResolveResult.Combine(indexResults);
}
/// <summary>
/// Shows the dialog for downloading dependencies given a result of dependency resolution.
/// </summary>
/// <param name="resolveResult">Result of resolving for missing packages.</param>
/// <param name="token">Used to cancel the operation.</param>
public static void DownloadPackages(ModDependencyResolveResult resolveResult, CancellationToken token = default)
{
if (!HasInternetConnection)
return;
if (resolveResult.FoundDependencies.Count <= 0)
return;
var viewModel = new DownloadPackageViewModel(resolveResult.FoundDependencies, IoC.Get<LoaderConfig>());
viewModel.Text = Resources.PackageDownloaderDownloadingDependencies.Get();
#pragma warning disable CS4014
viewModel.StartDownloadAsync(); // Fire and forget.
#pragma warning restore CS4014
Actions.SynchronizationContext.Send(state =>
{
Actions.ShowFetchPackageDialog.Invoke(viewModel);
}, null);
}
/// <summary>
/// Checks for all missing dependencies.
/// </summary>
/// <returns>True if there ar missing dependencies, else false.</returns>
public static DependencyResolutionResult CheckMissingDependencies()
{
var modConfigService = IoC.Get<ModConfigService>();
return modConfigService.GetMissingDependencies(_modLoaderDependencies);
}
/// <summary>
/// Checks if the user is connected to the internet using the same method Chromium OS does.
/// </summary>
/// <returns></returns>
public static bool CheckForInternetConnection()
{
var urls = new List<string>()
{
"http://clients1.google.com/generate_204",
"http://clients2.google.com/generate_204",
"http://clients3.google.com/generate_204",
"https://google.com",
"https://github.com",
"https://en.wikipedia.org",
"https://baidu.com" // In case of Firewall of People's Republic of China.
};
foreach (var url in urls)
{
try
{
using var client = new WebClient();
using (client.OpenRead(url))
return true;
}
catch
{
// ignored
}
}
return false;
}
// TODO: This is a temporary hack to get people unstuck.
private static bool IsSameAsLast(ModDependencyResolveResult thisItem, ModDependencyResolveResult? lastItem)
{
if (lastItem == null)
return false;
if (thisItem.FoundDependencies.Count != lastItem.FoundDependencies.Count)
return false;
// Assert whether they changed.
// We will always have ID as we resolve deps by ID.
var thisIds = new HashSet<string>(thisItem.FoundDependencies.Select(x => x.Id)!);
var otherIds = new HashSet<string>(lastItem.FoundDependencies.Select(x => x.Id)!);
return thisIds.SetEquals(otherIds);
}
private static void ShowStuckInDownloadLoopDialog(ModDependencyResolveResult result)
{
var message = new StringBuilder("We got stuck in a dependency download loop.\n" +
"This bug is tracked at:\n" +
"https://github.com/Reloaded-Project/Reloaded-II/issues/226\n\n" +
"Here's a list of mods that's stuck:\n");
foreach (var item in result.FoundDependencies)
{
message.AppendLine($"Id: {item.Id} | Name: {item.Name} | Version: {item.Version} | Source: {item.Source}");
}
message.AppendLine($"\nSometimes this can happen due to a mod incorrectly published/uploaded,\n" +
$"or a file being removed by a mod author of a dependency.\n\n" +
$"In some very rare cases, this can happen on any mod for completely unknown reasons.\n\n" +
$"Please report this issue to the link above if you encounter it.\n" +
$"In the meantime, download the required mods manually (you should " +
$"hopefully find it by ID or Name).\n\n" +
$"Sometimes this can also happen if you exceed the API rate limit.\n" +
$"Try again after about an hour; the issue may resolve itself.\n\n" +
$"Sorry for the pain.");
ActionWrappers.ExecuteWithApplicationDispatcher(() =>
{
Actions.DisplayMessagebox.Invoke("Stuck in Download Loop", message.ToString(), new Actions.DisplayMessageBoxParams(){
StartupLocation = Actions.WindowStartupLocation.CenterScreen
});
});
}
}