From 8b7effd6ff1694688e93d03a48c5dcddb4efe4f0 Mon Sep 17 00:00:00 2001 From: LukePulverenti Luke Pulverenti luke pulverenti Date: Tue, 18 Sep 2012 15:33:57 -0400 Subject: Moved discovery of loggers and weather providers to MEF. Also added support for third-party image processors, also discovered through MEF. --- MediaBrowser.Controller/Drawing/ImageProcessor.cs | 148 ++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 MediaBrowser.Controller/Drawing/ImageProcessor.cs (limited to 'MediaBrowser.Controller/Drawing/ImageProcessor.cs') diff --git a/MediaBrowser.Controller/Drawing/ImageProcessor.cs b/MediaBrowser.Controller/Drawing/ImageProcessor.cs new file mode 100644 index 000000000..b7815750b --- /dev/null +++ b/MediaBrowser.Controller/Drawing/ImageProcessor.cs @@ -0,0 +1,148 @@ +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Entities; +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; + +namespace MediaBrowser.Controller.Drawing +{ + public static class ImageProcessor + { + /// + /// Processes an image by resizing to target dimensions + /// + /// The stream containing the source image + /// The stream to save the new image to + /// Use if a fixed width is required. Aspect ratio will be preserved. + /// Use if a fixed height is required. Aspect ratio will be preserved. + /// Use if a max width is required. Aspect ratio will be preserved. + /// Use if a max height is required. Aspect ratio will be preserved. + /// Quality level, from 0-100. Currently only applies to JPG. The default value should suffice. + /// The entity that owns the image + /// The image type + /// The image index (currently only used with backdrops) + public static void ProcessImage(Stream sourceImageStream, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality, BaseEntity entity, ImageType imageType, int imageIndex) + { + Image originalImage = Image.FromStream(sourceImageStream); + + // Determine the output size based on incoming parameters + Size newSize = DrawingUtils.Resize(originalImage.Size, width, height, maxWidth, maxHeight); + + Bitmap thumbnail; + + // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here + if (originalImage.PixelFormat.HasFlag(PixelFormat.Indexed)) + { + thumbnail = new Bitmap(originalImage, newSize.Width, newSize.Height); + } + else + { + thumbnail = new Bitmap(newSize.Width, newSize.Height, originalImage.PixelFormat); + } + + // Preserve the original resolution + thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution); + + Graphics thumbnailGraph = Graphics.FromImage(thumbnail); + + thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality; + thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; + thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; + thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality; + thumbnailGraph.CompositingMode = CompositingMode.SourceOver; + + thumbnailGraph.DrawImage(originalImage, 0, 0, newSize.Width, newSize.Height); + + // Run Kernel image processors + if (Kernel.Instance.ImageProcessors.Any()) + { + ExecuteAdditionalImageProcessors(thumbnail, thumbnailGraph, entity, imageType, imageIndex); + } + + // Write to the output stream + SaveImage(originalImage.RawFormat, thumbnail, toStream, quality); + + thumbnailGraph.Dispose(); + thumbnail.Dispose(); + originalImage.Dispose(); + } + + /// + /// Executes additional image processors that are registered with the Kernel + /// + /// The bitmap holding the original image, after re-sizing + /// The graphics surface on which the output is drawn + /// The entity that owns the image + /// The image type + /// The image index (currently only used with backdrops) + private static void ExecuteAdditionalImageProcessors(Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex) + { + var baseItem = entity as BaseItem; + + if (baseItem != null) + { + foreach (var processor in Kernel.Instance.ImageProcessors) + { + processor.ProcessImage(bitmap, graphics, baseItem, imageType, imageIndex); + } + } + else + { + foreach (var processor in Kernel.Instance.ImageProcessors) + { + processor.ProcessImage(bitmap, graphics, entity); + } + } + } + + public static void SaveImage(ImageFormat originalImageRawFormat, Image newImage, Stream toStream, int? quality) + { + // Use special save methods for jpeg and png that will result in a much higher quality image + // All other formats use the generic Image.Save + if (ImageFormat.Jpeg.Equals(originalImageRawFormat)) + { + SaveJpeg(newImage, toStream, quality); + } + else if (ImageFormat.Png.Equals(originalImageRawFormat)) + { + newImage.Save(toStream, ImageFormat.Png); + } + else + { + newImage.Save(toStream, originalImageRawFormat); + } + } + + public static void SaveJpeg(Image image, Stream target, int? quality) + { + if (!quality.HasValue) + { + quality = 90; + } + + using (var encoderParameters = new EncoderParameters(1)) + { + encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality.Value); + image.Save(target, GetImageCodecInfo("image/jpeg"), encoderParameters); + } + } + + public static ImageCodecInfo GetImageCodecInfo(string mimeType) + { + ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders(); + + for (int i = 0; i < info.Length; i++) + { + ImageCodecInfo ici = info[i]; + if (ici.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase)) + { + return ici; + } + } + return info[1]; + } + } +} -- cgit v1.2.3 From e76ff3bf160dc90968a5530b7477daaff67480b8 Mon Sep 17 00:00:00 2001 From: LukePulverenti Luke Pulverenti luke pulverenti Date: Tue, 18 Sep 2012 17:39:42 -0400 Subject: Improved image processing --- MediaBrowser.Api/HttpHandlers/ImageHandler.cs | 8 +++- .../Drawing/BaseImageProcessor.cs | 56 +++++++++++++++++++++- MediaBrowser.Controller/Drawing/ImageProcessor.cs | 27 +++++++---- MediaBrowser.Controller/Kernel.cs | 2 +- 4 files changed, 80 insertions(+), 13 deletions(-) (limited to 'MediaBrowser.Controller/Drawing/ImageProcessor.cs') diff --git a/MediaBrowser.Api/HttpHandlers/ImageHandler.cs b/MediaBrowser.Api/HttpHandlers/ImageHandler.cs index 73098c71b..da20e0533 100644 --- a/MediaBrowser.Api/HttpHandlers/ImageHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/ImageHandler.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Common.Logging; +using System.Drawing.Imaging; +using MediaBrowser.Common.Logging; using MediaBrowser.Common.Net; using MediaBrowser.Common.Net.Handlers; using MediaBrowser.Controller; @@ -128,6 +129,11 @@ namespace MediaBrowser.Api.HttpHandlers return null; } + if (Kernel.Instance.ImageProcessors.Any(i => i.RequiresTransparency)) + { + return MimeTypes.GetMimeType(".png"); + } + return MimeTypes.GetMimeType(await GetImagePath().ConfigureAwait(false)); } diff --git a/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs b/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs index a2b223a70..ebd0e22c8 100644 --- a/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs @@ -1,6 +1,8 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Entities; +using System.ComponentModel.Composition; using System.Drawing; +using System.Drawing.Drawing2D; namespace MediaBrowser.Controller.Drawing { @@ -15,19 +17,69 @@ namespace MediaBrowser.Controller.Drawing /// /// Processes the primary image for a BaseEntity (Person, Studio, User, etc) /// + /// The original Image, before re-sizing /// The bitmap holding the original image, after re-sizing /// The graphics surface on which the output is drawn /// The entity that owns the image - public abstract void ProcessImage(Bitmap bitmap, Graphics graphics, BaseEntity entity); + public abstract void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity); /// /// Processes an image for a BaseItem /// + /// The original Image, before re-sizing /// The bitmap holding the original image, after re-sizing /// The graphics surface on which the output is drawn /// The entity that owns the image /// The image type /// The image index (currently only used with backdrops) - public abstract void ProcessImage(Bitmap bitmap, Graphics graphics, BaseItem entity, ImageType imageType, int imageIndex); + public abstract void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseItem entity, ImageType imageType, int imageIndex); + + /// + /// If true, the image output format will be forced to png, resulting in an output size that will generally run larger than jpg + /// + public virtual bool RequiresTransparency + { + get + { + return false; + } + } + } + + /// + /// This is demo-ware and should be deleted eventually + /// + //[Export(typeof(BaseImageProcessor))] + public class MyRoundedCornerImageProcessor : BaseImageProcessor + { + public override void ProcessImage(Image originalImage, Bitmap bitmap, Graphics g, BaseEntity entity) + { + var CornerRadius = 20; + + g.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); + + g.SetClip(gp); + g.DrawImage(originalImage, 0, 0, bitmap.Width, bitmap.Height); + } + } + + public override void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseItem entity, ImageType imageType, int imageIndex) + { + } + + public override bool RequiresTransparency + { + get + { + return true; + } + } } } diff --git a/MediaBrowser.Controller/Drawing/ImageProcessor.cs b/MediaBrowser.Controller/Drawing/ImageProcessor.cs index b7815750b..f9b6366c6 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessor.cs @@ -43,6 +43,8 @@ namespace MediaBrowser.Controller.Drawing thumbnail = new Bitmap(newSize.Width, newSize.Height, originalImage.PixelFormat); } + thumbnail.MakeTransparent(); + // Preserve the original resolution thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution); @@ -56,14 +58,21 @@ namespace MediaBrowser.Controller.Drawing thumbnailGraph.DrawImage(originalImage, 0, 0, newSize.Width, newSize.Height); + ImageFormat outputFormat = originalImage.RawFormat; + // Run Kernel image processors if (Kernel.Instance.ImageProcessors.Any()) { - ExecuteAdditionalImageProcessors(thumbnail, thumbnailGraph, entity, imageType, imageIndex); + ExecuteAdditionalImageProcessors(originalImage, thumbnail, thumbnailGraph, entity, imageType, imageIndex); + + if (Kernel.Instance.ImageProcessors.Any(i => i.RequiresTransparency)) + { + outputFormat = ImageFormat.Png; + } } // Write to the output stream - SaveImage(originalImage.RawFormat, thumbnail, toStream, quality); + SaveImage(outputFormat, thumbnail, toStream, quality); thumbnailGraph.Dispose(); thumbnail.Dispose(); @@ -78,7 +87,7 @@ namespace MediaBrowser.Controller.Drawing /// The entity that owns the image /// The image type /// The image index (currently only used with backdrops) - private static void ExecuteAdditionalImageProcessors(Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex) + private static void ExecuteAdditionalImageProcessors(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex) { var baseItem = entity as BaseItem; @@ -86,33 +95,33 @@ namespace MediaBrowser.Controller.Drawing { foreach (var processor in Kernel.Instance.ImageProcessors) { - processor.ProcessImage(bitmap, graphics, baseItem, imageType, imageIndex); + processor.ProcessImage(originalImage, bitmap, graphics, baseItem, imageType, imageIndex); } } else { foreach (var processor in Kernel.Instance.ImageProcessors) { - processor.ProcessImage(bitmap, graphics, entity); + processor.ProcessImage(originalImage, bitmap, graphics, entity); } } } - public static void SaveImage(ImageFormat originalImageRawFormat, Image newImage, Stream toStream, int? quality) + 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 // All other formats use the generic Image.Save - if (ImageFormat.Jpeg.Equals(originalImageRawFormat)) + if (ImageFormat.Jpeg.Equals(outputFormat)) { SaveJpeg(newImage, toStream, quality); } - else if (ImageFormat.Png.Equals(originalImageRawFormat)) + else if (ImageFormat.Png.Equals(outputFormat)) { newImage.Save(toStream, ImageFormat.Png); } else { - newImage.Save(toStream, originalImageRawFormat); + newImage.Save(toStream, outputFormat); } } diff --git a/MediaBrowser.Controller/Kernel.cs b/MediaBrowser.Controller/Kernel.cs index 4c0dc6965..1c11b9fc8 100644 --- a/MediaBrowser.Controller/Kernel.cs +++ b/MediaBrowser.Controller/Kernel.cs @@ -81,7 +81,7 @@ namespace MediaBrowser.Controller /// Gets the list of currently registered entity resolvers /// [ImportMany(typeof(BaseImageProcessor))] - internal IEnumerable ImageProcessors { get; private set; } + public IEnumerable ImageProcessors { get; private set; } /// /// Creates a kernel based on a Data path, which is akin to our current programdata path -- cgit v1.2.3 From bd6c2d2a22c099e35fd69816e28b5c46a83176b1 Mon Sep 17 00:00:00 2001 From: LukePulverenti Luke Pulverenti luke pulverenti Date: Tue, 18 Sep 2012 18:32:37 -0400 Subject: A few more image improvements --- MediaBrowser.Api/HttpHandlers/ImageHandler.cs | 138 +++++++-------------- .../Drawing/BaseImageProcessor.cs | 55 +++++--- MediaBrowser.Controller/Drawing/ImageProcessor.cs | 59 ++++++--- 3 files changed, 122 insertions(+), 130 deletions(-) (limited to 'MediaBrowser.Controller/Drawing/ImageProcessor.cs') diff --git a/MediaBrowser.Api/HttpHandlers/ImageHandler.cs b/MediaBrowser.Api/HttpHandlers/ImageHandler.cs index da20e0533..c168569cd 100644 --- a/MediaBrowser.Api/HttpHandlers/ImageHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/ImageHandler.cs @@ -1,6 +1,4 @@ -using System.Drawing.Imaging; -using MediaBrowser.Common.Logging; -using MediaBrowser.Common.Net; +using MediaBrowser.Common.Net; using MediaBrowser.Common.Net.Handlers; using MediaBrowser.Controller; using MediaBrowser.Controller.Drawing; @@ -24,6 +22,7 @@ namespace MediaBrowser.Api.HttpHandlers } private string _imagePath; + private async Task GetImagePath() { _imagePath = _imagePath ?? await DiscoverImagePath(); @@ -32,28 +31,34 @@ namespace MediaBrowser.Api.HttpHandlers } private BaseEntity _sourceEntity; + private async Task GetSourceEntity() { if (_sourceEntity == null) { if (!string.IsNullOrEmpty(QueryString["personname"])) { - _sourceEntity = await Kernel.Instance.ItemController.GetPerson(QueryString["personname"]).ConfigureAwait(false); + _sourceEntity = + await Kernel.Instance.ItemController.GetPerson(QueryString["personname"]).ConfigureAwait(false); } else if (!string.IsNullOrEmpty(QueryString["genre"])) { - _sourceEntity = await Kernel.Instance.ItemController.GetGenre(QueryString["genre"]).ConfigureAwait(false); + _sourceEntity = + await Kernel.Instance.ItemController.GetGenre(QueryString["genre"]).ConfigureAwait(false); } else if (!string.IsNullOrEmpty(QueryString["year"])) { - _sourceEntity = await Kernel.Instance.ItemController.GetYear(int.Parse(QueryString["year"])).ConfigureAwait(false); + _sourceEntity = + await + Kernel.Instance.ItemController.GetYear(int.Parse(QueryString["year"])).ConfigureAwait(false); } else if (!string.IsNullOrEmpty(QueryString["studio"])) { - _sourceEntity = await Kernel.Instance.ItemController.GetStudio(QueryString["studio"]).ConfigureAwait(false); + _sourceEntity = + await Kernel.Instance.ItemController.GetStudio(QueryString["studio"]).ConfigureAwait(false); } else if (!string.IsNullOrEmpty(QueryString["userid"])) @@ -74,85 +79,62 @@ namespace MediaBrowser.Api.HttpHandlers { var entity = await GetSourceEntity().ConfigureAwait(false); - var item = entity as BaseItem; + return ImageProcessor.GetImagePath(entity, ImageType, ImageIndex); + } - if (item != null) + public override async Task GetContentType() + { + if (Kernel.Instance.ImageProcessors.Any(i => i.RequiresTransparency)) { - return GetImagePathFromTypes(item, ImageType, ImageIndex); + return MimeTypes.GetMimeType(".png"); } - return entity.PrimaryImagePath; + return MimeTypes.GetMimeType(await GetImagePath().ConfigureAwait(false)); } - private Stream _sourceStream; - private async Task GetSourceStream() + public override TimeSpan CacheDuration { - await EnsureSourceStream().ConfigureAwait(false); - return _sourceStream; + get { return TimeSpan.FromDays(365); } } - private bool _sourceStreamEnsured; - private async Task EnsureSourceStream() + protected override async Task GetLastDateModified() { - if (!_sourceStreamEnsured) + string path = await GetImagePath().ConfigureAwait(false); + + 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) { - try - { - _sourceStream = File.OpenRead(await GetImagePath().ConfigureAwait(false)); - } - catch (FileNotFoundException ex) - { - StatusCode = 404; - Logger.LogException(ex); - } - catch (DirectoryNotFoundException ex) + if (!File.Exists(path)) { StatusCode = 404; - Logger.LogException(ex); - } - catch (UnauthorizedAccessException ex) - { - StatusCode = 403; - Logger.LogException(ex); - } - finally - { - _sourceStreamEnsured = true; + return null; } } - } - - public async override Task GetContentType() - { - if (await GetSourceStream().ConfigureAwait(false) == null) - { - return null; - } - if (Kernel.Instance.ImageProcessors.Any(i => i.RequiresTransparency)) - { - return MimeTypes.GetMimeType(".png"); - } - - return MimeTypes.GetMimeType(await GetImagePath().ConfigureAwait(false)); + return await GetMostRecentDateModified(date); } - public override TimeSpan CacheDuration + private async Task GetMostRecentDateModified(DateTime imageFileLastDateModified) { - get - { - return TimeSpan.FromDays(365); - } - } + var date = imageFileLastDateModified; - protected async override Task GetLastDateModified() - { - if (await GetSourceStream().ConfigureAwait(false) == null) + var entity = await GetSourceEntity().ConfigureAwait(false); + + foreach (var processor in Kernel.Instance.ImageProcessors) { - return null; + if (processor.IsConfiguredToProcess(entity, ImageType, ImageIndex)) + { + if (processor.ProcessingConfigurationDateLastModifiedUtc > date) + { + date = processor.ProcessingConfigurationDateLastModifiedUtc; + } + } } - return File.GetLastWriteTimeUtc(await GetImagePath().ConfigureAwait(false)); + return date; } private int ImageIndex @@ -262,37 +244,9 @@ namespace MediaBrowser.Api.HttpHandlers protected override async Task WriteResponseToOutputStream(Stream stream) { - Stream sourceStream = await GetSourceStream().ConfigureAwait(false); - var entity = await GetSourceEntity().ConfigureAwait(false); - ImageProcessor.ProcessImage(sourceStream, stream, Width, Height, MaxWidth, MaxHeight, Quality, entity, ImageType, ImageIndex); - } - - private string GetImagePathFromTypes(BaseItem item, ImageType imageType, int imageIndex) - { - if (imageType == ImageType.Logo) - { - return item.LogoImagePath; - } - if (imageType == ImageType.Backdrop) - { - return item.BackdropImagePaths.ElementAt(imageIndex); - } - if (imageType == ImageType.Banner) - { - return item.BannerImagePath; - } - if (imageType == ImageType.Art) - { - return item.ArtImagePath; - } - if (imageType == ImageType.Thumbnail) - { - return item.ThumbnailImagePath; - } - - return item.PrimaryImagePath; + ImageProcessor.ProcessImage(entity, ImageType, ImageIndex, stream, Width, Height, MaxWidth, MaxHeight, Quality); } } } diff --git a/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs b/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs index ebd0e22c8..8fc6564e7 100644 --- a/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs @@ -1,5 +1,6 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Entities; +using System; using System.ComponentModel.Composition; using System.Drawing; using System.Drawing.Drawing2D; @@ -15,16 +16,7 @@ namespace MediaBrowser.Controller.Drawing public abstract class BaseImageProcessor { /// - /// Processes the primary image for a BaseEntity (Person, Studio, User, etc) - /// - /// The original Image, before re-sizing - /// The bitmap holding the original image, after re-sizing - /// The graphics surface on which the output is drawn - /// The entity that owns the image - public abstract void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity); - - /// - /// Processes an image for a BaseItem + /// Processes an image for a BaseEntity /// /// The original Image, before re-sizing /// The bitmap holding the original image, after re-sizing @@ -32,10 +24,11 @@ namespace MediaBrowser.Controller.Drawing /// The entity that owns the image /// The image type /// The image index (currently only used with backdrops) - public abstract void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseItem entity, ImageType imageType, int imageIndex); + public abstract void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex); /// /// 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. /// public virtual bool RequiresTransparency { @@ -44,6 +37,18 @@ namespace MediaBrowser.Controller.Drawing return false; } } + + /// + /// 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 + /// + public abstract bool IsConfiguredToProcess(BaseEntity entity, ImageType imageType, int imageIndex); + + /// + /// 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 + /// + public abstract DateTime ProcessingConfigurationDateLastModifiedUtc { get; } } /// @@ -52,34 +57,44 @@ namespace MediaBrowser.Controller.Drawing //[Export(typeof(BaseImageProcessor))] public class MyRoundedCornerImageProcessor : BaseImageProcessor { - public override void ProcessImage(Image originalImage, Bitmap bitmap, Graphics g, BaseEntity entity) + public override void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex) { var CornerRadius = 20; - g.Clear(Color.Transparent); - + 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); - - g.SetClip(gp); - g.DrawImage(originalImage, 0, 0, bitmap.Width, bitmap.Height); + + graphics.SetClip(gp); + graphics.DrawImage(originalImage, 0, 0, bitmap.Width, bitmap.Height); } } - public override void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseItem entity, ImageType imageType, int imageIndex) + public override bool RequiresTransparency { + get + { + return true; + } } - public override bool RequiresTransparency + public override DateTime ProcessingConfigurationDateLastModifiedUtc { get { - return true; + // This will result in a situation where images are never cached, but again, this is a prototype + return DateTime.UtcNow; } } + + public override bool IsConfiguredToProcess(BaseEntity entity, ImageType imageType, int imageIndex) + { + return true; + } } } diff --git a/MediaBrowser.Controller/Drawing/ImageProcessor.cs b/MediaBrowser.Controller/Drawing/ImageProcessor.cs index f9b6366c6..7ee4ef734 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessor.cs @@ -14,19 +14,18 @@ namespace MediaBrowser.Controller.Drawing /// /// Processes an image by resizing to target dimensions /// - /// The stream containing the source image + /// The entity that owns the image + /// The image type + /// The image index (currently only used with backdrops) /// The stream to save the new image to /// Use if a fixed width is required. Aspect ratio will be preserved. /// Use if a fixed height is required. Aspect ratio will be preserved. /// Use if a max width is required. Aspect ratio will be preserved. /// Use if a max height is required. Aspect ratio will be preserved. /// Quality level, from 0-100. Currently only applies to JPG. The default value should suffice. - /// The entity that owns the image - /// The image type - /// The image index (currently only used with backdrops) - public static void ProcessImage(Stream sourceImageStream, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality, BaseEntity entity, ImageType imageType, int imageIndex) + public static void ProcessImage(BaseEntity entity, ImageType imageType, int imageIndex, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality) { - Image originalImage = Image.FromStream(sourceImageStream); + Image originalImage = Image.FromFile(GetImagePath(entity, imageType, imageIndex)); // Determine the output size based on incoming parameters Size newSize = DrawingUtils.Resize(originalImage.Size, width, height, maxWidth, maxHeight); @@ -79,9 +78,42 @@ namespace MediaBrowser.Controller.Drawing originalImage.Dispose(); } + public static string GetImagePath(BaseEntity entity, ImageType imageType, int imageIndex) + { + var item = entity as BaseItem; + + if (item != null) + { + if (imageType == ImageType.Logo) + { + return item.LogoImagePath; + } + if (imageType == ImageType.Backdrop) + { + return item.BackdropImagePaths.ElementAt(imageIndex); + } + if (imageType == ImageType.Banner) + { + return item.BannerImagePath; + } + if (imageType == ImageType.Art) + { + return item.ArtImagePath; + } + if (imageType == ImageType.Thumbnail) + { + return item.ThumbnailImagePath; + } + } + + return entity.PrimaryImagePath; + } + + /// /// Executes additional image processors that are registered with the Kernel /// + /// The original Image, before re-sizing /// The bitmap holding the original image, after re-sizing /// The graphics surface on which the output is drawn /// The entity that owns the image @@ -89,20 +121,11 @@ namespace MediaBrowser.Controller.Drawing /// The image index (currently only used with backdrops) private static void ExecuteAdditionalImageProcessors(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex) { - var baseItem = entity as BaseItem; - - if (baseItem != null) - { - foreach (var processor in Kernel.Instance.ImageProcessors) - { - processor.ProcessImage(originalImage, bitmap, graphics, baseItem, imageType, imageIndex); - } - } - else + foreach (var processor in Kernel.Instance.ImageProcessors) { - foreach (var processor in Kernel.Instance.ImageProcessors) + if (processor.IsConfiguredToProcess(entity, imageType, imageIndex)) { - processor.ProcessImage(originalImage, bitmap, graphics, entity); + processor.ProcessImage(originalImage, bitmap, graphics, entity, imageType, imageIndex); } } } -- cgit v1.2.3 From d8c01ded6eb57ba312e1cd62c4fa51dbcce6053a Mon Sep 17 00:00:00 2001 From: LukePulverenti Luke Pulverenti luke pulverenti Date: Wed, 19 Sep 2012 12:51:37 -0400 Subject: made some improvements to the base http handler --- MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs | 13 +- MediaBrowser.Api/HttpHandlers/ImageHandler.cs | 71 ++-------- .../HttpHandlers/PluginAssemblyHandler.cs | 4 +- .../HttpHandlers/PluginConfigurationHandler.cs | 19 ++- .../HttpHandlers/ServerConfigurationHandler.cs | 19 ++- MediaBrowser.Api/HttpHandlers/WeatherHandler.cs | 16 +-- .../Net/Handlers/BaseEmbeddedResourceHandler.cs | 5 - MediaBrowser.Common/Net/Handlers/BaseHandler.cs | 146 +++++++++------------ .../Net/Handlers/BaseSerializationHandler.cs | 84 ++++++------ .../Net/Handlers/StaticFileHandler.cs | 87 +++++------- .../Drawing/BaseImageProcessor.cs | 102 -------------- MediaBrowser.Controller/Drawing/ImageProcessor.cs | 32 ----- MediaBrowser.Controller/Kernel.cs | 6 - .../MediaBrowser.Controller.csproj | 1 - 14 files changed, 177 insertions(+), 428 deletions(-) delete mode 100644 MediaBrowser.Controller/Drawing/BaseImageProcessor.cs (limited to 'MediaBrowser.Controller/Drawing/ImageProcessor.cs') diff --git a/MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs b/MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs index 7ad0ed8aa..96ef60681 100644 --- a/MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/BaseMediaHandler.cs @@ -90,14 +90,15 @@ namespace MediaBrowser.Api.HttpHandlers } } - public override Task GetContentType() + protected override Task 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(info); } public override Task ProcessRequest(HttpListenerContext ctx) diff --git a/MediaBrowser.Api/HttpHandlers/ImageHandler.cs b/MediaBrowser.Api/HttpHandlers/ImageHandler.cs index d3aaf27ff..4aa367fb7 100644 --- a/MediaBrowser.Api/HttpHandlers/ImageHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/ImageHandler.cs @@ -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 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 GetLastDateModified() + protected async override Task 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; - } - } - - return await GetMostRecentDateModified(date); - } - - private async Task 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; - } + info.StatusCode = 404; + date = null; } } - return date; - } - - protected override async Task 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(); - } - } + info.DateLastModified = date; - return tag; + return info; } private int ImageIndex diff --git a/MediaBrowser.Api/HttpHandlers/PluginAssemblyHandler.cs b/MediaBrowser.Api/HttpHandlers/PluginAssemblyHandler.cs index 88161c114..47f08c8c3 100644 --- a/MediaBrowser.Api/HttpHandlers/PluginAssemblyHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/PluginAssemblyHandler.cs @@ -15,8 +15,8 @@ namespace MediaBrowser.Api.HttpHandlers { return ApiService.IsApiUrlMatch("pluginassembly", request); } - - public override Task GetContentType() + + protected override Task GetResponseInfo() { throw new NotImplementedException(); } diff --git a/MediaBrowser.Api/HttpHandlers/PluginConfigurationHandler.cs b/MediaBrowser.Api/HttpHandlers/PluginConfigurationHandler.cs index 95af9a344..dc363956f 100644 --- a/MediaBrowser.Api/HttpHandlers/PluginConfigurationHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/PluginConfigurationHandler.cs @@ -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 GetResponseInfo() { - get - { - return TimeSpan.FromDays(7); - } - } + var info = await base.GetResponseInfo().ConfigureAwait(false); - protected override Task GetLastDateModified() - { - return Task.FromResult(Plugin.ConfigurationDateLastModified); - } + info.DateLastModified = Plugin.ConfigurationDateLastModified; + info.CacheDuration = TimeSpan.FromDays(7); + + return info; + } } } diff --git a/MediaBrowser.Api/HttpHandlers/ServerConfigurationHandler.cs b/MediaBrowser.Api/HttpHandlers/ServerConfigurationHandler.cs index 64ba44ec2..48c6761b1 100644 --- a/MediaBrowser.Api/HttpHandlers/ServerConfigurationHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/ServerConfigurationHandler.cs @@ -16,23 +16,22 @@ namespace MediaBrowser.Api.HttpHandlers { return ApiService.IsApiUrlMatch("serverconfiguration", request); } - + protected override Task GetObjectToSerialize() { return Task.FromResult(Kernel.Instance.Configuration); } - public override TimeSpan CacheDuration + protected override async Task GetResponseInfo() { - get - { - return TimeSpan.FromDays(7); - } - } + var info = await base.GetResponseInfo().ConfigureAwait(false); - protected override Task GetLastDateModified() - { - return Task.FromResult(File.GetLastWriteTimeUtc(Kernel.Instance.ApplicationPaths.SystemConfigurationFilePath)); + info.DateLastModified = + File.GetLastWriteTimeUtc(Kernel.Instance.ApplicationPaths.SystemConfigurationFilePath); + + info.CacheDuration = TimeSpan.FromDays(7); + + return info; } } } diff --git a/MediaBrowser.Api/HttpHandlers/WeatherHandler.cs b/MediaBrowser.Api/HttpHandlers/WeatherHandler.cs index 90ecae122..378e89067 100644 --- a/MediaBrowser.Api/HttpHandlers/WeatherHandler.cs +++ b/MediaBrowser.Api/HttpHandlers/WeatherHandler.cs @@ -16,7 +16,7 @@ namespace MediaBrowser.Api.HttpHandlers { return ApiService.IsApiUrlMatch("weather", request); } - + protected override Task 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); } - /// - /// Tell the client to cache the weather info for 15 minutes - /// - public override TimeSpan CacheDuration + protected override async Task GetResponseInfo() { - get - { - return TimeSpan.FromMinutes(15); - } + var info = await base.GetResponseInfo().ConfigureAwait(false); + + info.CacheDuration = TimeSpan.FromMinutes(15); + + return info; } } } diff --git a/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs index 3ce85a688..579e341fe 100644 --- a/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs +++ b/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs @@ -13,11 +13,6 @@ namespace MediaBrowser.Common.Net.Handlers protected string ResourcePath { get; set; } - public override Task GetContentType() - { - return Task.FromResult(MimeTypes.GetMimeType(ResourcePath)); - } - protected override Task WriteResponseToOutputStream(Stream stream) { return GetEmbeddedResourceStream().CopyToAsync(stream); diff --git a/MediaBrowser.Common/Net/Handlers/BaseHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseHandler.cs index ab12cb2cf..a5058e6ca 100644 --- a/MediaBrowser.Common/Net/Handlers/BaseHandler.cs +++ b/MediaBrowser.Common/Net/Handlers/BaseHandler.cs @@ -112,32 +112,6 @@ namespace MediaBrowser.Common.Net.Handlers } } - /// - /// Gets the MIME type to include in the response headers - /// - public abstract Task GetContentType(); - - /// - /// Gets the status code to include in the response headers - /// - protected int StatusCode { get; set; } - - /// - /// Gets the cache duration to include in the response headers - /// - 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; - - ctx.Response.ContentType = await GetContentType().ConfigureAwait(false); + ResponseInfo responseInfo = await GetResponseInfo().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}", StatusCode, url); + Logger.LogInfo("Responding with status code {0} for url {1}", responseInfo.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); } + if (responseInfo.DateLastModified.HasValue) + { + ctx.Response.Headers[HttpResponseHeader.LastModified] = responseInfo.DateLastModified.Value.ToString("r"); + } + // Add caching headers - if (cacheDuration.Ticks > 0) + if (responseInfo.CacheDuration.Ticks > 0) { - CacheResponse(ctx.Response, cacheDuration, lastDateModified); + 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 GetETag() - { - return Task.FromResult(string.Empty); - } - - /// - /// Gives subclasses a chance to do any prep work, and also to validate data and set an error status code, if needed - /// - protected virtual Task PrepareResponse() - { - return Task.FromResult(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 GetLastDateModified() - { - DateTime? value = null; - - return Task.FromResult(value); - } - - private bool IsResponseValid - { - get - { - return StatusCode == 200 || StatusCode == 206; - } - } + protected abstract Task 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; + } + } + } } \ No newline at end of file diff --git a/MediaBrowser.Common/Net/Handlers/BaseSerializationHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseSerializationHandler.cs index d60a9ae1f..53b3ee817 100644 --- a/MediaBrowser.Common/Net/Handlers/BaseSerializationHandler.cs +++ b/MediaBrowser.Common/Net/Handlers/BaseSerializationHandler.cs @@ -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 : 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 GetContentType() + + protected string ContentType { - switch (SerializationFormat) + get { - case SerializationFormat.Jsv: - return Task.FromResult("text/plain"); - case SerializationFormat.Protobuf: - return Task.FromResult("application/x-protobuf"); - default: - return Task.FromResult(MimeTypes.JsonMimeType); + switch (SerializationFormat) + { + case SerializationFormat.Jsv: + return "text/plain"; + case SerializationFormat.Protobuf: + return "application/x-protobuf"; + default: + return MimeTypes.JsonMimeType; + } } } - private bool _objectToSerializeEnsured; - private T _objectToSerialize; - - private async Task EnsureObjectToSerialize() + protected override async Task GetResponseInfo() { - if (!_objectToSerializeEnsured) + ResponseInfo info = new ResponseInfo { - _objectToSerialize = await GetObjectToSerialize().ConfigureAwait(false); + ContentType = ContentType + }; - if (_objectToSerialize == null) - { - StatusCode = 404; - } + _objectToSerialize = await GetObjectToSerialize().ConfigureAwait(false); - _objectToSerializeEnsured = true; + if (_objectToSerialize == null) + { + info.StatusCode = 404; } + + return info; } - protected abstract Task GetObjectToSerialize(); + private T _objectToSerialize; - protected override Task PrepareResponse() - { - return EnsureObjectToSerialize(); - } + protected abstract Task GetObjectToSerialize(); - protected async override Task WriteResponseToOutputStream(Stream stream) + protected 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; + } + }); } } diff --git a/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs b/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs index 741d2d6c1..11438b164 100644 --- a/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs +++ b/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs @@ -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 GetLastDateModified() + protected override Task GetResponseInfo() { - DateTime? value = null; - - EnsureSourceStream(); + ResponseInfo info = new ResponseInfo + { + ContentType = MimeTypes.GetMimeType(Path), + }; - if (SourceStream != null) + try + { + SourceStream = File.OpenRead(Path); + } + catch (FileNotFoundException ex) + { + info.StatusCode = 404; + Logger.LogException(ex); + } + catch (DirectoryNotFoundException ex) { - value = File.GetLastWriteTimeUtc(Path); + info.StatusCode = 404; + Logger.LogException(ex); + } + catch (UnauthorizedAccessException ex) + { + info.StatusCode = 403; + Logger.LogException(ex); } - return Task.FromResult(value); - } + info.CompressResponse = ShouldCompressResponse(info.ContentType); - public override Task GetContentType() - { - return Task.FromResult(MimeTypes.GetMimeType(Path)); - } + if (SourceStream != null) + { + info.DateLastModified = File.GetLastWriteTimeUtc(Path); + } - protected override Task PrepareResponse() - { - EnsureSourceStream(); - return Task.FromResult(null); + return Task.FromResult(info); } protected override Task WriteResponseToOutputStream(Stream stream) diff --git a/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs b/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs deleted file mode 100644 index a1441cf7f..000000000 --- a/MediaBrowser.Controller/Drawing/BaseImageProcessor.cs +++ /dev/null @@ -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 -{ - /// - /// 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 - /// - public abstract class BaseImageProcessor - { - /// - /// Processes an image for a BaseEntity - /// - /// The original Image, before re-sizing - /// The bitmap holding the original image, after re-sizing - /// The graphics surface on which the output is drawn - /// The entity that owns the image - /// The image type - /// The image index (currently only used with backdrops) - public abstract void ProcessImage(Image originalImage, Bitmap bitmap, Graphics graphics, BaseEntity entity, ImageType imageType, int imageIndex); - - /// - /// 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. - /// - public virtual bool RequiresTransparency - { - get - { - return false; - } - } - - /// - /// 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 - /// - public abstract bool IsConfiguredToProcess(BaseEntity entity, ImageType imageType, int imageIndex); - - /// - /// 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 - /// - public abstract DateTime ProcessingConfigurationDateLastModifiedUtc { get; } - } - - /// - /// This is demo-ware and should be deleted eventually - /// - //[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; - } - } -} diff --git a/MediaBrowser.Controller/Drawing/ImageProcessor.cs b/MediaBrowser.Controller/Drawing/ImageProcessor.cs index 7ee4ef734..29e40d17d 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessor.cs @@ -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; } - - /// - /// Executes additional image processors that are registered with the Kernel - /// - /// The original Image, before re-sizing - /// The bitmap holding the original image, after re-sizing - /// The graphics surface on which the output is drawn - /// The entity that owns the image - /// The image type - /// The image index (currently only used with backdrops) - 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 diff --git a/MediaBrowser.Controller/Kernel.cs b/MediaBrowser.Controller/Kernel.cs index 1c11b9fc8..bf03d1af1 100644 --- a/MediaBrowser.Controller/Kernel.cs +++ b/MediaBrowser.Controller/Kernel.cs @@ -77,12 +77,6 @@ namespace MediaBrowser.Controller /// internal IBaseItemResolver[] EntityResolvers { get; private set; } - /// - /// Gets the list of currently registered entity resolvers - /// - [ImportMany(typeof(BaseImageProcessor))] - public IEnumerable ImageProcessors { get; private set; } - /// /// Creates a kernel based on a Data path, which is akin to our current programdata path /// diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 131825af3..fd2be689e 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -59,7 +59,6 @@ - -- cgit v1.2.3