1
0
Fork 0
mirror of https://github.com/lidarr/Lidarr synced 2025-03-03 18:15:37 +00:00
Lidarr/NzbDrone.Api/Extensions/GZipPipeline.cs

47 lines
1.5 KiB
C#
Raw Normal View History

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