seperated cli & some work for options
This commit is contained in:
82
ModpackUpdater.Apps.Client.Gui/AppUpdater.cs
Normal file
82
ModpackUpdater.Apps.Client.Gui/AppUpdater.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Pilz.Extensions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ModpackUpdater.Apps.Client.Gui;
|
||||
|
||||
public class AppUpdater(string updateUrl)
|
||||
{
|
||||
private class UpdateInfo
|
||||
{
|
||||
[JsonConverter(typeof(VersionConverter))]
|
||||
public Version Version { get; set; }
|
||||
public string DownloadUrl { get; set; }
|
||||
}
|
||||
|
||||
private readonly HttpClient httpClient = new();
|
||||
private UpdateInfo info;
|
||||
|
||||
public async Task<bool> Check()
|
||||
{
|
||||
var hasUpdate = false;
|
||||
|
||||
try
|
||||
{
|
||||
var appVersion = Assembly.GetExecutingAssembly().GetAppVersion().Version;
|
||||
var result = await httpClient.GetStringAsync(updateUrl);
|
||||
info = JsonConvert.DeserializeObject<UpdateInfo>(result);
|
||||
|
||||
if (info is not null && info.Version > appVersion)
|
||||
hasUpdate = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
return hasUpdate;
|
||||
}
|
||||
|
||||
public async Task Install()
|
||||
{
|
||||
var client = new HttpClient();
|
||||
var tempFileName = Path.GetTempFileName();
|
||||
var appFileName = Environment.ProcessPath;
|
||||
var oldFileName = appFileName + ".old";
|
||||
|
||||
// Delete old file
|
||||
try
|
||||
{
|
||||
File.Delete(oldFileName);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
// Download the new file
|
||||
using (var tempFileStream = new FileStream(tempFileName, FileMode.Create, FileAccess.ReadWrite))
|
||||
{
|
||||
Stream? downloadStream = null;
|
||||
try
|
||||
{
|
||||
var url = info?.DownloadUrl;
|
||||
downloadStream = await client.GetStreamAsync(url);
|
||||
await downloadStream.CopyToAsync(tempFileStream);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
downloadStream?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Replace current application file with new file
|
||||
if (!string.IsNullOrWhiteSpace(appFileName))
|
||||
{
|
||||
File.Move(appFileName, oldFileName, true);
|
||||
File.Move(tempFileName, appFileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user