1
1

HttpFunctions.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. using System.Diagnostics;
  2. using System.IO;
  3. using System.Windows;
  4. using System.Windows.Threading;
  5. using PicView.Core.FileHandling;
  6. using PicView.WPF.ChangeImage;
  7. using PicView.WPF.ImageHandling;
  8. using PicView.WPF.UILogic;
  9. using static PicView.WPF.ChangeImage.ErrorHandling;
  10. using static PicView.WPF.UILogic.Tooltip;
  11. namespace PicView.WPF.FileHandling
  12. {
  13. public abstract class HttpFunctions
  14. {
  15. /// <summary>
  16. /// Attempts to download image and display it
  17. /// </summary>
  18. /// <param name="url"></param>
  19. internal static async Task LoadPicFromUrlAsync(string url)
  20. {
  21. ChangeFolder(true);
  22. string destination;
  23. try
  24. {
  25. destination = await DownloadDataAsync(url).ConfigureAwait(false);
  26. }
  27. catch (Exception e)
  28. {
  29. #if DEBUG
  30. Trace.WriteLine("LoadPicFromUrlAsync exception = \n" + e.Message);
  31. #endif
  32. await ConfigureWindows.GetMainWindow.Dispatcher.InvokeAsync(async () =>
  33. {
  34. await ReloadAsync(true).ConfigureAwait(false);
  35. ShowTooltipMessage(e.Message, true);
  36. });
  37. return;
  38. }
  39. var check = CheckIfLoadableString(destination);
  40. switch (check)
  41. {
  42. default:
  43. var pic = await Image2BitmapSource.ReturnBitmapSourceAsync(new FileInfo(check)).ConfigureAwait(false);
  44. await UpdateImage.UpdateImageAsync(url, pic,
  45. Path.GetExtension(url).Contains(".gif", StringComparison.OrdinalIgnoreCase), destination)
  46. .ConfigureAwait(false);
  47. break;
  48. case "base64":
  49. await UpdateImage.UpdateImageFromBase64PicAsync(destination).ConfigureAwait(false);
  50. break;
  51. case "zip":
  52. await LoadPic.LoadPicFromArchiveAsync(check).ConfigureAwait(false);
  53. break;
  54. case "directory":
  55. case "":
  56. ConfigureWindows.GetMainWindow.Dispatcher.Invoke(DispatcherPriority.Render, () => Unload(true));
  57. return;
  58. }
  59. await ConfigureWindows.GetMainWindow.Dispatcher.InvokeAsync(() =>
  60. {
  61. // Fix not having focus after drag and drop
  62. if (!ConfigureWindows.GetMainWindow.IsFocused)
  63. {
  64. ConfigureWindows.GetMainWindow.Focus();
  65. }
  66. });
  67. FileHistoryNavigation.Add(url);
  68. Navigation.InitialPath = url;
  69. }
  70. /// <summary>
  71. /// Downloads data from the specified URL to a temporary directory and returns the path to the downloaded file.
  72. /// </summary>
  73. /// <param name="url">The URL of the data to be downloaded.</param>
  74. /// <param name="displayProgress">True if a progress display should be updated during the download, otherwise false.</param>
  75. /// <returns>The path to the downloaded file in the temporary directory.</returns>
  76. internal static async Task<string> DownloadDataAsync(string url, bool displayProgress = true)
  77. {
  78. // Create temp directory
  79. var tempPath = Path.GetTempPath();
  80. var fileName = Path.GetFileName(url);
  81. Core.FileHandling.ArchiveExtraction.CreateTempDirectory(tempPath);
  82. // Remove past "?" to not get file exceptions
  83. var index = fileName.IndexOf("?", StringComparison.InvariantCulture);
  84. if (index >= 0)
  85. {
  86. fileName = fileName[..index];
  87. }
  88. Core.FileHandling.ArchiveExtraction.TempFilePath = tempPath + fileName;
  89. using (var client = new HttpHelper.HttpClientDownloadWithProgress(url, Core.FileHandling.ArchiveExtraction.TempFilePath))
  90. {
  91. if (displayProgress) // Set up progress display
  92. {
  93. client.ProgressChanged += UpdateProgressDisplay;
  94. }
  95. await client.StartDownloadAsync().ConfigureAwait(false);
  96. }
  97. return Core.FileHandling.ArchiveExtraction.TempFilePath;
  98. }
  99. /// <summary>
  100. /// Updates the progress display during the download.
  101. /// </summary>
  102. /// <param name="totalFileSize">The total size of the file to be downloaded.</param>
  103. /// <param name="totalBytesDownloaded">The total number of bytes downloaded so far.</param>
  104. /// <param name="progressPercentage">The percentage of the download that has been completed.</param>
  105. private static void UpdateProgressDisplay(long? totalFileSize, long? totalBytesDownloaded,
  106. double? progressPercentage)
  107. {
  108. if (!totalFileSize.HasValue || !totalBytesDownloaded.HasValue || !progressPercentage.HasValue) return;
  109. var percentComplete = (string)Application.Current.Resources["PercentComplete"];
  110. var displayProgress =
  111. $"{(int)totalBytesDownloaded}/{(int)totalBytesDownloaded} {(int)progressPercentage} {percentComplete}";
  112. ConfigureWindows.GetMainWindow.Dispatcher.Invoke(DispatcherPriority.Normal, () =>
  113. {
  114. ConfigureWindows.GetMainWindow.Title = displayProgress;
  115. ConfigureWindows.GetMainWindow.TitleText.Text = displayProgress;
  116. ConfigureWindows.GetMainWindow.TitleText.ToolTip = displayProgress;
  117. });
  118. }
  119. }
  120. }