UpdateDownloader.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. {
  9. public static class UpdateDownloader
  10. {
  11. public static string DownloadLocation { get; } = Path.Join(Path.GetTempPath(), "PixiEditor");
  12. public static async Task DownloadReleaseZip(ReleaseInfo release)
  13. {
  14. Asset matchingAsset = GetMatchingAsset(release);
  15. using (HttpClient client = new HttpClient())
  16. {
  17. client.DefaultRequestHeaders.Add("User-Agent", "PixiEditor");
  18. client.DefaultRequestHeaders.Add("Accept", "application/octet-stream");
  19. var response = await client.GetAsync(matchingAsset.Url);
  20. if (response.StatusCode == HttpStatusCode.OK)
  21. {
  22. byte[] bytes = await response.Content.ReadAsByteArrayAsync();
  23. CreateTempDirectory();
  24. File.WriteAllBytes(Path.Join(DownloadLocation, $"update-{release.TagName}.zip"), bytes);
  25. }
  26. }
  27. }
  28. public static async Task DownloadInstaller(ReleaseInfo info)
  29. {
  30. Asset matchingAsset = GetMatchingAsset(info, "application/x-msdownload");
  31. using (HttpClient client = new HttpClient())
  32. {
  33. client.DefaultRequestHeaders.Add("User-Agent", "PixiEditor");
  34. client.DefaultRequestHeaders.Add("Accept", "application/octet-stream");
  35. var response = await client.GetAsync(matchingAsset.Url);
  36. if (response.StatusCode == HttpStatusCode.OK)
  37. {
  38. byte[] bytes = await response.Content.ReadAsByteArrayAsync();
  39. CreateTempDirectory();
  40. File.WriteAllBytes(Path.Join(DownloadLocation, $"update-{info.TagName}.exe"), bytes);
  41. }
  42. }
  43. }
  44. public static void CreateTempDirectory()
  45. {
  46. if (!Directory.Exists(DownloadLocation))
  47. {
  48. Directory.CreateDirectory(DownloadLocation);
  49. }
  50. }
  51. private static Asset GetMatchingAsset(ReleaseInfo release, string assetType = "zip")
  52. {
  53. string arch = IntPtr.Size == 8 ? "x64" : "x86";
  54. return release.Assets.First(x => x.ContentType.Contains(assetType)
  55. && x.Name.Contains(arch));
  56. }
  57. }
  58. }