made some improvements to the base http handler
This commit is contained in:
parent
19e202d5e1
commit
d8c01ded6e
|
@ -90,14 +90,15 @@ namespace MediaBrowser.Api.HttpHandlers
|
|||
}
|
||||
}
|
||||
|
||||
public override Task<string> GetContentType()
|
||||
protected override Task<ResponseInfo> GetResponseInfo()
|
||||
{
|
||||
return Task.FromResult(MimeTypes.GetMimeType("." + GetConversionOutputFormat()));
|
||||
}
|
||||
ResponseInfo info = new ResponseInfo
|
||||
{
|
||||
ContentType = MimeTypes.GetMimeType("." + GetConversionOutputFormat()),
|
||||
CompressResponse = false
|
||||
};
|
||||
|
||||
public override bool ShouldCompressResponse(string contentType)
|
||||
{
|
||||
return false;
|
||||
return Task.FromResult<ResponseInfo>(info);
|
||||
}
|
||||
|
||||
public override Task ProcessRequest(HttpListenerContext ctx)
|
||||
|
|
|
@ -7,7 +7,6 @@ using MediaBrowser.Model.Entities;
|
|||
using System;
|
||||
using System.ComponentModel.Composition;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
|
@ -82,76 +81,32 @@ namespace MediaBrowser.Api.HttpHandlers
|
|||
return ImageProcessor.GetImagePath(entity, ImageType, ImageIndex);
|
||||
}
|
||||
|
||||
public override async Task<string> GetContentType()
|
||||
{
|
||||
if (Kernel.Instance.ImageProcessors.Any(i => i.RequiresTransparency))
|
||||
{
|
||||
return MimeTypes.GetMimeType(".png");
|
||||
}
|
||||
|
||||
return MimeTypes.GetMimeType(await GetImagePath().ConfigureAwait(false));
|
||||
}
|
||||
|
||||
public override TimeSpan CacheDuration
|
||||
{
|
||||
get { return TimeSpan.FromDays(365); }
|
||||
}
|
||||
|
||||
protected override async Task<DateTime?> GetLastDateModified()
|
||||
protected async override Task<ResponseInfo> GetResponseInfo()
|
||||
{
|
||||
string path = await GetImagePath().ConfigureAwait(false);
|
||||
|
||||
DateTime date = File.GetLastWriteTimeUtc(path);
|
||||
ResponseInfo info = new ResponseInfo
|
||||
{
|
||||
CacheDuration = TimeSpan.FromDays(365),
|
||||
ContentType = MimeTypes.GetMimeType(path)
|
||||
};
|
||||
|
||||
DateTime? date = File.GetLastWriteTimeUtc(path);
|
||||
|
||||
// If the file does not exist it will return jan 1, 1601
|
||||
// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc.aspx
|
||||
if (date.Year == 1601)
|
||||
if (date.Value.Year == 1601)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
StatusCode = 404;
|
||||
return null;
|
||||
info.StatusCode = 404;
|
||||
date = null;
|
||||
}
|
||||
}
|
||||
|
||||
return await GetMostRecentDateModified(date);
|
||||
}
|
||||
info.DateLastModified = date;
|
||||
|
||||
private async Task<DateTime> GetMostRecentDateModified(DateTime imageFileLastDateModified)
|
||||
{
|
||||
var date = imageFileLastDateModified;
|
||||
|
||||
var entity = await GetSourceEntity().ConfigureAwait(false);
|
||||
|
||||
foreach (var processor in Kernel.Instance.ImageProcessors)
|
||||
{
|
||||
if (processor.IsConfiguredToProcess(entity, ImageType, ImageIndex))
|
||||
{
|
||||
if (processor.ProcessingConfigurationDateLastModifiedUtc > date)
|
||||
{
|
||||
date = processor.ProcessingConfigurationDateLastModifiedUtc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
protected override async Task<string> GetETag()
|
||||
{
|
||||
string tag = string.Empty;
|
||||
|
||||
var entity = await GetSourceEntity().ConfigureAwait(false);
|
||||
|
||||
foreach (var processor in Kernel.Instance.ImageProcessors)
|
||||
{
|
||||
if (processor.IsConfiguredToProcess(entity, ImageType, ImageIndex))
|
||||
{
|
||||
tag += processor.ProcessingConfigurationDateLastModifiedUtc.Ticks.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
return tag;
|
||||
return info;
|
||||
}
|
||||
|
||||
private int ImageIndex
|
||||
|
|
|
@ -15,8 +15,8 @@ namespace MediaBrowser.Api.HttpHandlers
|
|||
{
|
||||
return ApiService.IsApiUrlMatch("pluginassembly", request);
|
||||
}
|
||||
|
||||
public override Task<string> GetContentType()
|
||||
|
||||
protected override Task<ResponseInfo> GetResponseInfo()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
|
|
@ -17,7 +17,7 @@ namespace MediaBrowser.Api.HttpHandlers
|
|||
{
|
||||
return ApiService.IsApiUrlMatch("pluginconfiguration", request);
|
||||
}
|
||||
|
||||
|
||||
private BasePlugin _plugin;
|
||||
private BasePlugin Plugin
|
||||
{
|
||||
|
@ -39,18 +39,15 @@ namespace MediaBrowser.Api.HttpHandlers
|
|||
return Task.FromResult(Plugin.Configuration);
|
||||
}
|
||||
|
||||
public override TimeSpan CacheDuration
|
||||
protected override async Task<ResponseInfo> GetResponseInfo()
|
||||
{
|
||||
get
|
||||
{
|
||||
return TimeSpan.FromDays(7);
|
||||
}
|
||||
}
|
||||
var info = await base.GetResponseInfo().ConfigureAwait(false);
|
||||
|
||||
protected override Task<DateTime?> GetLastDateModified()
|
||||
{
|
||||
return Task.FromResult<DateTime?>(Plugin.ConfigurationDateLastModified);
|
||||
}
|
||||
info.DateLastModified = Plugin.ConfigurationDateLastModified;
|
||||
|
||||
info.CacheDuration = TimeSpan.FromDays(7);
|
||||
|
||||
return info;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,23 +16,22 @@ namespace MediaBrowser.Api.HttpHandlers
|
|||
{
|
||||
return ApiService.IsApiUrlMatch("serverconfiguration", request);
|
||||
}
|
||||
|
||||
|
||||
protected override Task<ServerConfiguration> GetObjectToSerialize()
|
||||
{
|
||||
return Task.FromResult(Kernel.Instance.Configuration);
|
||||
}
|
||||
|
||||
public override TimeSpan CacheDuration
|
||||
protected override async Task<ResponseInfo> GetResponseInfo()
|
||||
{
|
||||
get
|
||||
{
|
||||
return TimeSpan.FromDays(7);
|
||||
}
|
||||
}
|
||||
var info = await base.GetResponseInfo().ConfigureAwait(false);
|
||||
|
||||
protected override Task<DateTime?> GetLastDateModified()
|
||||
{
|
||||
return Task.FromResult<DateTime?>(File.GetLastWriteTimeUtc(Kernel.Instance.ApplicationPaths.SystemConfigurationFilePath));
|
||||
info.DateLastModified =
|
||||
File.GetLastWriteTimeUtc(Kernel.Instance.ApplicationPaths.SystemConfigurationFilePath);
|
||||
|
||||
info.CacheDuration = TimeSpan.FromDays(7);
|
||||
|
||||
return info;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ namespace MediaBrowser.Api.HttpHandlers
|
|||
{
|
||||
return ApiService.IsApiUrlMatch("weather", request);
|
||||
}
|
||||
|
||||
|
||||
protected override Task<WeatherInfo> GetObjectToSerialize()
|
||||
{
|
||||
// If a specific zip code was requested on the query string, use that. Otherwise use the value from configuration
|
||||
|
@ -31,15 +31,13 @@ namespace MediaBrowser.Api.HttpHandlers
|
|||
return Kernel.Instance.WeatherProviders.First().GetWeatherInfoAsync(zipCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tell the client to cache the weather info for 15 minutes
|
||||
/// </summary>
|
||||
public override TimeSpan CacheDuration
|
||||
protected override async Task<ResponseInfo> GetResponseInfo()
|
||||
{
|
||||
get
|
||||
{
|
||||
return TimeSpan.FromMinutes(15);
|
||||
}
|
||||
var info = await base.GetResponseInfo().ConfigureAwait(false);
|
||||
|
||||
info.CacheDuration = TimeSpan.FromMinutes(15);
|
||||
|
||||
return info;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,11 +13,6 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
|
||||
protected string ResourcePath { get; set; }
|
||||
|
||||
public override Task<string> GetContentType()
|
||||
{
|
||||
return Task.FromResult(MimeTypes.GetMimeType(ResourcePath));
|
||||
}
|
||||
|
||||
protected override Task WriteResponseToOutputStream(Stream stream)
|
||||
{
|
||||
return GetEmbeddedResourceStream().CopyToAsync(stream);
|
||||
|
|
|
@ -112,32 +112,6 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the MIME type to include in the response headers
|
||||
/// </summary>
|
||||
public abstract Task<string> GetContentType();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status code to include in the response headers
|
||||
/// </summary>
|
||||
protected int StatusCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cache duration to include in the response headers
|
||||
/// </summary>
|
||||
public virtual TimeSpan CacheDuration
|
||||
{
|
||||
get
|
||||
{
|
||||
return TimeSpan.FromTicks(0);
|
||||
}
|
||||
}
|
||||
|
||||
public virtual bool ShouldCompressResponse(string contentType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool ClientSupportsCompression
|
||||
{
|
||||
get
|
||||
|
@ -186,22 +160,21 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
ctx.Response.Headers["Accept-Ranges"] = "bytes";
|
||||
}
|
||||
|
||||
// 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;
|
||||
ResponseInfo responseInfo = await GetResponseInfo().ConfigureAwait(false);
|
||||
|
||||
ctx.Response.ContentType = await GetContentType().ConfigureAwait(false);
|
||||
|
||||
string etag = await GetETag().ConfigureAwait(false);
|
||||
|
||||
if (!string.IsNullOrEmpty(etag))
|
||||
if (responseInfo.IsResponseValid)
|
||||
{
|
||||
ctx.Response.Headers["ETag"] = etag;
|
||||
// Set the initial status code
|
||||
// When serving a range request, we need to return status code 206 to indicate a partial response body
|
||||
responseInfo.StatusCode = SupportsByteRangeRequests && IsRangeRequest ? 206 : 200;
|
||||
}
|
||||
|
||||
TimeSpan cacheDuration = CacheDuration;
|
||||
ctx.Response.ContentType = responseInfo.ContentType;
|
||||
|
||||
DateTime? lastDateModified = await GetLastDateModified().ConfigureAwait(false);
|
||||
if (!string.IsNullOrEmpty(responseInfo.Etag))
|
||||
{
|
||||
ctx.Response.Headers["ETag"] = responseInfo.Etag;
|
||||
}
|
||||
|
||||
if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since"))
|
||||
{
|
||||
|
@ -210,30 +183,26 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
if (DateTime.TryParse(ctx.Request.Headers["If-Modified-Since"], out ifModifiedSince))
|
||||
{
|
||||
// If the cache hasn't expired yet just return a 304
|
||||
if (IsCacheValid(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
|
||||
if (IsCacheValid(ifModifiedSince.ToUniversalTime(), responseInfo.CacheDuration, responseInfo.DateLastModified))
|
||||
{
|
||||
// ETag must also match (if supplied)
|
||||
if ((etag ?? string.Empty).Equals(ctx.Request.Headers["If-None-Match"] ?? string.Empty))
|
||||
if ((responseInfo.Etag ?? string.Empty).Equals(ctx.Request.Headers["If-None-Match"] ?? string.Empty))
|
||||
{
|
||||
StatusCode = 304;
|
||||
responseInfo.StatusCode = 304;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await PrepareResponse().ConfigureAwait(false);
|
||||
Logger.LogInfo("Responding with status code {0} for url {1}", responseInfo.StatusCode, url);
|
||||
|
||||
Logger.LogInfo("Responding with status code {0} for url {1}", StatusCode, url);
|
||||
|
||||
if (IsResponseValid)
|
||||
if (responseInfo.IsResponseValid)
|
||||
{
|
||||
bool compressResponse = ShouldCompressResponse(ctx.Response.ContentType) && ClientSupportsCompression;
|
||||
|
||||
await ProcessUncachedRequest(ctx, compressResponse, cacheDuration, lastDateModified).ConfigureAwait(false);
|
||||
await ProcessUncachedRequest(ctx, responseInfo).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
ctx.Response.StatusCode = StatusCode;
|
||||
ctx.Response.StatusCode = responseInfo.StatusCode;
|
||||
ctx.Response.SendChunked = false;
|
||||
}
|
||||
}
|
||||
|
@ -250,7 +219,7 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
}
|
||||
}
|
||||
|
||||
private async Task ProcessUncachedRequest(HttpListenerContext ctx, bool compressResponse, TimeSpan cacheDuration, DateTime? lastDateModified)
|
||||
private async Task ProcessUncachedRequest(HttpListenerContext ctx, ResponseInfo responseInfo)
|
||||
{
|
||||
long? totalContentLength = TotalContentLength;
|
||||
|
||||
|
@ -269,22 +238,29 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
ctx.Response.ContentLength64 = totalContentLength.Value;
|
||||
}
|
||||
|
||||
var compressResponse = responseInfo.CompressResponse && ClientSupportsCompression;
|
||||
|
||||
// Add the compression header
|
||||
if (compressResponse)
|
||||
{
|
||||
ctx.Response.AddHeader("Content-Encoding", CompressionMethod);
|
||||
}
|
||||
|
||||
// Add caching headers
|
||||
if (cacheDuration.Ticks > 0)
|
||||
if (responseInfo.DateLastModified.HasValue)
|
||||
{
|
||||
CacheResponse(ctx.Response, cacheDuration, lastDateModified);
|
||||
ctx.Response.Headers[HttpResponseHeader.LastModified] = responseInfo.DateLastModified.Value.ToString("r");
|
||||
}
|
||||
|
||||
// Add caching headers
|
||||
if (responseInfo.CacheDuration.Ticks > 0)
|
||||
{
|
||||
CacheResponse(ctx.Response, responseInfo.CacheDuration);
|
||||
}
|
||||
|
||||
// Set the status code
|
||||
ctx.Response.StatusCode = StatusCode;
|
||||
ctx.Response.StatusCode = responseInfo.StatusCode;
|
||||
|
||||
if (IsResponseValid)
|
||||
if (responseInfo.IsResponseValid)
|
||||
{
|
||||
// Finally, write the response data
|
||||
Stream outputStream = ctx.Response.OutputStream;
|
||||
|
@ -311,28 +287,10 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
}
|
||||
}
|
||||
|
||||
private void CacheResponse(HttpListenerResponse response, TimeSpan duration, DateTime? dateModified)
|
||||
private void CacheResponse(HttpListenerResponse response, TimeSpan duration)
|
||||
{
|
||||
DateTime now = DateTime.UtcNow;
|
||||
|
||||
DateTime lastModified = dateModified ?? now;
|
||||
|
||||
response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(duration.TotalSeconds);
|
||||
response.Headers[HttpResponseHeader.Expires] = now.Add(duration).ToString("r");
|
||||
response.Headers[HttpResponseHeader.LastModified] = lastModified.ToString("r");
|
||||
}
|
||||
|
||||
protected virtual Task<string> GetETag()
|
||||
{
|
||||
return Task.FromResult<string>(string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gives subclasses a chance to do any prep work, and also to validate data and set an error status code, if needed
|
||||
/// </summary>
|
||||
protected virtual Task PrepareResponse()
|
||||
{
|
||||
return Task.FromResult<object>(null);
|
||||
response.Headers[HttpResponseHeader.Expires] = DateTime.UtcNow.Add(duration).ToString("r");
|
||||
}
|
||||
|
||||
protected abstract Task WriteResponseToOutputStream(Stream stream);
|
||||
|
@ -380,20 +338,7 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
return null;
|
||||
}
|
||||
|
||||
protected virtual Task<DateTime?> GetLastDateModified()
|
||||
{
|
||||
DateTime? value = null;
|
||||
|
||||
return Task.FromResult(value);
|
||||
}
|
||||
|
||||
private bool IsResponseValid
|
||||
{
|
||||
get
|
||||
{
|
||||
return StatusCode == 200 || StatusCode == 206;
|
||||
}
|
||||
}
|
||||
protected abstract Task<ResponseInfo> GetResponseInfo();
|
||||
|
||||
private Hashtable _formValues;
|
||||
|
||||
|
@ -455,4 +400,31 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
return formVars;
|
||||
}
|
||||
}
|
||||
|
||||
public class ResponseInfo
|
||||
{
|
||||
public string ContentType { get; set; }
|
||||
public string Etag { get; set; }
|
||||
public DateTime? DateLastModified { get; set; }
|
||||
public TimeSpan CacheDuration { get; set; }
|
||||
public bool CompressResponse { get; set; }
|
||||
public int StatusCode { get; set; }
|
||||
|
||||
public ResponseInfo()
|
||||
{
|
||||
CacheDuration = TimeSpan.FromTicks(0);
|
||||
|
||||
CompressResponse = true;
|
||||
|
||||
StatusCode = 200;
|
||||
}
|
||||
|
||||
public bool IsResponseValid
|
||||
{
|
||||
get
|
||||
{
|
||||
return StatusCode == 200 || StatusCode == 206;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,12 +1,12 @@
|
|||
using System;
|
||||
using MediaBrowser.Common.Serialization;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Common.Serialization;
|
||||
|
||||
namespace MediaBrowser.Common.Net.Handlers
|
||||
{
|
||||
public abstract class BaseSerializationHandler<T> : BaseHandler
|
||||
where T : class
|
||||
where T : class
|
||||
{
|
||||
public SerializationFormat SerializationFormat
|
||||
{
|
||||
|
@ -22,61 +22,61 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
return (SerializationFormat)Enum.Parse(typeof(SerializationFormat), format, true);
|
||||
}
|
||||
}
|
||||
|
||||
public override Task<string> GetContentType()
|
||||
{
|
||||
switch (SerializationFormat)
|
||||
{
|
||||
case SerializationFormat.Jsv:
|
||||
return Task.FromResult("text/plain");
|
||||
case SerializationFormat.Protobuf:
|
||||
return Task.FromResult("application/x-protobuf");
|
||||
default:
|
||||
return Task.FromResult(MimeTypes.JsonMimeType);
|
||||
}
|
||||
}
|
||||
|
||||
private bool _objectToSerializeEnsured;
|
||||
private T _objectToSerialize;
|
||||
|
||||
private async Task EnsureObjectToSerialize()
|
||||
protected string ContentType
|
||||
{
|
||||
if (!_objectToSerializeEnsured)
|
||||
get
|
||||
{
|
||||
_objectToSerialize = await GetObjectToSerialize().ConfigureAwait(false);
|
||||
|
||||
if (_objectToSerialize == null)
|
||||
switch (SerializationFormat)
|
||||
{
|
||||
StatusCode = 404;
|
||||
case SerializationFormat.Jsv:
|
||||
return "text/plain";
|
||||
case SerializationFormat.Protobuf:
|
||||
return "application/x-protobuf";
|
||||
default:
|
||||
return MimeTypes.JsonMimeType;
|
||||
}
|
||||
|
||||
_objectToSerializeEnsured = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task<ResponseInfo> GetResponseInfo()
|
||||
{
|
||||
ResponseInfo info = new ResponseInfo
|
||||
{
|
||||
ContentType = ContentType
|
||||
};
|
||||
|
||||
_objectToSerialize = await GetObjectToSerialize().ConfigureAwait(false);
|
||||
|
||||
if (_objectToSerialize == null)
|
||||
{
|
||||
info.StatusCode = 404;
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
private T _objectToSerialize;
|
||||
|
||||
protected abstract Task<T> GetObjectToSerialize();
|
||||
|
||||
protected override Task PrepareResponse()
|
||||
protected override Task WriteResponseToOutputStream(Stream stream)
|
||||
{
|
||||
return EnsureObjectToSerialize();
|
||||
}
|
||||
|
||||
protected async override Task WriteResponseToOutputStream(Stream stream)
|
||||
{
|
||||
await EnsureObjectToSerialize().ConfigureAwait(false);
|
||||
|
||||
switch (SerializationFormat)
|
||||
return Task.Run(() =>
|
||||
{
|
||||
case SerializationFormat.Jsv:
|
||||
JsvSerializer.SerializeToStream(_objectToSerialize, stream);
|
||||
break;
|
||||
case SerializationFormat.Protobuf:
|
||||
ProtobufSerializer.SerializeToStream(_objectToSerialize, stream);
|
||||
break;
|
||||
default:
|
||||
JsonSerializer.SerializeToStream(_objectToSerialize, stream);
|
||||
break;
|
||||
}
|
||||
switch (SerializationFormat)
|
||||
{
|
||||
case SerializationFormat.Jsv:
|
||||
JsvSerializer.SerializeToStream(_objectToSerialize, stream);
|
||||
break;
|
||||
case SerializationFormat.Protobuf:
|
||||
ProtobufSerializer.SerializeToStream(_objectToSerialize, stream);
|
||||
break;
|
||||
default:
|
||||
JsonSerializer.SerializeToStream(_objectToSerialize, stream);
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -33,46 +33,7 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
}
|
||||
}
|
||||
|
||||
private bool _sourceStreamEnsured;
|
||||
private Stream _sourceStream;
|
||||
private Stream SourceStream
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureSourceStream();
|
||||
return _sourceStream;
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureSourceStream()
|
||||
{
|
||||
if (!_sourceStreamEnsured)
|
||||
{
|
||||
try
|
||||
{
|
||||
_sourceStream = File.OpenRead(Path);
|
||||
}
|
||||
catch (FileNotFoundException ex)
|
||||
{
|
||||
StatusCode = 404;
|
||||
Logger.LogException(ex);
|
||||
}
|
||||
catch (DirectoryNotFoundException ex)
|
||||
{
|
||||
StatusCode = 404;
|
||||
Logger.LogException(ex);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
StatusCode = 403;
|
||||
Logger.LogException(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sourceStreamEnsured = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
private Stream SourceStream { get; set; }
|
||||
|
||||
protected override bool SupportsByteRangeRequests
|
||||
{
|
||||
|
@ -82,7 +43,7 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
}
|
||||
}
|
||||
|
||||
public override bool ShouldCompressResponse(string contentType)
|
||||
private bool ShouldCompressResponse(string contentType)
|
||||
{
|
||||
// Can't compress these
|
||||
if (IsRangeRequest)
|
||||
|
@ -105,29 +66,41 @@ namespace MediaBrowser.Common.Net.Handlers
|
|||
return SourceStream.Length;
|
||||
}
|
||||
|
||||
protected override Task<DateTime?> GetLastDateModified()
|
||||
protected override Task<ResponseInfo> GetResponseInfo()
|
||||
{
|
||||
DateTime? value = null;
|
||||
ResponseInfo info = new ResponseInfo
|
||||
{
|
||||
ContentType = MimeTypes.GetMimeType(Path),
|
||||
};
|
||||
|
||||
EnsureSourceStream();
|
||||
try
|
||||
{
|
||||
SourceStream = File.OpenRead(Path);
|
||||
}
|
||||
catch (FileNotFoundException ex)
|
||||
{
|
||||
info.StatusCode = 404;
|
||||
Logger.LogException(ex);
|
||||
}
|
||||
catch (DirectoryNotFoundException ex)
|
||||
{
|
||||
info.StatusCode = 404;
|
||||
Logger.LogException(ex);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
info.StatusCode = 403;
|
||||
Logger.LogException(ex);
|
||||
}
|
||||
|
||||
info.CompressResponse = ShouldCompressResponse(info.ContentType);
|
||||
|
||||
if (SourceStream != null)
|
||||
{
|
||||
value = File.GetLastWriteTimeUtc(Path);
|
||||
info.DateLastModified = File.GetLastWriteTimeUtc(Path);
|
||||
}
|
||||
|
||||
return Task.FromResult(value);
|
||||
}
|
||||
|
||||
public override Task<string> GetContentType()
|
||||
{
|
||||
return Task.FromResult(MimeTypes.GetMimeType(Path));
|
||||
}
|
||||
|
||||
protected override Task PrepareResponse()
|
||||
{
|
||||
EnsureSourceStream();
|
||||
return Task.FromResult<object>(null);
|
||||
return Task.FromResult<ResponseInfo>(info);
|
||||
}
|
||||
|
||||
protected override Task WriteResponseToOutputStream(Stream stream)
|
||||
|
|
|
@ -1,102 +0,0 @@
|
|||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using System;
|
||||
using System.ComponentModel.Composition;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Drawing2D;
|
||||
|
||||
namespace MediaBrowser.Controller.Drawing
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides a base image processor class that plugins can use to process images as they are being writen to http responses
|
||||
/// Since this is completely modular with MEF, a plugin only needs to have a subclass in their assembly with the following attribute on the class:
|
||||
/// [Export(typeof(BaseImageProcessor))]
|
||||
/// This will require a reference to System.ComponentModel.Composition
|
||||
/// </summary>
|
||||
public abstract class BaseImageProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// Processes an image for a BaseEntity
|
||||
/// </summary>
|
||||
/// <param name="originalImage">The original Image, before re-sizing</param>
|
||||
/// <param name="bitmap">The bitmap holding the original image, after re-sizing</param>
|
||||
/// <param name="graphics">The graphics surface on which the output is drawn</param>
|
||||
/// <param name="entity">The entity that owns the image</param>
|
||||
/// <param name="imageType">The image type</param>
|
||||
/// <param name="imageIndex">The image index (currently only used with backdrops)</param>
|
||||
public abstract void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex);
|
||||
|
||||
/// <summary>
|
||||
/// If true, the image output format will be forced to png, resulting in an output size that will generally run larger than jpg
|
||||
/// If false, the original image format is preserved.
|
||||
/// </summary>
|
||||
public virtual bool RequiresTransparency
|
||||
{
|
||||
get
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the image processor is configured to process the specified entity, image type and image index
|
||||
/// This will aid http response caching so that we don't invalidate image caches when we don't have to
|
||||
/// </summary>
|
||||
public abstract bool IsConfiguredToProcess(BaseEntity entity, ImageType imageType, int imageIndex);
|
||||
|
||||
/// <summary>
|
||||
/// This is used for caching purposes, since a configuration change needs to invalidate a user's image cache
|
||||
/// If the image processor is hosted within a plugin then this should be the plugin ConfigurationDateLastModified
|
||||
/// </summary>
|
||||
public abstract DateTime ProcessingConfigurationDateLastModifiedUtc { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is demo-ware and should be deleted eventually
|
||||
/// </summary>
|
||||
//[Export(typeof(BaseImageProcessor))]
|
||||
public class MyRoundedCornerImageProcessor : BaseImageProcessor
|
||||
{
|
||||
public override void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex)
|
||||
{
|
||||
var CornerRadius = 20;
|
||||
|
||||
graphics.Clear(Color.Transparent);
|
||||
|
||||
using (GraphicsPath gp = new GraphicsPath())
|
||||
{
|
||||
gp.AddArc(0, 0, CornerRadius, CornerRadius, 180, 90);
|
||||
gp.AddArc(0 + bitmap.Width - CornerRadius, 0, CornerRadius, CornerRadius, 270, 90);
|
||||
gp.AddArc(0 + bitmap.Width - CornerRadius, 0 + bitmap.Height - CornerRadius, CornerRadius, CornerRadius, 0, 90);
|
||||
gp.AddArc(0, 0 + bitmap.Height - CornerRadius, CornerRadius, CornerRadius, 90, 90);
|
||||
|
||||
graphics.SetClip(gp);
|
||||
graphics.DrawImage(originalImage, 0, 0, bitmap.Width, bitmap.Height);
|
||||
}
|
||||
}
|
||||
|
||||
public override bool RequiresTransparency
|
||||
{
|
||||
get
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static DateTime testDate = DateTime.UtcNow;
|
||||
|
||||
public override DateTime ProcessingConfigurationDateLastModifiedUtc
|
||||
{
|
||||
get
|
||||
{
|
||||
// This will result in a situation where images are only cached throughout a server session, but again, this is a prototype
|
||||
return testDate;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool IsConfiguredToProcess(BaseEntity entity, ImageType imageType, int imageIndex)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -59,17 +59,6 @@ namespace MediaBrowser.Controller.Drawing
|
|||
|
||||
ImageFormat outputFormat = originalImage.RawFormat;
|
||||
|
||||
// Run Kernel image processors
|
||||
if (Kernel.Instance.ImageProcessors.Any())
|
||||
{
|
||||
ExecuteAdditionalImageProcessors(originalImage, thumbnail, thumbnailGraph, entity, imageType, imageIndex);
|
||||
|
||||
if (Kernel.Instance.ImageProcessors.Any(i => i.RequiresTransparency))
|
||||
{
|
||||
outputFormat = ImageFormat.Png;
|
||||
}
|
||||
}
|
||||
|
||||
// Write to the output stream
|
||||
SaveImage(outputFormat, thumbnail, toStream, quality);
|
||||
|
||||
|
@ -109,27 +98,6 @@ namespace MediaBrowser.Controller.Drawing
|
|||
return entity.PrimaryImagePath;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Executes additional image processors that are registered with the Kernel
|
||||
/// </summary>
|
||||
/// <param name="originalImage">The original Image, before re-sizing</param>
|
||||
/// <param name="bitmap">The bitmap holding the original image, after re-sizing</param>
|
||||
/// <param name="graphics">The graphics surface on which the output is drawn</param>
|
||||
/// <param name="entity">The entity that owns the image</param>
|
||||
/// <param name="imageType">The image type</param>
|
||||
/// <param name="imageIndex">The image index (currently only used with backdrops)</param>
|
||||
private static void ExecuteAdditionalImageProcessors(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex)
|
||||
{
|
||||
foreach (var processor in Kernel.Instance.ImageProcessors)
|
||||
{
|
||||
if (processor.IsConfiguredToProcess(entity, imageType, imageIndex))
|
||||
{
|
||||
processor.ProcessImage(originalImage, bitmap, graphics, entity, imageType, imageIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void SaveImage(ImageFormat outputFormat, Image newImage, Stream toStream, int? quality)
|
||||
{
|
||||
// Use special save methods for jpeg and png that will result in a much higher quality image
|
||||
|
|
|
@ -77,12 +77,6 @@ namespace MediaBrowser.Controller
|
|||
/// </summary>
|
||||
internal IBaseItemResolver[] EntityResolvers { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of currently registered entity resolvers
|
||||
/// </summary>
|
||||
[ImportMany(typeof(BaseImageProcessor))]
|
||||
public IEnumerable<BaseImageProcessor> ImageProcessors { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a kernel based on a Data path, which is akin to our current programdata path
|
||||
/// </summary>
|
||||
|
|
|
@ -59,7 +59,6 @@
|
|||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Drawing\BaseImageProcessor.cs" />
|
||||
<Compile Include="Drawing\DrawingUtils.cs" />
|
||||
<Compile Include="Drawing\ImageProcessor.cs" />
|
||||
<Compile Include="Entities\Audio.cs" />
|
||||
|
|
Loading…
Reference in New Issue
Block a user