Files
minecraft-modpack-updater/ModpackUpdater/AppUpdater.cs

78 lines
2.1 KiB
C#

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Reflection;
namespace ModpackUpdater;
public class AppUpdater
{
private class UpdateInfo
{
[JsonConverter(typeof(VersionConverter))]
public Version Version { get; set; }
public string DownloadUrl { get; set; }
}
private const string UPDATE_URL = "https://git.pilzinsel64.de/gaming/minecraft/minecraft-modpack-updater/-/snippets/3/raw/main/updates.json";
private readonly HttpClient httpClient = new();
private UpdateInfo info;
public async Task<bool> Check()
{
var hasUpdate = false;
try
{
var appVersion = Assembly.GetExecutingAssembly().GetName().Version;
string result = await httpClient.GetStringAsync(UPDATE_URL);
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 = Pilz.Win32.NativeTools.GetExecutablePath();
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
{
downloadStream = await client.GetStreamAsync(info.DownloadUrl);
await downloadStream.CopyToAsync(tempFileStream);
}
catch
{
}
finally
{
downloadStream?.Dispose();
}
}
// Replace current application file with new file
File.Move(appFileName, oldFileName, true);
File.Move(tempFileName, appFileName);
}
}