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