From 9d8fd840c4f980a2b36bde402e04a52de5ec2212 Mon Sep 17 00:00:00 2001 From: Keivan Beigi Date: Mon, 10 Jun 2013 17:17:57 -0700 Subject: [PATCH] added gzip after pipeline --- NzbDrone.Api/Extensions/GZipPipeline.cs | 38 +++++++++++++++++++++++++ NzbDrone.Api/NancyBootstrapper.cs | 1 + NzbDrone.Api/NzbDrone.Api.csproj | 1 + 3 files changed, 40 insertions(+) create mode 100644 NzbDrone.Api/Extensions/GZipPipeline.cs diff --git a/NzbDrone.Api/Extensions/GZipPipeline.cs b/NzbDrone.Api/Extensions/GZipPipeline.cs new file mode 100644 index 000000000..86767f2e4 --- /dev/null +++ b/NzbDrone.Api/Extensions/GZipPipeline.cs @@ -0,0 +1,38 @@ +using System.IO; +using System.IO.Compression; +using System.Linq; +using Nancy; + +namespace NzbDrone.Api.Extensions +{ + public static class GzipCompressionPipeline + { + public static void Handle(NancyContext context) + { + if (!context.Response.ContentType.Contains("image") && context.Request.Headers.AcceptEncoding.Any(x => x.Contains("gzip"))) + { + var data = new MemoryStream(); + context.Response.Contents.Invoke(data); + data.Position = 0; + if (data.Length < 1024) + { + context.Response.Contents = stream => + { + data.CopyTo(stream); + stream.Flush(); + }; + } + else + { + context.Response.Headers["Content-Encoding"] = "gzip"; + context.Response.Contents = s => + { + var gzip = new GZipStream(s, CompressionMode.Compress, true); + data.CopyTo(gzip); + gzip.Close(); + }; + } + } + } + } +} \ No newline at end of file diff --git a/NzbDrone.Api/NancyBootstrapper.cs b/NzbDrone.Api/NancyBootstrapper.cs index 01128eff9..400817880 100644 --- a/NzbDrone.Api/NancyBootstrapper.cs +++ b/NzbDrone.Api/NancyBootstrapper.cs @@ -38,6 +38,7 @@ namespace NzbDrone.Api container.Resolve().Register(pipelines); container.Resolve().PublishEvent(new ApplicationStartedEvent()); + pipelines.AfterRequest.AddItemToStartOfPipeline(GzipCompressionPipeline.Handle); ApplicationPipelines.OnError.AddItemToEndOfPipeline(container.Resolve().HandleException); } diff --git a/NzbDrone.Api/NzbDrone.Api.csproj b/NzbDrone.Api/NzbDrone.Api.csproj index 92621ce49..24ab92ec1 100644 --- a/NzbDrone.Api/NzbDrone.Api.csproj +++ b/NzbDrone.Api/NzbDrone.Api.csproj @@ -102,6 +102,7 @@ +