2012-07-19 19:22:44 -07:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Collections.Specialized;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.IO.Compression;
|
2012-08-10 06:07:58 -07:00
|
|
|
|
using System.Linq;
|
2012-08-09 05:59:54 -07:00
|
|
|
|
using System.Net;
|
2012-08-11 11:07:07 -07:00
|
|
|
|
using System.Threading.Tasks;
|
2012-08-10 06:07:58 -07:00
|
|
|
|
using MediaBrowser.Common.Logging;
|
2012-07-19 19:22:44 -07:00
|
|
|
|
|
2012-07-21 11:39:47 -07:00
|
|
|
|
namespace MediaBrowser.Common.Net.Handlers
|
2012-07-19 19:22:44 -07:00
|
|
|
|
{
|
|
|
|
|
public abstract class BaseHandler
|
|
|
|
|
{
|
2012-08-09 05:41:54 -07:00
|
|
|
|
private Stream CompressedStream { get; set; }
|
|
|
|
|
|
2012-08-10 06:07:58 -07:00
|
|
|
|
public virtual bool? UseChunkedEncoding
|
2012-08-06 15:10:07 -07:00
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
return null;
|
2012-08-06 15:10:07 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-10 06:07:58 -07:00
|
|
|
|
private bool _TotalContentLengthDiscovered = false;
|
|
|
|
|
private long? _TotalContentLength = null;
|
|
|
|
|
public long? TotalContentLength
|
2012-08-06 15:10:07 -07:00
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
if (!_TotalContentLengthDiscovered)
|
|
|
|
|
{
|
|
|
|
|
_TotalContentLength = GetTotalContentLength();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return _TotalContentLength;
|
2012-08-06 15:10:07 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-10 06:07:58 -07:00
|
|
|
|
protected virtual bool SupportsByteRangeRequests
|
2012-08-06 06:21:56 -07:00
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
return false;
|
2012-08-06 06:21:56 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
2012-07-19 19:22:44 -07:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
2012-08-10 06:07:58 -07:00
|
|
|
|
/// The original HttpListenerContext
|
2012-07-19 19:22:44 -07:00
|
|
|
|
/// </summary>
|
2012-08-10 20:06:25 -07:00
|
|
|
|
protected HttpListenerContext HttpListenerContext { get; set; }
|
2012-07-19 19:22:44 -07:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The original QueryString
|
|
|
|
|
/// </summary>
|
|
|
|
|
protected NameValueCollection QueryString
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
return HttpListenerContext.Request.QueryString;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected List<KeyValuePair<long, long?>> _RequestedRanges = null;
|
|
|
|
|
protected IEnumerable<KeyValuePair<long, long?>> RequestedRanges
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
if (_RequestedRanges == null)
|
|
|
|
|
{
|
|
|
|
|
_RequestedRanges = new List<KeyValuePair<long, long?>>();
|
|
|
|
|
|
|
|
|
|
if (IsRangeRequest)
|
|
|
|
|
{
|
|
|
|
|
// Example: bytes=0-,32-63
|
|
|
|
|
string[] ranges = HttpListenerContext.Request.Headers["Range"].Split('=')[1].Split(',');
|
|
|
|
|
|
|
|
|
|
foreach (string range in ranges)
|
|
|
|
|
{
|
|
|
|
|
string[] vals = range.Split('-');
|
|
|
|
|
|
|
|
|
|
long start = 0;
|
|
|
|
|
long? end = null;
|
|
|
|
|
|
|
|
|
|
if (!string.IsNullOrEmpty(vals[0]))
|
|
|
|
|
{
|
|
|
|
|
start = long.Parse(vals[0]);
|
|
|
|
|
}
|
|
|
|
|
if (!string.IsNullOrEmpty(vals[1]))
|
|
|
|
|
{
|
|
|
|
|
end = long.Parse(vals[1]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_RequestedRanges.Add(new KeyValuePair<long, long?>(start, end));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return _RequestedRanges;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected bool IsRangeRequest
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
return HttpListenerContext.Request.Headers.AllKeys.Contains("Range");
|
2012-07-19 19:22:44 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Gets the MIME type to include in the response headers
|
|
|
|
|
/// </summary>
|
2012-08-19 13:38:31 -07:00
|
|
|
|
public abstract Task<string> GetContentType();
|
2012-07-19 19:22:44 -07:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Gets the status code to include in the response headers
|
|
|
|
|
/// </summary>
|
2012-08-10 06:07:58 -07:00
|
|
|
|
protected int StatusCode { get; set; }
|
2012-07-19 19:22:44 -07:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Gets the cache duration to include in the response headers
|
|
|
|
|
/// </summary>
|
|
|
|
|
public virtual TimeSpan CacheDuration
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
return TimeSpan.FromTicks(0);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-19 13:38:31 -07:00
|
|
|
|
public virtual bool ShouldCompressResponse(string contentType)
|
2012-07-19 19:22:44 -07:00
|
|
|
|
{
|
2012-08-19 13:38:31 -07:00
|
|
|
|
return true;
|
2012-07-19 19:22:44 -07:00
|
|
|
|
}
|
|
|
|
|
|
2012-08-09 05:59:54 -07:00
|
|
|
|
private bool ClientSupportsCompression
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
|
2012-08-09 05:59:54 -07:00
|
|
|
|
|
|
|
|
|
return enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1 || enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private string CompressionMethod
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
|
2012-08-09 05:59:54 -07:00
|
|
|
|
|
|
|
|
|
if (enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
|
|
|
|
|
{
|
|
|
|
|
return "deflate";
|
|
|
|
|
}
|
|
|
|
|
if (enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
|
|
|
|
|
{
|
|
|
|
|
return "gzip";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
public virtual async Task ProcessRequest(HttpListenerContext ctx)
|
2012-08-09 05:59:54 -07:00
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
HttpListenerContext = ctx;
|
|
|
|
|
|
|
|
|
|
Logger.LogInfo("Http Server received request at: " + ctx.Request.Url.ToString());
|
|
|
|
|
Logger.LogInfo("Http Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
|
|
|
|
|
|
|
|
|
|
ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
|
|
|
|
|
|
|
|
|
|
ctx.Response.KeepAlive = true;
|
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
try
|
2012-08-09 05:59:54 -07:00
|
|
|
|
{
|
2012-08-15 06:20:29 -07:00
|
|
|
|
if (SupportsByteRangeRequests && IsRangeRequest)
|
|
|
|
|
{
|
|
|
|
|
ctx.Response.Headers["Accept-Ranges"] = "bytes";
|
|
|
|
|
}
|
2012-08-10 06:07:58 -07:00
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
// Set the initial status code
|
|
|
|
|
// When serving a range request, we need to return status code 206 to indicate a partial response body
|
|
|
|
|
StatusCode = SupportsByteRangeRequests && IsRangeRequest ? 206 : 200;
|
2012-08-09 05:59:54 -07:00
|
|
|
|
|
2012-08-21 19:50:59 -07:00
|
|
|
|
ctx.Response.ContentType = await GetContentType().ConfigureAwait(false);
|
2012-08-10 06:07:58 -07:00
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
TimeSpan cacheDuration = CacheDuration;
|
2012-08-10 06:07:58 -07:00
|
|
|
|
|
2012-08-21 19:50:59 -07:00
|
|
|
|
DateTime? lastDateModified = await GetLastDateModified().ConfigureAwait(false);
|
2012-08-19 13:38:31 -07:00
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since"))
|
2012-08-10 06:07:58 -07:00
|
|
|
|
{
|
2012-08-15 06:20:29 -07:00
|
|
|
|
DateTime ifModifiedSince;
|
|
|
|
|
|
|
|
|
|
if (DateTime.TryParse(ctx.Request.Headers["If-Modified-Since"].Replace(" GMT", string.Empty), out ifModifiedSince))
|
2012-08-10 06:07:58 -07:00
|
|
|
|
{
|
2012-08-15 06:20:29 -07:00
|
|
|
|
// If the cache hasn't expired yet just return a 304
|
2012-08-19 13:38:31 -07:00
|
|
|
|
if (IsCacheValid(ifModifiedSince, cacheDuration, lastDateModified))
|
2012-08-15 06:20:29 -07:00
|
|
|
|
{
|
|
|
|
|
StatusCode = 304;
|
|
|
|
|
}
|
2012-08-10 06:07:58 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
2012-08-09 05:59:54 -07:00
|
|
|
|
|
2012-08-21 19:50:59 -07:00
|
|
|
|
await PrepareResponse().ConfigureAwait(false);
|
2012-08-15 06:20:29 -07:00
|
|
|
|
|
|
|
|
|
if (IsResponseValid)
|
|
|
|
|
{
|
2012-08-19 13:38:31 -07:00
|
|
|
|
bool compressResponse = ShouldCompressResponse(ctx.Response.ContentType) && ClientSupportsCompression;
|
|
|
|
|
|
2012-08-21 19:50:59 -07:00
|
|
|
|
await ProcessUncachedRequest(ctx, compressResponse, cacheDuration, lastDateModified).ConfigureAwait(false);
|
2012-08-15 06:20:29 -07:00
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
ctx.Response.StatusCode = StatusCode;
|
|
|
|
|
ctx.Response.SendChunked = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
2012-08-09 05:59:54 -07:00
|
|
|
|
{
|
2012-08-15 06:20:29 -07:00
|
|
|
|
// It might be too late if some response data has already been transmitted, but try to set this
|
|
|
|
|
ctx.Response.StatusCode = 500;
|
2012-08-19 13:38:31 -07:00
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
Logger.LogException(ex);
|
2012-08-09 05:59:54 -07:00
|
|
|
|
}
|
2012-08-15 06:20:29 -07:00
|
|
|
|
finally
|
2012-08-09 05:59:54 -07:00
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
DisposeResponseStream();
|
2012-08-09 05:59:54 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-19 13:38:31 -07:00
|
|
|
|
private async Task ProcessUncachedRequest(HttpListenerContext ctx, bool compressResponse, TimeSpan cacheDuration, DateTime? lastDateModified)
|
2012-08-09 05:59:54 -07:00
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
long? totalContentLength = TotalContentLength;
|
2012-08-09 05:59:54 -07:00
|
|
|
|
|
2012-08-10 06:07:58 -07:00
|
|
|
|
// By default, use chunked encoding if we don't know the content length
|
|
|
|
|
bool useChunkedEncoding = UseChunkedEncoding == null ? (totalContentLength == null) : UseChunkedEncoding.Value;
|
2012-08-09 05:59:54 -07:00
|
|
|
|
|
2012-08-10 06:07:58 -07:00
|
|
|
|
// Don't force this to true. HttpListener will default it to true if supported by the client.
|
|
|
|
|
if (!useChunkedEncoding)
|
|
|
|
|
{
|
|
|
|
|
ctx.Response.SendChunked = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Set the content length, if we know it
|
|
|
|
|
if (totalContentLength.HasValue)
|
|
|
|
|
{
|
|
|
|
|
ctx.Response.ContentLength64 = totalContentLength.Value;
|
|
|
|
|
}
|
2012-08-09 05:59:54 -07:00
|
|
|
|
|
2012-08-10 06:07:58 -07:00
|
|
|
|
// Add the compression header
|
2012-08-19 13:38:31 -07:00
|
|
|
|
if (compressResponse)
|
2012-07-19 19:22:44 -07:00
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
ctx.Response.AddHeader("Content-Encoding", CompressionMethod);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add caching headers
|
|
|
|
|
if (cacheDuration.Ticks > 0)
|
|
|
|
|
{
|
2012-08-19 13:38:31 -07:00
|
|
|
|
CacheResponse(ctx.Response, cacheDuration, lastDateModified);
|
2012-08-10 06:07:58 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Set the status code
|
|
|
|
|
ctx.Response.StatusCode = StatusCode;
|
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
if (IsResponseValid)
|
2012-08-10 06:07:58 -07:00
|
|
|
|
{
|
|
|
|
|
// Finally, write the response data
|
|
|
|
|
Stream outputStream = ctx.Response.OutputStream;
|
|
|
|
|
|
2012-08-19 13:38:31 -07:00
|
|
|
|
if (compressResponse)
|
2012-08-09 05:59:54 -07:00
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
if (CompressionMethod.Equals("deflate", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
CompressedStream = new DeflateStream(outputStream, CompressionLevel.Fastest, false);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
CompressedStream = new GZipStream(outputStream, CompressionLevel.Fastest, false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
outputStream = CompressedStream;
|
2012-08-09 05:59:54 -07:00
|
|
|
|
}
|
2012-08-10 06:07:58 -07:00
|
|
|
|
|
2012-08-21 19:50:59 -07:00
|
|
|
|
await WriteResponseToOutputStream(outputStream).ConfigureAwait(false);
|
2012-07-19 19:22:44 -07:00
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2012-08-10 06:07:58 -07:00
|
|
|
|
ctx.Response.SendChunked = false;
|
2012-07-19 19:22:44 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-10 06:07:58 -07:00
|
|
|
|
private void CacheResponse(HttpListenerResponse response, TimeSpan duration, DateTime? dateModified)
|
|
|
|
|
{
|
|
|
|
|
DateTime lastModified = dateModified ?? DateTime.Now;
|
|
|
|
|
|
|
|
|
|
response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(duration.TotalSeconds);
|
|
|
|
|
response.Headers[HttpResponseHeader.Expires] = DateTime.Now.Add(duration).ToString("r");
|
|
|
|
|
response.Headers[HttpResponseHeader.LastModified] = lastModified.ToString("r");
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
/// <summary>
|
2012-08-19 13:38:31 -07:00
|
|
|
|
/// Gives subclasses a chance to do any prep work, and also to validate data and set an error status code, if needed
|
2012-08-15 06:20:29 -07:00
|
|
|
|
/// </summary>
|
2012-08-19 13:38:31 -07:00
|
|
|
|
protected virtual Task PrepareResponse()
|
2012-08-15 06:20:29 -07:00
|
|
|
|
{
|
2012-08-21 19:50:59 -07:00
|
|
|
|
return Task.FromResult<object>(null);
|
2012-08-15 06:20:29 -07:00
|
|
|
|
}
|
|
|
|
|
|
2012-08-11 11:07:07 -07:00
|
|
|
|
protected abstract Task WriteResponseToOutputStream(Stream stream);
|
2012-07-19 19:22:44 -07:00
|
|
|
|
|
2012-08-15 06:20:29 -07:00
|
|
|
|
protected virtual void DisposeResponseStream()
|
2012-08-09 05:41:54 -07:00
|
|
|
|
{
|
|
|
|
|
if (CompressedStream != null)
|
|
|
|
|
{
|
|
|
|
|
CompressedStream.Dispose();
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-10 06:07:58 -07:00
|
|
|
|
HttpListenerContext.Response.OutputStream.Dispose();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private bool IsCacheValid(DateTime ifModifiedSince, TimeSpan cacheDuration, DateTime? dateModified)
|
|
|
|
|
{
|
|
|
|
|
if (dateModified.HasValue)
|
|
|
|
|
{
|
|
|
|
|
DateTime lastModified = NormalizeDateForComparison(dateModified.Value);
|
|
|
|
|
ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
|
|
|
|
|
|
|
|
|
|
return lastModified <= ifModifiedSince;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
DateTime cacheExpirationDate = ifModifiedSince.Add(cacheDuration);
|
|
|
|
|
|
|
|
|
|
if (DateTime.Now < cacheExpirationDate)
|
|
|
|
|
{
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
|
|
|
|
|
/// </summary>
|
|
|
|
|
private DateTime NormalizeDateForComparison(DateTime date)
|
|
|
|
|
{
|
|
|
|
|
return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected virtual long? GetTotalContentLength()
|
|
|
|
|
{
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-19 13:38:31 -07:00
|
|
|
|
protected virtual Task<DateTime?> GetLastDateModified()
|
2012-08-10 06:07:58 -07:00
|
|
|
|
{
|
2012-08-19 13:38:31 -07:00
|
|
|
|
DateTime? value = null;
|
|
|
|
|
|
2012-08-21 19:50:59 -07:00
|
|
|
|
return Task.FromResult<DateTime?>(value);
|
2012-08-09 05:41:54 -07:00
|
|
|
|
}
|
2012-08-15 06:20:29 -07:00
|
|
|
|
|
|
|
|
|
private bool IsResponseValid
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
return StatusCode == 200 || StatusCode == 206;
|
|
|
|
|
}
|
|
|
|
|
}
|
2012-07-19 19:22:44 -07:00
|
|
|
|
}
|
|
|
|
|
}
|