1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2024-12-16 11:37:58 +02:00
Sonarr/NzbDrone.Api/Extensions/Pipelines/GZipPipeline.cs

48 lines
1.6 KiB
C#
Raw Normal View History

2013-06-11 03:17:57 +03:00
using System.IO;
using System.IO.Compression;
using System.Linq;
using Nancy;
2013-08-20 08:53:18 +03:00
using Nancy.Bootstrapper;
2013-06-11 03:17:57 +03:00
2013-08-20 08:53:18 +03:00
namespace NzbDrone.Api.Extensions.Pipelines
2013-06-11 03:17:57 +03:00
{
2013-08-20 08:53:18 +03:00
public class GzipCompressionPipeline : IRegisterNancyPipeline
2013-06-11 03:17:57 +03:00
{
2013-08-20 08:53:18 +03:00
public void Register(IPipelines pipelines)
2013-06-11 03:17:57 +03:00
{
2013-08-20 08:53:18 +03:00
pipelines.AfterRequest.AddItemToEndOfPipeline(c => CompressResponse(c.Request, c.Response));
2013-07-07 06:56:33 +03:00
}
2013-08-20 08:53:18 +03:00
private Response CompressResponse(Request request, Response response)
2013-07-07 06:56:33 +03:00
{
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
}
}
}