-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathAppUpdateSideloadService.cs
303 lines (246 loc) · 8.29 KB
/
AppUpdateSideloadService.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
// Copyright (c) Files Community
// Licensed under the MIT License.
using Microsoft.Extensions.Logging;
using System.IO;
using System.Net.Http;
using System.Xml.Serialization;
using Windows.ApplicationModel;
using Windows.Management.Deployment;
using Windows.Storage;
namespace Files.App.Services
{
public sealed partial class SideloadUpdateService : ObservableObject, IUpdateService, IDisposable
{
private const string SIDELOAD_STABLE = "https://cdn.files.community/files/stable/Files.Package.appinstaller";
private const string SIDELOAD_PREVIEW = "https://cdn.files.community/files/preview/Files.Package.appinstaller";
private readonly HttpClient _client = new(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(3) });
private readonly Dictionary<string, string> _sideloadVersion = new()
{
{ "Files", SIDELOAD_STABLE },
{ "FilesPreview", SIDELOAD_PREVIEW }
};
private const string TEMPORARY_UPDATE_PACKAGE_NAME = "UpdatePackage.msix";
private ILogger? Logger { get; } = Ioc.Default.GetRequiredService<ILogger<App>>();
private string PackageName { get; } = Package.Current.Id.Name;
private Version PackageVersion { get; } = new(
Package.Current.Id.Version.Major,
Package.Current.Id.Version.Minor,
Package.Current.Id.Version.Build,
Package.Current.Id.Version.Revision);
private Uri? DownloadUri { get; set; }
private bool _isUpdateAvailable;
public bool IsUpdateAvailable
{
get => _isUpdateAvailable;
private set => SetProperty(ref _isUpdateAvailable, value);
}
private bool _isUpdating;
public bool IsUpdating
{
get => _isUpdating;
private set => SetProperty(ref _isUpdating, value);
}
public bool IsAppUpdated
{
get => AppLifecycleHelper.IsAppUpdated;
}
private bool _areReleaseNotesAvailable = false;
public bool AreReleaseNotesAvailable
{
get => _areReleaseNotesAvailable;
private set => SetProperty(ref _areReleaseNotesAvailable, value);
}
public async Task DownloadUpdatesAsync()
{
await ApplyPackageUpdateAsync();
}
public Task DownloadMandatoryUpdatesAsync()
{
return Task.CompletedTask;
}
public async Task CheckForUpdatesAsync()
{
IsUpdateAvailable = false;
try
{
Logger?.LogInformation($"SIDELOAD: Checking for updates...");
await using var stream = await _client.GetStreamAsync(_sideloadVersion[PackageName]);
// Deserialize AppInstaller.
XmlSerializer xml = new XmlSerializer(typeof(AppInstaller));
var appInstaller = (AppInstaller?)xml.Deserialize(stream);
if (appInstaller is null)
throw new ArgumentNullException(nameof(appInstaller));
var remoteVersion = new Version(appInstaller.Version);
Logger?.LogInformation($"SIDELOAD: Current Package Name: {PackageName}");
Logger?.LogInformation($"SIDELOAD: Remote Package Name: {appInstaller.MainBundle.Name}");
Logger?.LogInformation($"SIDELOAD: Current Version: {PackageVersion}");
Logger?.LogInformation($"SIDELOAD: Remote Version: {remoteVersion}");
// Check details and version number
if (appInstaller.MainBundle.Name.Equals(PackageName) && remoteVersion.CompareTo(PackageVersion) > 0)
{
Logger?.LogInformation("SIDELOAD: Update found.");
Logger?.LogInformation("SIDELOAD: Starting background download.");
DownloadUri = new Uri(appInstaller.MainBundle.Uri);
await StartBackgroundDownloadAsync();
}
else
{
Logger?.LogWarning("SIDELOAD: Update not found.");
}
}
catch (HttpRequestException ex)
{
Logger?.LogDebug(ex, ex.Message);
}
catch (Exception ex)
{
Logger?.LogError(ex, ex.Message);
}
}
public async Task CheckAndUpdateFilesLauncherAsync()
{
try
{
var destFolderPath = Path.Combine(UserDataPaths.GetDefault().LocalAppData, "Files");
var destExeFilePath = Path.Combine(destFolderPath, "Files.App.Launcher.exe");
if (!File.Exists(destExeFilePath))
return;
var hashEqual = false;
var srcHashFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/FilesOpenDialog/Files.App.Launcher.exe.sha256"))
.AsTask().ConfigureAwait(false);
var destHashFilePath = Path.Combine(destFolderPath, "Files.App.Launcher.exe.sha256");
if (File.Exists(destHashFilePath))
{
await using var srcStream = (await srcHashFile.OpenReadAsync().AsTask().ConfigureAwait(false)).AsStream();
await using var destStream = File.OpenRead(destHashFilePath);
hashEqual = HashEqual(srcStream, destStream);
}
if (!hashEqual)
{
var srcExeFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/FilesOpenDialog/Files.App.Launcher.exe"))
.AsTask().ConfigureAwait(false);
var destFolder = await StorageFolder.GetFolderFromPathAsync(destFolderPath).AsTask().ConfigureAwait(false);
await srcExeFile.CopyAsync(destFolder, "Files.App.Launcher.exe", NameCollisionOption.ReplaceExisting)
.AsTask().ConfigureAwait(false);
await srcHashFile.CopyAsync(destFolder, "Files.App.Launcher.exe.sha256", NameCollisionOption.ReplaceExisting)
.AsTask().ConfigureAwait(false);
Logger?.LogInformation("Files.App.Launcher updated.");
}
}
catch (Exception ex)
{
Logger?.LogError(ex, ex.Message);
return;
}
bool HashEqual(Stream a, Stream b)
{
Span<byte> bufferA = stackalloc byte[64];
Span<byte> bufferB = stackalloc byte[64];
a.Read(bufferA);
b.Read(bufferB);
return bufferA.SequenceEqual(bufferB);
}
}
public async Task CheckForReleaseNotesAsync()
{
using var client = new HttpClient();
try
{
var response = await client.GetAsync(Constants.ExternalUrl.ReleaseNotesUrl);
AreReleaseNotesAvailable = response.IsSuccessStatusCode;
}
catch
{
AreReleaseNotesAvailable = false;
}
}
private async Task StartBackgroundDownloadAsync()
{
try
{
var tempDownloadPath = ApplicationData.Current.LocalFolder.Path + "\\" + TEMPORARY_UPDATE_PACKAGE_NAME;
Stopwatch timer = Stopwatch.StartNew();
await using (var stream = await _client.GetStreamAsync(DownloadUri))
await using (var fileStream = new FileStream(tempDownloadPath, FileMode.Create))
await stream.CopyToAsync(fileStream);
timer.Stop();
var timespan = timer.Elapsed;
Logger?.LogInformation($"Download time taken: {timespan.Hours:00}:{timespan.Minutes:00}:{timespan.Seconds:00}");
IsUpdateAvailable = true;
}
catch (IOException ex)
{
Logger?.LogDebug(ex, ex.Message);
}
catch (Exception ex)
{
Logger?.LogError(ex, ex.Message);
}
}
private async Task ApplyPackageUpdateAsync()
{
if (!IsUpdateAvailable)
return;
IsUpdating = true;
DeploymentResult? result = null;
try
{
PackageManager packageManager = new PackageManager();
var restartStatus = Win32PInvoke.RegisterApplicationRestart(null, 0);
App.AppModel.ForceProcessTermination = true;
Logger?.LogInformation($"Register for restart: {restartStatus}");
await Task.Run(async () =>
{
var bundlePath = new Uri(ApplicationData.Current.LocalFolder.Path + "\\" + TEMPORARY_UPDATE_PACKAGE_NAME);
var deployment = packageManager.RequestAddPackageAsync(
bundlePath,
null,
DeploymentOptions.ForceApplicationShutdown,
packageManager.GetDefaultPackageVolume(),
null,
null);
result = await deployment;
});
}
catch (Exception e)
{
if (result?.ExtendedErrorCode is not null)
Logger?.LogInformation(result.ErrorText);
Logger?.LogError(e, e.Message);
}
finally
{
// Reset fields
IsUpdating = false;
IsUpdateAvailable = false;
DownloadUri = null;
}
}
public void Dispose()
{
_client?.Dispose();
}
}
/// <summary>
/// AppInstaller class to hold information about remote updates.
/// </summary>
[XmlRoot(ElementName = "AppInstaller", Namespace = "http://schemas.microsoft.com/appx/appinstaller/2018")]
public sealed class AppInstaller
{
[XmlElement("MainBundle")]
public MainBundle MainBundle { get; set; }
[XmlAttribute("Uri")]
public string Uri { get; set; }
[XmlAttribute("Version")]
public string Version { get; set; }
}
public sealed class MainBundle
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("Version")]
public string Version { get; set; }
[XmlAttribute("Uri")]
public string Uri { get; set; }
}
}