UpdateDownloader.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Threading.Tasks;
  7. namespace PixiEditor.UpdateModule;
  8. public static class UpdateDownloader
  9. {
  10. public static string DownloadLocation { get; } = Path.Join(Path.GetTempPath(), "PixiEditor");
  11. public static async Task DownloadReleaseZip(ReleaseInfo release)
  12. {
  13. Asset? matchingAsset = GetMatchingAsset(release);
  14. if (matchingAsset == null)
  15. {
  16. throw new FileNotFoundException("No matching update for your system found.");
  17. }
  18. using HttpClient client = new HttpClient();
  19. client.DefaultRequestHeaders.Add("User-Agent", "PixiEditor");
  20. client.DefaultRequestHeaders.Add("Accept", "application/octet-stream");
  21. var response = await client.GetAsync(matchingAsset.Url);
  22. if (response.StatusCode == HttpStatusCode.OK)
  23. {
  24. byte[] bytes = await response.Content.ReadAsByteArrayAsync();
  25. CreateTempDirectory();
  26. await File.WriteAllBytesAsync(Path.Join(DownloadLocation, $"update-{release.TagName}.zip"), bytes);
  27. }
  28. }
  29. public static async Task DownloadInstaller(ReleaseInfo info)
  30. {
  31. Asset? matchingAsset = GetMatchingAsset(info, "application/x-msdownload");
  32. if (matchingAsset == null)
  33. {
  34. throw new FileNotFoundException("No matching update for your system found.");
  35. }
  36. using HttpClient client = new HttpClient();
  37. client.DefaultRequestHeaders.Add("User-Agent", "PixiEditor");
  38. client.DefaultRequestHeaders.Add("Accept", "application/octet-stream");
  39. var response = await client.GetAsync(matchingAsset.Url);
  40. if (response.StatusCode == HttpStatusCode.OK)
  41. {
  42. byte[] bytes = await response.Content.ReadAsByteArrayAsync();
  43. CreateTempDirectory();
  44. await File.WriteAllBytesAsync(Path.Join(DownloadLocation, $"update-{info.TagName}.exe"), bytes);
  45. }
  46. }
  47. public static void CreateTempDirectory()
  48. {
  49. if (!Directory.Exists(DownloadLocation))
  50. {
  51. Directory.CreateDirectory(DownloadLocation);
  52. }
  53. }
  54. private static Asset? GetMatchingAsset(ReleaseInfo release, string assetType = "zip")
  55. {
  56. if (release.TagName.StartsWith("1."))
  57. {
  58. string archOld = IntPtr.Size == 8 ? "x64" : "x86";
  59. return release.Assets.FirstOrDefault(x => x.ContentType.Contains(assetType)
  60. && x.Name.Contains(archOld));
  61. }
  62. string arch = "x64";
  63. string os = OperatingSystem.IsWindows() ? "win" : OperatingSystem.IsLinux() ? "linux" : "mac";
  64. return release.Assets.FirstOrDefault(x => x.ContentType.Contains(assetType)
  65. && x.Name.Contains(arch) && x.Name.Contains(os));
  66. }
  67. }