2013-06-11 00:17:57 +00:00
|
|
|
|
using System.IO;
|
|
|
|
|
using System.IO.Compression;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using Nancy;
|
2013-08-20 05:53:18 +00:00
|
|
|
|
using Nancy.Bootstrapper;
|
2013-06-11 00:17:57 +00:00
|
|
|
|
|
2013-08-20 05:53:18 +00:00
|
|
|
|
namespace NzbDrone.Api.Extensions.Pipelines
|
2013-06-11 00:17:57 +00:00
|
|
|
|
{
|
2013-08-20 05:53:18 +00:00
|
|
|
|
public class GzipCompressionPipeline : IRegisterNancyPipeline
|
2013-06-11 00:17:57 +00:00
|
|
|
|
{
|
2013-08-20 05:53:18 +00:00
|
|
|
|
public void Register(IPipelines pipelines)
|
2013-06-11 00:17:57 +00:00
|
|
|
|
{
|
2013-08-20 05:53:18 +00:00
|
|
|
|
pipelines.AfterRequest.AddItemToEndOfPipeline(c => CompressResponse(c.Request, c.Response));
|
2013-07-07 03:56:33 +00:00
|
|
|
|
}
|
|
|
|
|
|
2013-08-20 05:53:18 +00:00
|
|
|
|
private Response CompressResponse(Request request, Response response)
|
2013-07-07 03:56:33 +00:00
|
|
|
|
{
|
2013-07-07 06:50:49 +00: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 00:17:57 +00:00
|
|
|
|
{
|
|
|
|
|
var data = new MemoryStream();
|
2013-07-07 03:56:33 +00:00
|
|
|
|
response.Contents.Invoke(data);
|
2013-06-11 00:17:57 +00:00
|
|
|
|
data.Position = 0;
|
|
|
|
|
if (data.Length < 1024)
|
|
|
|
|
{
|
2013-07-07 03:56:33 +00:00
|
|
|
|
response.Contents = stream =>
|
2013-06-11 00:17:57 +00:00
|
|
|
|
{
|
|
|
|
|
data.CopyTo(stream);
|
|
|
|
|
stream.Flush();
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2013-07-07 03:56:33 +00:00
|
|
|
|
response.Headers["Content-Encoding"] = "gzip";
|
|
|
|
|
response.Contents = s =>
|
2013-06-11 00:17:57 +00:00
|
|
|
|
{
|
|
|
|
|
var gzip = new GZipStream(s, CompressionMode.Compress, true);
|
|
|
|
|
data.CopyTo(gzip);
|
|
|
|
|
gzip.Close();
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
2013-07-07 03:56:33 +00:00
|
|
|
|
|
|
|
|
|
return response;
|
2013-06-11 00:17:57 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|