-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.cs
467 lines (407 loc) · 18 KB
/
Main.cs
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Flow.Launcher.Plugin;
using Microsoft.Win32;
using System.Windows.Controls;
using System.Windows;
namespace Flow.Launcher.Plugin.AppUpgrader
{
public class AppUpgrader : IAsyncPlugin, ISettingProvider
{
private SettingsPage settingsPage;
internal PluginInitContext Context;
private ConcurrentBag<UpgradableApp> allUpgradableApps;
private ConcurrentBag<UpgradableApp> upgradableApps;
private ConcurrentDictionary<string, string> appIconPaths;
private readonly SemaphoreSlim _refreshSemaphore = new SemaphoreSlim(1, 1);
private DateTime _lastRefreshTime = DateTime.MinValue;
private const int CACHE_EXPIRATION_MINUTES = 15;
private const int COMMAND_TIMEOUT_SECONDS = 10;
private static readonly Regex AppLineRegex = new Regex(
@"^(.+?)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$",
RegexOptions.Compiled | RegexOptions.IgnoreCase,
TimeSpan.FromMilliseconds(500)
);
private static readonly Regex DashLineRegex = new Regex(
@"^-+$",
RegexOptions.Compiled,
TimeSpan.FromMilliseconds(500)
);
public async Task InitAsync(PluginInitContext context)
{
Context = context;
appIconPaths = new ConcurrentDictionary<string, string>();
Application.Current.Dispatcher.Invoke(() =>
{
settingsPage = new SettingsPage(Context);
settingsPage.SettingLoaded += async (s, e) =>
{
settingsPage.ExcludedApps.CollectionChanged += (s,e)=> ApplyExclusionFilter();
RemoveExcludedAppsFromUpgradableList();
};
});
Task.Run(async () =>
{
try
{
await RefreshUpgradableAppsAsync();
}
catch (Exception ex){}
});
ThreadPool.SetMinThreads(Environment.ProcessorCount * 2, Environment.ProcessorCount * 2);
await Task.CompletedTask;
}
private void RemoveExcludedAppsFromUpgradableList()
{
var excludedApps = settingsPage.ExcludedApps;
if (excludedApps == null || !excludedApps.Any())
{
return;
}
var updatedApps = upgradableApps
.Where(app => !excludedApps.Any(excludedApp =>
app.Name.Contains(excludedApp, StringComparison.OrdinalIgnoreCase) ||
app.Id.Contains(excludedApp, StringComparison.OrdinalIgnoreCase)))
.ToList();
upgradableApps = new ConcurrentBag<UpgradableApp>(updatedApps);
}
private void ExcludedApps_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add ||
e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
RemoveExcludedAppsFromUpgradableList();
}
}
public async Task<List<Result>> QueryAsync(Query query, CancellationToken token)
{
if (ShouldRefreshCache())
{
await RefreshUpgradableAppsAsync();
}
if (upgradableApps == null || !upgradableApps.Any())
{
return new List<Result>
{
new Result
{
Title = "No updates available",
SubTitle = "All applications are up-to-date.",
IcoPath = "Images\\app.png"
}
};
}
string filterTerm = query.Search?.Trim().ToLower();
var results = new List<Result>();
if (settingsPage.EnableUpgradeAll)
{
results.Add(new Result
{
Title = "Upgrade All Applications",
SubTitle = "Upgrade all apps listed below.",
IcoPath = "Images\\app.png",
Action = context =>
{
Task.Run(async () =>
{
try
{
foreach (var app in upgradableApps)
{
await PerformUpgradeAsync(app);
}
}
catch (Exception ex){}
});
return true;
}
});
}
var tasks = upgradableApps.AsParallel()
.WithDegreeOfParallelism(Environment.ProcessorCount)
.Where(app => string.IsNullOrEmpty(filterTerm) ||
app.Name.ToLower().Contains(filterTerm))
.Select(async app => new Result
{
Title = $"Upgrade {app.Name}",
SubTitle = $"From {app.Version} to {app.AvailableVersion}",
IcoPath = await GetAppIconPath(app.Id, app.Name),
Action = context =>
{
Task.Run(async () =>
{
try
{
await PerformUpgradeAsync(app);
}
catch (Exception ex)
{
Context.API.ShowMsg($"Upgrade failed: {ex.Message}");
}
});
return true;
}
});
results.AddRange(await Task.WhenAll(tasks));
return results;
}
private async Task<string> GetAppIconPath(string appId, string appName)
{
if (appIconPaths.TryGetValue(appId, out string cachedPath))
{
return cachedPath;
}
try
{
var cleanAppName = new string(appName.TakeWhile(c => c != ' ').ToArray()).ToLowerInvariant();
var possibleNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
cleanAppName,
appName.ToLowerInvariant(),
appId.ToLowerInvariant()
};
if (appName.Contains(" "))
{
possibleNames.Add(appName.Replace(" ", "").ToLowerInvariant());
possibleNames.Add(string.Join(".", appName.Split(' ')).ToLowerInvariant());
}
var searchPaths = new List<string>
{
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs"),
@"C:\Program Files\WindowsApps"
};
foreach (var basePath in searchPaths)
{
if (!Directory.Exists(basePath)) continue;
var directories = await Task.Run(() => Directory.GetDirectories(basePath, "*", SearchOption.TopDirectoryOnly));
var possibleDirs = directories.Where(dir => possibleNames.Any(name =>
Path.GetFileName(dir).Contains(name, StringComparison.OrdinalIgnoreCase)));
foreach (var dir in possibleDirs)
{
var iconFiles = new List<string>();
try
{
await Task.Run(() =>
{
iconFiles.AddRange(Directory.GetFiles(dir, "*.exe", SearchOption.AllDirectories));
iconFiles.AddRange(Directory.GetFiles(dir, "*.ico", SearchOption.AllDirectories));
iconFiles.AddRange(Directory.GetFiles(dir, "*.lnk", SearchOption.AllDirectories));
});
}
catch (UnauthorizedAccessException) { continue; }
foreach (var file in iconFiles)
{
var fileName = Path.GetFileNameWithoutExtension(file).ToLowerInvariant();
if (possibleNames.Any(name => fileName.Contains(name)))
{
appIconPaths.TryAdd(appId, file);
return file;
}
}
}
}
var registryResult = await Task.Run(() =>
{
var registryPaths = new[]
{
$@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{cleanAppName}.exe",
$@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{appId}",
$@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{appId}",
$@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{cleanAppName}",
$@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{cleanAppName}"
};
foreach (var regPath in registryPaths)
{
using (var key = Registry.LocalMachine.OpenSubKey(regPath))
using (var userKey = Registry.CurrentUser.OpenSubKey(regPath))
{
foreach (var regKey in new[] { key, userKey })
{
if (regKey == null) continue;
var paths = new[]
{
regKey.GetValue("DisplayIcon") as string,
regKey.GetValue("InstallLocation") as string,
regKey.GetValue(null) as string
};
foreach (var path in paths.Where(p => !string.IsNullOrEmpty(p)))
{
if (File.Exists(path))
{
return path;
}
if (Directory.Exists(path))
{
var iconInDir = Directory.GetFiles(path, "*.exe")
.Concat(Directory.GetFiles(path, "*.ico"))
.FirstOrDefault(f => possibleNames.Any(name =>
Path.GetFileNameWithoutExtension(f).Contains(name, StringComparison.OrdinalIgnoreCase)));
if (iconInDir != null)
{
return iconInDir;
}
}
}
}
}
}
return null;
});
if (registryResult != null)
{
appIconPaths.TryAdd(appId, registryResult);
return registryResult;
}
var startMenuPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu);
var shortcutFiles = await Task.Run(() =>
Directory.GetFiles(startMenuPath, "*.lnk", SearchOption.AllDirectories)
.Where(f => possibleNames.Any(name =>
Path.GetFileNameWithoutExtension(f).Contains(name, StringComparison.OrdinalIgnoreCase)))
.ToList());
if (shortcutFiles.Any())
{
var result = shortcutFiles.First();
appIconPaths.TryAdd(appId, result);
return result;
}
}
catch (Exception ex){}
return "Images\\app.png";
}
private bool ShouldRefreshCache()
{
return upgradableApps == null ||
DateTime.UtcNow - _lastRefreshTime > TimeSpan.FromMinutes(CACHE_EXPIRATION_MINUTES);
}
private async Task RefreshUpgradableAppsAsync()
{
if (!ShouldRefreshCache())
return;
await _refreshSemaphore.WaitAsync();
try
{
if (!ShouldRefreshCache())
return;
var apps = await GetUpgradableAppsAsync();
allUpgradableApps = new ConcurrentBag<UpgradableApp>(apps);
ApplyExclusionFilter();
_lastRefreshTime = DateTime.UtcNow;
}
finally
{
_refreshSemaphore.Release();
}
}
private void ApplyExclusionFilter()
{
var excludedApps = settingsPage.ExcludedApps;
if (excludedApps == null || !excludedApps.Any())
{
upgradableApps = new ConcurrentBag<UpgradableApp>(allUpgradableApps);
return;
}
var filteredApps = allUpgradableApps
.Where(app => !excludedApps.Any(excludedApp =>
app.Name.Contains(excludedApp, StringComparison.OrdinalIgnoreCase) ||
app.Id.Contains(excludedApp, StringComparison.OrdinalIgnoreCase)))
.ToList();
upgradableApps = new ConcurrentBag<UpgradableApp>(filteredApps);
}
private async Task PerformUpgradeAsync(UpgradableApp app)
{
Context.API.ShowMsg($"Preparing to update {app.Name}... This may take a moment.");
await ExecuteWingetCommandAsync($"winget upgrade --id {app.Id} -i");
if (allUpgradableApps != null)
{
var updatedAllApps = allUpgradableApps.Where(a => a.Id != app.Id).ToList();
allUpgradableApps = new ConcurrentBag<UpgradableApp>(updatedAllApps);
}
if (upgradableApps != null)
{
var updatedApps = upgradableApps.Where(a => a.Id != app.Id).ToList();
upgradableApps = new ConcurrentBag<UpgradableApp>(updatedApps);
}
await RefreshUpgradableAppsAsync();
}
public Control CreateSettingPanel()
{
return settingsPage;
}
private async Task<List<UpgradableApp>> GetUpgradableAppsAsync()
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(COMMAND_TIMEOUT_SECONDS));
var output = await ExecuteWingetCommandAsync("winget upgrade", cts.Token);
return ParseWingetOutput(output);
}
private static List<UpgradableApp> ParseWingetOutput(string output)
{
var upgradableApps = new List<UpgradableApp>();
var lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var startIndex = Array.FindIndex(lines, line => DashLineRegex.IsMatch(line));
if (startIndex == -1) return upgradableApps;
for (int i = startIndex + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (string.IsNullOrWhiteSpace(line)) continue;
var match = AppLineRegex.Match(line);
if (match.Success)
{
var app = new UpgradableApp
{
Name = match.Groups[1].Value.Trim(),
Id = match.Groups[2].Value,
Version = match.Groups[3].Value,
AvailableVersion = match.Groups[4].Value,
Source = match.Groups[5].Value
};
if (app.Id.Contains('.') || app.Id.Contains('-'))
{
upgradableApps.Add(app);
}
}
}
return upgradableApps;
}
private static async Task<string> ExecuteWingetCommandAsync(string command, CancellationToken cancellationToken = default)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = Process.Start(processInfo);
if (process == null)
throw new InvalidOperationException("Failed to start process.");
var output = await process.StandardOutput.ReadToEndAsync(cancellationToken);
var error = await process.StandardError.ReadToEndAsync(cancellationToken);
await process.WaitForExitAsync(cancellationToken);
if (!string.IsNullOrEmpty(error))
{
throw new InvalidOperationException(error);
}
return output;
}
}
public class UpgradableApp
{
public string Name { get; set; }
public string Id { get; set; }
public string Version { get; set; }
public string AvailableVersion { get; set; }
public string Source { get; set; }
}
}