diff --git a/Client/FluentClientExtensions.cs b/Client/FluentClientExtensions.cs index 1a0900e..9c01ca8 100644 --- a/Client/FluentClientExtensions.cs +++ b/Client/FluentClientExtensions.cs @@ -287,6 +287,86 @@ public static IRequest WithOptions(this IRequest request, bool? ignoreHttpErrors }); } + /// Download a resource to a file path, reporting incremental download progress if requested. + /// The HTTP client. + /// The resource to download. + /// The path to save the downloaded file. + /// The buffer size to use when reading the response stream. + /// An optional progress reporter, which receives incremental progress updates (from 0 to 100) as it downloads. + /// A cancellation token. + public static async Task DownloadFileAsync(this IClient client, string resource, string path, int bufferSize = 4096, IProgress? progress = null, CancellationToken cancellationToken = default) + { + // fetch response + IResponse response = await client + .GetAsync(resource) + .WithOptions(completeWhen: HttpCompletionOption.ResponseHeadersRead) + .WithCancellationToken(cancellationToken) + .AsResponse() + .ConfigureAwait(false); + + // get content length if possible + long contentLength = response.Message.Content.Headers.ContentLength ?? 0; + + // init file + using Stream responseStream = await response.AsStream().ConfigureAwait(false); + using FileStream fileStream = File.Create(path, bufferSize); + + // stream file to disk + double lastReportedProgress = 0; + { + int bytesRead; + long totalBytesRead = 0L; + + long lastTickReported = 0; + const long throttleMilliseconds = 250; + +#if NET5_0_OR_GREATER + Memory buffer = new byte[bufferSize]; + while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) +#else + byte[] buffer = new byte[bufferSize]; + while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) +#endif + { + // stream next chunk +#if NET5_0_OR_GREATER + await fileStream.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); +#else + await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); +#endif + totalBytesRead += bytesRead; + + // get current tick + long tick = +#if NET5_0_OR_GREATER + Environment.TickCount64; +#else + Environment.TickCount; +#endif + if (tick < lastTickReported) + lastTickReported = tick; // workaround: `Environment.TickCount` eventually wraps around, which would stop any further progress updates + + // notify progress tracker + if (contentLength > 0 && tick >= lastTickReported + throttleMilliseconds) + { + double percentDownloaded = (totalBytesRead / (contentLength * 1d)) * 100; + if (percentDownloaded > 100) + percentDownloaded = 100; + + if (percentDownloaded > lastReportedProgress) + { + progress?.Report(percentDownloaded); + lastReportedProgress = percentDownloaded; + lastTickReported = tick; + } + } + } + } + + // send final progress update + if (lastReportedProgress < 100) + progress?.Report(100); + } /********* ** Internal methods diff --git a/Tests/Integration/IntegrationTests.cs b/Tests/Integration/IntegrationTests.cs index cd12e11..bdb87d6 100644 --- a/Tests/Integration/IntegrationTests.cs +++ b/Tests/Integration/IntegrationTests.cs @@ -1,7 +1,9 @@ using System; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq.Expressions; + #if NET452 using System.Net; #endif @@ -55,11 +57,20 @@ public class IntegrationTests /********* ** Unit tests *********/ + /// The setup code to before any tests in the fixture. + [OneTimeSetUp] + public void OneTimeSetUp() + { +#if NET452 + ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; +#endif + } + [Test(Description = "The client can stream a large file.")] public async Task StreamLargeFile() { // arrange - IClient client = this.ConstructClient("https://proof.ovh.net/"); + using IClient client = this.ConstructClient("https://proof.ovh.net/"); // act Stream result = await client @@ -71,15 +82,40 @@ public async Task StreamLargeFile() Assert.IsNotNull(result); } + [Test(Description = "The client can download a large file.")] + public async Task DownloadLargeFile() + { + string saveToPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + try + { + // arrange + using IClient client = this.ConstructClient("https://proof.ovh.net/"); + + // act + bool progressInvoked = false; + double lastProgressReported = 0; + await client.DownloadFileAsync("files/1Mb.dat", saveToPath, 4096, new Progress(percent => + { + Debug.WriteLine($"Download progress: {percent}%"); + progressInvoked = true; + lastProgressReported = percent; + })); + + // assert + Assert.IsTrue(progressInvoked); + Assert.AreEqual(100, lastProgressReported); + } + finally + { + File.Delete(saveToPath); + } + } + [Test(Description = "The client can fetch a resource from the English Wikipedia's API.")] public async Task EnglishWikipedia() { -#if NET452 - ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; -#endif - // arrange - IClient client = this.ConstructClient("https://en.wikipedia.org/"); + using IClient client = this.ConstructClient("https://en.wikipedia.org/"); // act WikipediaMetadata response = await client @@ -94,12 +130,8 @@ public async Task EnglishWikipedia() [Test(Description = "The client can fetch a resource from the Chinese Wikipedia's API, including proper Unicode handling.")] public async Task ChineseWikipedia() { -#if NET452 - ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; -#endif - // arrange - IClient client = this.ConstructClient("https://zh.wikipedia.org/"); + using IClient client = this.ConstructClient("https://zh.wikipedia.org/"); // act WikipediaMetadata response = await client @@ -165,4 +197,4 @@ public static TObject AssertValue(this TObject obj, Expression< Assert.AreEqual(expected, actual.Compile().Invoke(obj), "Unexpected value for " + actual.Body); return obj; } -} \ No newline at end of file +}