using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using PluginManager.Others;
namespace PluginManager.Online.Helpers;
internal static class OnlineFunctions
{
///
/// Downloads a and saves it to another .
///
/// The that is used to download the file
/// The url to the file
/// The to save the downloaded data
/// The that is used to track the download progress
/// The cancellation token
///
internal static async Task DownloadFileAsync(this HttpClient client, string url, Stream destination,
IProgress? progress = null,
IProgress? downloadedBytes = null, int bufferSize = 81920,
CancellationToken cancellation = default)
{
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation))
{
var contentLength = response.Content.Headers.ContentLength;
using (var download = await response.Content.ReadAsStreamAsync(cancellation))
{
// Ignore progress reporting when no progress reporter was
// passed or when the content length is unknown
if (progress == null || !contentLength.HasValue)
{
await download.CopyToAsync(destination, cancellation);
return;
}
// Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
var relativeProgress = new Progress(totalBytes =>
{
progress?.Report((float)totalBytes / contentLength.Value * 100);
downloadedBytes?.Report(totalBytes);
}
);
// Use extension method to report progress while downloading
await download.CopyToOtherStreamAsync(destination, bufferSize, relativeProgress, cancellation);
progress.Report(100);
}
}
}
///
/// Read contents of a file as string from specified URL
///
/// The URL to read from
/// The cancellation token
///
internal static async Task DownloadStringAsync(string url, CancellationToken cancellation = default)
{
using var client = new HttpClient();
return await client.GetStringAsync(url, cancellation);
}
}