forked from LykosAI/StabilityMatrix
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathUpdateHelper.cs
More file actions
324 lines (277 loc) · 11.3 KB
/
UpdateHelper.cs
File metadata and controls
324 lines (277 loc) · 11.3 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
using System.Text.Json;
using System.Web;
using Injectio.Attributes;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StabilityMatrix.Core.Api.LykosAuthApi;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models.Configs;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Models.Update;
using StabilityMatrix.Core.Services;
namespace StabilityMatrix.Core.Updater;
[RegisterSingleton<IUpdateHelper, UpdateHelper>]
public class UpdateHelper : IUpdateHelper
{
private readonly ILogger<UpdateHelper> logger;
private readonly IHttpClientFactory httpClientFactory;
private readonly IDownloadService downloadService;
private readonly ISettingsManager settingsManager;
private readonly ILykosAuthApiV2 lykosAuthApi;
private readonly DebugOptions debugOptions;
private readonly System.Timers.Timer timer = new(TimeSpan.FromMinutes(60));
private string UpdateManifestUrl =>
debugOptions.UpdateManifestUrl ?? "https://cdn.lykos.ai/update-v3.json";
public const string UpdateFolderName = ".StabilityMatrixUpdate";
public static DirectoryPath UpdateFolder => Compat.AppCurrentDir.JoinDir(UpdateFolderName);
public static IPathObject ExecutablePath =>
Compat.IsMacOS
? UpdateFolder.JoinDir(Compat.GetAppName())
: UpdateFolder.JoinFile(Compat.GetAppName());
/// <inheritdoc />
public event EventHandler<UpdateStatusChangedEventArgs>? UpdateStatusChanged;
public UpdateHelper(
ILogger<UpdateHelper> logger,
IHttpClientFactory httpClientFactory,
IDownloadService downloadService,
IOptions<DebugOptions> debugOptions,
ISettingsManager settingsManager,
ILykosAuthApiV2 lykosAuthApi
)
{
this.logger = logger;
this.httpClientFactory = httpClientFactory;
this.downloadService = downloadService;
this.settingsManager = settingsManager;
this.lykosAuthApi = lykosAuthApi;
this.debugOptions = debugOptions.Value;
timer.Elapsed += async (_, _) =>
{
await CheckForUpdate().ConfigureAwait(false);
};
settingsManager.RegisterOnLibraryDirSet(_ =>
{
timer.Start();
});
}
public async Task StartCheckingForUpdates()
{
timer.Enabled = true;
timer.Start();
await CheckForUpdate().ConfigureAwait(false);
}
public async Task DownloadUpdate(UpdateInfo updateInfo, IProgress<ProgressReport> progress)
{
UpdateFolder.Create();
UpdateFolder.Info.Attributes |= FileAttributes.Hidden;
var downloadFile = UpdateFolder.JoinFile(Path.GetFileName(updateInfo.Url.ToString()));
var extractDir = UpdateFolder.JoinDir("extract");
try
{
var url = updateInfo.Url.ToString();
// check if need authenticated download
const string authedPathPrefix = "/lykos-s1/";
if (
updateInfo.Url.Host.Equals("cdn.lykos.ai", StringComparison.OrdinalIgnoreCase)
&& updateInfo.Url.PathAndQuery.StartsWith(
authedPathPrefix,
StringComparison.OrdinalIgnoreCase
)
)
{
logger.LogInformation("Handling authenticated update download: {Url}", updateInfo.Url);
var path = updateInfo.Url.PathAndQuery.StripStart(authedPathPrefix);
path = HttpUtility.UrlDecode(path);
url = (
await lykosAuthApi.ApiV2FilesDownload(path).ConfigureAwait(false)
).DownloadUrl.ToString();
}
// Download update
await downloadService
.DownloadToFileAsync(url, downloadFile, progress: progress, httpClientName: "UpdateClient")
.ConfigureAwait(false);
// Unzip if needed
if (downloadFile.Extension == ".zip")
{
if (extractDir.Exists)
{
await extractDir.DeleteAsync(true).ConfigureAwait(false);
}
extractDir.Create();
progress.Report(new ProgressReport(-1, isIndeterminate: true, type: ProgressType.Extract));
await ArchiveHelper.Extract(downloadFile, extractDir).ConfigureAwait(false);
progress.Report(new ProgressReport(1, isIndeterminate: true, type: ProgressType.Extract));
// Find binary and move it up to the root
var binaryFile = extractDir
.EnumerateFiles("*", EnumerationOptionConstants.AllDirectories)
.First(f => f.Extension.ToLowerInvariant() is ".exe" or ".appimage");
await binaryFile.MoveToAsync((FilePath)ExecutablePath).ConfigureAwait(false);
}
else if (downloadFile.Extension == ".dmg")
{
if (!Compat.IsMacOS)
throw new NotSupportedException(".dmg is only supported on macOS");
if (extractDir.Exists)
{
await extractDir.DeleteAsync(true).ConfigureAwait(false);
}
extractDir.Create();
// Extract dmg contents
await ArchiveHelper.ExtractDmg(downloadFile, extractDir).ConfigureAwait(false);
// Find app dir and move it up to the root
var appBundle = extractDir.EnumerateDirectories("*.app").First();
await appBundle.MoveToAsync((DirectoryPath)ExecutablePath).ConfigureAwait(false);
}
// Otherwise just rename
else
{
downloadFile.Rename(ExecutablePath.Name);
}
progress.Report(new ProgressReport(1d));
}
finally
{
// Clean up original download
await downloadFile.DeleteAsync().ConfigureAwait(false);
// Clean up extract dir
if (extractDir.Exists)
{
await extractDir.DeleteAsync(true).ConfigureAwait(false);
}
}
}
public async Task CheckForUpdate()
{
try
{
var httpClient = httpClientFactory.CreateClient("UpdateClient");
var response = await httpClient.GetAsync(UpdateManifestUrl).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
logger.LogWarning(
"Error while checking for update {StatusCode} - {Content}",
response.StatusCode,
await response.Content.ReadAsStringAsync().ConfigureAwait(false)
);
return;
}
var updateManifest = await JsonSerializer
.DeserializeAsync<UpdateManifest>(
await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }
)
.ConfigureAwait(false);
if (updateManifest is null)
{
logger.LogError("UpdateManifest is null");
return;
}
foreach (
var channel in Enum.GetValues(typeof(UpdateChannel))
.Cast<UpdateChannel>()
.Where(c =>
c > UpdateChannel.Unknown && c <= settingsManager.Settings.PreferredUpdateChannel
)
)
{
if (
updateManifest.Updates.TryGetValue(channel, out var platforms)
&& platforms.GetInfoForCurrentPlatform() is { } update
&& ValidateUpdate(update)
)
{
OnUpdateStatusChanged(
new UpdateStatusChangedEventArgs
{
LatestUpdate = update,
UpdateChannels = updateManifest
.Updates.Select(kv => (kv.Key, kv.Value.GetInfoForCurrentPlatform()))
.Where(kv => kv.Item2 is not null)
.ToDictionary(kv => kv.Item1, kv => kv.Item2)!,
}
);
return;
}
}
logger.LogInformation("No update available");
var args = new UpdateStatusChangedEventArgs
{
UpdateChannels = updateManifest
.Updates.Select(kv => (kv.Key, kv.Value.GetInfoForCurrentPlatform()))
.Where(kv => kv.Item2 is not null)
.ToDictionary(kv => kv.Item1, kv => kv.Item2)!,
};
OnUpdateStatusChanged(args);
}
catch (Exception e)
{
logger.LogError(e, "Couldn't check for update");
}
}
private bool ValidateUpdate(UpdateInfo? update)
{
if (update is null)
return false;
// Verify signature
var checker = new SignatureChecker();
var signedData = update.GetSignedData();
if (!checker.Verify(signedData, update.Signature))
{
logger.LogError(
"UpdateInfo signature {Signature} is invalid, Data = {Data}, UpdateInfo = {Info}",
update.Signature,
signedData,
update
);
return false;
}
switch (update.Version.ComparePrecedenceTo(Compat.AppVersion))
{
case > 0:
// Newer version available
return true;
case 0:
{
// Same version available, check if we both have commit hash metadata
var updateHash = update.Version.Metadata;
var appHash = Compat.AppVersion.Metadata;
// Always assume update if (We don't have hash && Update has hash)
if (string.IsNullOrEmpty(appHash) && !string.IsNullOrEmpty(updateHash))
{
return true;
}
// Trim both to the lower length, to a minimum of 7 characters
var minLength = Math.Min(7, Math.Min(updateHash.Length, appHash.Length));
updateHash = updateHash[..minLength];
appHash = appHash[..minLength];
// If different, we can update
if (updateHash != appHash)
{
return true;
}
break;
}
}
return false;
}
private void OnUpdateStatusChanged(UpdateStatusChangedEventArgs args)
{
UpdateStatusChanged?.Invoke(this, args);
if (args.LatestUpdate is { } update)
{
logger.LogInformation(
"Update available {AppVer} -> {UpdateVer}",
Compat.AppVersion,
update.Version
);
EventManager.Instance.OnUpdateAvailable(update);
}
}
private void NotifyUpdateAvailable(UpdateInfo update)
{
logger.LogInformation("Update available {AppVer} -> {UpdateVer}", Compat.AppVersion, update.Version);
EventManager.Instance.OnUpdateAvailable(update);
}
}