2013-06-11 03:17:57 +03:00
|
|
|
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)
|
|
|
|
{
|
2013-07-07 06:56:33 +03:00
|
|
|
context.Response.CompressResponse(context.Request);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static Response CompressResponse(this Response response, Request request)
|
|
|
|
{
|
2013-07-07 09:50:49 +03:00
|
|
|
if (!response.ContentType.Contains("image")
|
|
|
|
&& request.Headers.AcceptEncoding.Any(x => x.Contains("gzip"))
|
|
|
|
&& (!response.Headers.ContainsKey("Content-Encoding") || response.Headers["Content-Encoding"] != "gzip"))
|
2013-06-11 03:17:57 +03:00
|
|
|
{
|
|
|
|
var data = new MemoryStream();
|
2013-07-07 06:56:33 +03:00
|
|
|
response.Contents.Invoke(data);
|
2013-06-11 03:17:57 +03:00
|
|
|
data.Position = 0;
|
|
|
|
if (data.Length < 1024)
|
|
|
|
{
|
2013-07-07 06:56:33 +03:00
|
|
|
response.Contents = stream =>
|
2013-06-11 03:17:57 +03:00
|
|
|
{
|
|
|
|
data.CopyTo(stream);
|
|
|
|
stream.Flush();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2013-07-07 06:56:33 +03:00
|
|
|
response.Headers["Content-Encoding"] = "gzip";
|
|
|
|
response.Contents = s =>
|
2013-06-11 03:17:57 +03:00
|
|
|
{
|
|
|
|
var gzip = new GZipStream(s, CompressionMode.Compress, true);
|
|
|
|
data.CopyTo(gzip);
|
|
|
|
gzip.Close();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
2013-07-07 06:56:33 +03:00
|
|
|
|
|
|
|
return response;
|
2013-06-11 03:17:57 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|