Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.08 KB | None | 0 0
  1. #region imports
  2. using Installer.Models;
  3. using ReactiveUI;
  4. using System;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.IO.Compression;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Http.Json;
  12. using System.Runtime.InteropServices;
  13. using System.Threading.Tasks;
  14. #endregion
  15.  
  16. namespace Installer.ViewModels;
  17.  
  18. public partial class MainWindowViewModel : ViewModelBase
  19. {
  20.     #region Private Properties
  21.     private static HttpClient _client;
  22.     private readonly string _url = "https://api.github.com/repos/mekasu0124/Todo/releases/latest";
  23.     #endregion
  24.  
  25.     #region Observable Properties
  26.     public double _value;
  27.     public string _currentInformation;
  28.     public string _userOs;
  29.     public string _osDownloadUrl;
  30.     public bool _isUpdating;
  31.     public bool _canRun;
  32.     public bool _isUpdateFinished;
  33.     public record VersionData(string DownloadName, string DownloadUrl, ulong DownloadSize);
  34.     #endregion
  35.  
  36.     #region Getter and Setters
  37.     private double Value
  38.     {
  39.         get => _value;
  40.         set => this.RaiseAndSetIfChanged(ref _value, value);
  41.     }
  42.  
  43.     private string CurrentInformation
  44.     {
  45.         get => _currentInformation;
  46.         set => this.RaiseAndSetIfChanged(ref _currentInformation, value);
  47.     }
  48.  
  49.     private string UserOs
  50.     {
  51.         get => _userOs;
  52.         set => this.RaiseAndSetIfChanged(ref _userOs, value);
  53.     }
  54.  
  55.     private string OsDownloadUrl
  56.     {
  57.         get => _osDownloadUrl;
  58.         set => this.RaiseAndSetIfChanged(ref _osDownloadUrl, value);
  59.     }
  60.  
  61.     private bool IsUpdating
  62.     {
  63.         get => _isUpdating;
  64.         set => this.RaiseAndSetIfChanged(ref _isUpdating, value);
  65.     }
  66.  
  67.     private bool CanRun
  68.     {
  69.         get => _canRun;
  70.         set => this.RaiseAndSetIfChanged(ref _canRun, value);
  71.     }
  72.  
  73.     private bool IsUpdateFinished
  74.     {
  75.         get => _isUpdateFinished;
  76.         set => this.RaiseAndSetIfChanged(ref _isUpdateFinished, value);
  77.     }
  78.     #endregion
  79.  
  80.     public async void BeginUpdate()
  81.     {
  82.         var data = await GetDownloadUrl();
  83.  
  84.         if (data is { } d)
  85.         {
  86.             bool check = await DownloadAndExtract(d);
  87.  
  88.             if (check)
  89.             {
  90.                 AlertUserProcessFinished();
  91.             }
  92.         }
  93.     }
  94.  
  95.     SupportedOperatingSystem GetSupportedOs()
  96.     {
  97.         if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  98.             return SupportedOperatingSystem.Windows;
  99.         if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  100.             return SupportedOperatingSystem.Linux;
  101.         if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  102.             return SupportedOperatingSystem.Mac;
  103.         throw new PlatformNotSupportedException();
  104.     }
  105.    
  106.     async Task<VersionData?> GetDownloadUrl()
  107.     {
  108.         _client.DefaultRequestHeaders.UserAgent.TryParseAdd("request");
  109.  
  110.         try
  111.         {
  112.             var data = await _client.GetFromJsonAsync<ReleaseResponseDTO>(_url);
  113.             var releases = data.Assets;
  114.             var os = GetSupportedOs();
  115.             var osReleaseData = releases.FirstOrDefault(x =>
  116.             {
  117.                 var name = x.DownloadName;
  118.                 return os switch
  119.                 {
  120.                     SupportedOperatingSystem.Windows => name.Contains("Windows"),
  121.                     SupportedOperatingSystem.Linux => name.Contains("Linux"),
  122.                     SupportedOperatingSystem.Mac => name.Contains("Mac"),
  123.                     _ => false
  124.                 };
  125.             });
  126.  
  127.             if (osReleaseData != null)
  128.                 return new VersionData(
  129.                     osReleaseData.DownloadName,
  130.                     osReleaseData.DownloadUrl,
  131.                     osReleaseData.DownloadSize);
  132.  
  133.             CurrentInformation = "Failed to obtain download URL for given OS.";
  134.             return null;
  135.         }
  136.         catch (HttpRequestException ex)
  137.         {
  138.             CurrentInformation = ex.Message;
  139.             return new VersionData("Error", ex.Message, 0);
  140.         }
  141.     }
  142.  
  143.     async Task<bool> DownloadAndExtract(VersionData versionData)
  144.     {
  145.         try
  146.         {
  147.             // download zip folder to current Directory
  148.             var bytes = await _client.GetByteArrayAsync(versionData.DownloadUrl);
  149.             await File.WriteAllBytesAsync(Directory.GetCurrentDirectory(), bytes);
  150.  
  151.             // create zip directory path
  152.             string zipPath = (Directory.GetCurrentDirectory() + "\\" + versionData.DownloadName);
  153.  
  154.             // create temp folder for zipped files to go to
  155.             string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
  156.  
  157.             // create extract path
  158.             string extractToPath = Directory.GetCurrentDirectory();
  159.  
  160.             // unzip the folder to the temporary path
  161.             ZipFile.ExtractToDirectory(zipPath, tempPath);
  162.  
  163.             // build an array of the unzipped files
  164.             string[] files = Directory.GetFiles(tempPath);
  165.  
  166.             // iterate over each file
  167.             foreach (string file in files)
  168.             {
  169.                 // get file info
  170.                 FileInfo f = new FileInfo(file);
  171.  
  172.                 // if file exists
  173.                 if (File.Exists(Path.Combine(extractToPath, f.Name)))
  174.                 {
  175.                     // delete existing
  176.                     File.Delete(Path.Combine(extractToPath, f.Name));
  177.                     // move new in it's place
  178.                     File.Move(f.FullName, Path.Combine(extractToPath, f.Name));
  179.                 }
  180.                 else
  181.                 {
  182.                     // otherwise, just move the new file
  183.                     File.Move(f.FullName, Path.Combine(extractToPath, f.Name));
  184.                 }
  185.             }
  186.  
  187.             // clean up temp files
  188.             Directory.Delete(tempPath);
  189.             // clean up zip folder itself
  190.             Directory.Delete(zipPath);
  191.             IsUpdateFinished = true;
  192.             return true;
  193.         }
  194.         catch (Exception ex)
  195.         {
  196.             CurrentInformation = ex.Message;
  197.             return false;
  198.         }
  199.     }
  200.  
  201.     // used to increment progress bar
  202.     public void IncrementProgress(double progVal)
  203.     {
  204.         Value += progVal;
  205.     }
  206.  
  207.     public void AlertUserProcessFinished()
  208.     {
  209.         CurrentInformation = "THe Update Has Finished. Click Launch App To Open Todo App";
  210.         CanRun = true;
  211.     }
  212.  
  213.     public void LaunchApplication()
  214.     {
  215.         var userOs = GetSupportedOs();
  216.  
  217.         switch (userOs)
  218.         {
  219.             case SupportedOperatingSystem.Windows:
  220.                 var p = new Process();
  221.                 p.StartInfo.FileName = "Todo.exe";
  222.                 Environment.Exit(0);
  223.                 break;
  224.  
  225.             case SupportedOperatingSystem.Linux:
  226.                 // some code to launch application on linux
  227.                 Environment.Exit(0);
  228.                 break;
  229.  
  230.             case SupportedOperatingSystem.Mac:
  231.                 // some code to launch application on Mac
  232.                 Environment.Exit(0);
  233.                 break;
  234.         }
  235.     }
  236. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement