forked from Reloaded-Project/Reloaded-II
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDownloadPackagesViewModel.cs
More file actions
334 lines (282 loc) · 11.1 KB
/
Copy pathDownloadPackagesViewModel.cs
File metadata and controls
334 lines (282 loc) · 11.1 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
using System.Collections.ObjectModel;
namespace Reloaded.Mod.Launcher.Lib.Models.ViewModel;
/// <summary>
/// ViewModel for downloading packages from multiple sources, including NuGet.
/// </summary>
public class DownloadPackagesViewModel : ObservableObject, IDisposable
{
/// <summary>
/// String to search mods by.
/// </summary>
public string SearchQuery { get; set; } = "";
/// <summary>
/// List of potential packages to download.
/// </summary>
public BatchObservableCollection<IDownloadablePackage> SearchResult { get; set; } = new();
/// <summary>
/// The currently selected package.
/// </summary>
public IDownloadablePackage SelectedResult { get; set; } = null!;
/// <summary>
/// Status of the current package download.
/// </summary>
public DownloadPackageStatus DownloadPackageStatus { get; set; }
/// <summary>
/// Command used to download an individual mod.
/// </summary>
public DownloadPackageCommand DownloadModCommand { get; set; } = null!;
/// <summary>
/// Command used to configure sources for NuGet packages.
/// </summary>
public ConfigureNuGetSourcesCommand ConfigureNuGetSourcesCommand { get; set; }
/// <summary>
/// True if the user can go to last page, else false.
/// </summary>
public bool CanGoToLastPage { get; set; } = false;
/// <summary>
/// True if the user can go to next page, else false.
/// </summary>
public bool CanGoToNextPage { get; set; } = true;
/// <summary>
/// Hide already installed mods.
/// </summary>
public bool HideInstalled { get; set; } = false;
/// <summary>
/// List of all available package providers.
/// </summary>
public ObservableCollection<IDownloadablePackageProvider> PackageProviders { get; set; } = new();
/// <summary>
/// The currently used package provider.
/// </summary>
public IDownloadablePackageProvider CurrentPackageProvider { get; set; }
/// <summary>
/// Selects the next package for viewing.
/// </summary>
public RelayCommand SelectNextItem { get; set; }
/// <summary>
/// Selects the previous package for viewing.
/// </summary>
public RelayCommand SelectLastItem { get; set; }
/// <summary>
/// Source for current search' cancellationtoken.
/// </summary>
public CancellationTokenSource CurrentSearchTokenSource { get; set; } = new ();
/// <summary>
/// The available sorting strategies.
/// </summary>
public ObservableCollection<SearchSortingMode> SortingModes { get; set; } = new ObservableCollection<SearchSortingMode>();
/// <summary>
/// The current sorting strategy used.
/// </summary>
public SearchSortingMode SortingMode { get; set; } = new SearchSortingMode();
/// <summary>
/// Whether the search should work in descending order.
/// </summary>
public bool SortDescending { get; set; } = true;
private PaginationHelper _paginationHelper = PaginationHelper.Default;
/* Construction - Deconstruction */
/// <inheritdoc />
public DownloadPackagesViewModel(AggregateNugetRepository nugetRepository, ApplicationConfigService appConfigService)
{
// Get providers for all games.
PackageProviders.AddRange(PackageProviderFactory.GetAllProviders(appConfigService.Items.ToArray(), nugetRepository.Sources));
var allPackageProvider = new AggregatePackageProvider(PackageProviders.Select(x => x).ToArray(), Resources.DownloadPackagesAll.Get());
PackageProviders.Add(allPackageProvider);
CurrentPackageProvider = allPackageProvider;
// Setup other viewmodel elements.
ConfigureNuGetSourcesCommand = new ConfigureNuGetSourcesCommand(RefreshOnSourceChange);
PropertyChanged += OnAnyPropChanged;
SelectLastItem = new RelayCommand(SelectLastResult, CanSelectLastResult);
SelectNextItem = new RelayCommand(SelectNextResult, CanSelectNextResult);
UpdateCommands();
// React to search results and pagination stuff.
SearchResult.CollectionChanged += SetCanGoToNextPageOnSearchResultsChanged;
// Perform Initial Search.
_paginationHelper.ItemsPerPage = 500;
SortingModes = new ObservableCollection<SearchSortingMode>(SearchSortingMode.GetAll());
#pragma warning disable CS4014
GetSearchResults();
#pragma warning restore CS4014
}
/// <inheritdoc />
public void Dispose() => CurrentSearchTokenSource?.Dispose();
/// <summary>
/// Gets the search results for the current search term.
/// </summary>
/// <returns></returns>
public async Task GetSearchResults()
{
CurrentSearchTokenSource?.Cancel();
CurrentSearchTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var localTokenSource = CurrentSearchTokenSource;
var searchTuples = await CurrentPackageProvider.SearchAsync(SearchQuery, _paginationHelper.Skip, _paginationHelper.Take, new SearchOptions()
{
Sort = SortingMode.SortingMode,
SortDescending = SortingMode.IsDescending
}, localTokenSource.Token);
// Ideally we would use ModifyObservableCollection but this is not possible when the results are sorted; as our view wouldn't reorder them.
if (!localTokenSource.IsCancellationRequested)
SearchResult = new BatchObservableCollection<IDownloadablePackage>(searchTuples);
}
/// <summary>
/// Moves the search forward 1 page.
/// </summary>
/// <returns></returns>
public async Task GoToNextPage()
{
_paginationHelper.NextPage();
CanGoToLastPage = _paginationHelper.Page > 0;
await GetSearchResults();
}
/// <summary>
/// Moves the search back 1 page.
/// </summary>
public async Task GoToLastPage()
{
_paginationHelper.PreviousPage();
CanGoToLastPage = _paginationHelper.Page > 0;
await GetSearchResults();
}
/// <summary>
/// Returns true if next result in the list can be selected.
/// </summary>
public bool CanSelectNextResult(object? unused = null)
{
var index = SearchResult.IndexOf(SelectedResult);
return index < SearchResult.Count - 1;
}
/// <summary>
/// Returns true if next result in the list can be selected.
/// </summary>
public bool CanSelectLastResult(object? unused = null)
{
var index = SearchResult.IndexOf(SelectedResult);
return index > 0;
}
/// <summary>
/// Selects the next result in the list.
/// </summary>
public void SelectLastResult(object? unused = null)
{
var index = SearchResult.IndexOf(SelectedResult);
SelectedResult = SearchResult[index - 1];
}
/// <summary>
/// Selects the next result in the list.
/// </summary>
public void SelectNextResult(object? unused = null)
{
var index = SearchResult.IndexOf(SelectedResult);
SelectedResult = SearchResult[index + 1];
}
[SuppressPropertyChangedWarnings]
private void OnAnyPropChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(SearchQuery))
{
ResetSearch();
}
else if (e.PropertyName == nameof(CurrentPackageProvider))
{
ResetSearch();
}
else if (e.PropertyName == nameof(SortingMode))
{
ResetSearch();
}
else if (e.PropertyName == nameof(SelectedResult))
{
UpdateCommands();
}
}
private void ResetSearch()
{
_paginationHelper.Reset();
CanGoToLastPage = false;
#pragma warning disable 4014
GetSearchResults(); // Fire and forget.
#pragma warning restore 4014
}
private void SetCanGoToNextPageOnSearchResultsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
CanGoToNextPage = SearchResult.Count >= _paginationHelper.ItemsPerPage;
}
private async void RefreshOnSourceChange() => await GetSearchResults();
private void UpdateCommands()
{
DownloadModCommand = new DownloadPackageCommand(SelectedResult, this, IoC.Get<ModConfigService>());
}
}
/// <summary>
/// Command allowing you to download an individual mod.
/// </summary>
public class DownloadPackageCommand : WithCanExecuteChanged, ICommand
{
private readonly IDownloadablePackage? _package;
private readonly DownloadPackagesViewModel _viewModel;
private readonly ModConfigService _modConfigService;
private bool _canExecute = true;
/// <inheritdoc />
public DownloadPackageCommand(IDownloadablePackage? package, DownloadPackagesViewModel viewModel, ModConfigService modConfigService)
{
_package = package;
_viewModel = viewModel;
_modConfigService = modConfigService;
}
/* ICommand. */
/// <inheritdoc />
public bool CanExecute(object? parameter)
{
if (!_canExecute)
return false;
if (_package == null)
return ReturnResult(false, DownloadPackageStatus.Default);
if (_modConfigService.Items.Any(x => x.Config.ModId == _package.Id))
return ReturnResult(false, DownloadPackageStatus.AlreadyDownloaded);
return ReturnResult(true, DownloadPackageStatus.Default);
bool ReturnResult(bool canExecute, DownloadPackageStatus status)
{
_viewModel.DownloadPackageStatus = status;
return canExecute;
}
}
/// <inheritdoc />
public void Execute(object? parameter)
{
_viewModel.DownloadPackageStatus = DownloadPackageStatus.Downloading;
try
{
var modConfigService = IoC.GetConstant<ModConfigService>();
var modsBefore = new Dictionary<string, PathTuple<ModConfig>>(modConfigService.ItemsById);
_canExecute = false;
RaiseCanExecute(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
ActionWrappers.ExecuteWithApplicationDispatcher(async () =>
{
var viewModel = new DownloadPackageViewModel(_package!, IoC.Get<LoaderConfig>());
var dl = viewModel.StartDownloadAsync(); // Fire and forget.
Actions.ShowFetchPackageDialog(viewModel);
await dl;
await Update.ResolveMissingPackagesAsync();
});
modConfigService.ForceRefresh();
var newConfigs = new List<ModConfig>();
foreach (var item in modConfigService.ItemsById.ToArray())
{
if (!modsBefore.ContainsKey(item.Key))
{
newConfigs.Add(item.Value.Config);
ModValidationHelper.ValidateModAppCompatibility(
item.Value,
IoC.Get<ApplicationConfigService>(),
modConfigService);
}
}
_canExecute = true;
RaiseCanExecute(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
finally
{
_viewModel.DownloadPackageStatus = DownloadPackageStatus.Default;
}
}
}