Moved discovery of loggers and weather providers to MEF. Also added support for third-party image processors, also discovered through MEF.

This commit is contained in:
LukePulverenti Luke Pulverenti luke pulverenti 2012-09-18 15:33:57 -04:00
parent 01a25c48a0
commit 8b7effd6ff
23 changed files with 370 additions and 334 deletions

View File

@ -2,6 +2,7 @@
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using MediaBrowser.Common.Net.Handlers; using MediaBrowser.Common.Net.Handlers;
using MediaBrowser.Controller; using MediaBrowser.Controller;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using System; using System;
@ -29,49 +30,57 @@ namespace MediaBrowser.Api.HttpHandlers
return _imagePath; return _imagePath;
} }
private BaseEntity _sourceEntity;
private async Task<BaseEntity> GetSourceEntity()
{
if (_sourceEntity == null)
{
if (!string.IsNullOrEmpty(QueryString["personname"]))
{
_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);
}
else if (!string.IsNullOrEmpty(QueryString["year"]))
{
_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);
}
else if (!string.IsNullOrEmpty(QueryString["userid"]))
{
_sourceEntity = ApiService.GetUserById(QueryString["userid"], false);
}
else
{
_sourceEntity = ApiService.GetItemById(QueryString["id"]);
}
}
return _sourceEntity;
}
private async Task<string> DiscoverImagePath() private async Task<string> DiscoverImagePath()
{ {
string personName = QueryString["personname"]; var entity = await GetSourceEntity().ConfigureAwait(false);
if (!string.IsNullOrEmpty(personName)) var item = entity as BaseItem;
if (item != null)
{ {
return (await Kernel.Instance.ItemController.GetPerson(personName).ConfigureAwait(false)).PrimaryImagePath; return GetImagePathFromTypes(item, ImageType, ImageIndex);
} }
string genreName = QueryString["genre"]; return entity.PrimaryImagePath;
if (!string.IsNullOrEmpty(genreName))
{
return (await Kernel.Instance.ItemController.GetGenre(genreName).ConfigureAwait(false)).PrimaryImagePath;
}
string year = QueryString["year"];
if (!string.IsNullOrEmpty(year))
{
return (await Kernel.Instance.ItemController.GetYear(int.Parse(year)).ConfigureAwait(false)).PrimaryImagePath;
}
string studio = QueryString["studio"];
if (!string.IsNullOrEmpty(studio))
{
return (await Kernel.Instance.ItemController.GetStudio(studio).ConfigureAwait(false)).PrimaryImagePath;
}
string userId = QueryString["userid"];
if (!string.IsNullOrEmpty(userId))
{
return ApiService.GetUserById(userId, false).PrimaryImagePath;
}
BaseItem item = ApiService.GetItemById(QueryString["id"]);
string imageIndex = QueryString["index"];
int index = string.IsNullOrEmpty(imageIndex) ? 0 : int.Parse(imageIndex);
return GetImagePathFromTypes(item, ImageType, index);
} }
private Stream _sourceStream; private Stream _sourceStream;
@ -114,8 +123,6 @@ namespace MediaBrowser.Api.HttpHandlers
public async override Task<string> GetContentType() public async override Task<string> GetContentType()
{ {
await EnsureSourceStream().ConfigureAwait(false);
if (await GetSourceStream().ConfigureAwait(false) == null) if (await GetSourceStream().ConfigureAwait(false) == null)
{ {
return null; return null;
@ -134,8 +141,6 @@ namespace MediaBrowser.Api.HttpHandlers
protected async override Task<DateTime?> GetLastDateModified() protected async override Task<DateTime?> GetLastDateModified()
{ {
await EnsureSourceStream().ConfigureAwait(false);
if (await GetSourceStream().ConfigureAwait(false) == null) if (await GetSourceStream().ConfigureAwait(false) == null)
{ {
return null; return null;
@ -144,6 +149,21 @@ namespace MediaBrowser.Api.HttpHandlers
return File.GetLastWriteTimeUtc(await GetImagePath().ConfigureAwait(false)); return File.GetLastWriteTimeUtc(await GetImagePath().ConfigureAwait(false));
} }
private int ImageIndex
{
get
{
string val = QueryString["index"];
if (string.IsNullOrEmpty(val))
{
return 0;
}
return int.Parse(val);
}
}
private int? Height private int? Height
{ {
get get
@ -236,7 +256,11 @@ namespace MediaBrowser.Api.HttpHandlers
protected override async Task WriteResponseToOutputStream(Stream stream) protected override async Task WriteResponseToOutputStream(Stream stream)
{ {
ImageProcessor.ProcessImage(await GetSourceStream().ConfigureAwait(false), stream, Width, Height, MaxWidth, MaxHeight, Quality); 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) private string GetImagePathFromTypes(BaseItem item, ImageType imageType, int imageIndex)

View File

@ -1,5 +1,5 @@
using MediaBrowser.Common.Drawing; using MediaBrowser.Common.Net.Handlers;
using MediaBrowser.Common.Net.Handlers; using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.DTO; using MediaBrowser.Model.DTO;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
@ -7,7 +7,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.Composition; using System.ComponentModel.Composition;
using System.Drawing; using System.Drawing;
using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;

View File

@ -3,6 +3,7 @@ using MediaBrowser.Controller;
using MediaBrowser.Model.Weather; using MediaBrowser.Model.Weather;
using System; using System;
using System.ComponentModel.Composition; using System.ComponentModel.Composition;
using System.Linq;
using System.Net; using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -27,7 +28,7 @@ namespace MediaBrowser.Api.HttpHandlers
zipCode = Kernel.Instance.Configuration.WeatherZipCode; zipCode = Kernel.Instance.Configuration.WeatherZipCode;
} }
return Kernel.Instance.WeatherClient.GetWeatherInfoAsync(zipCode); return Kernel.Instance.WeatherProviders.First().GetWeatherInfoAsync(zipCode);
} }
/// <summary> /// <summary>

View File

@ -83,7 +83,6 @@
<Compile Include="HttpHandlers\WeatherHandler.cs" /> <Compile Include="HttpHandlers\WeatherHandler.cs" />
<Compile Include="HttpHandlers\YearHandler.cs" /> <Compile Include="HttpHandlers\YearHandler.cs" />
<Compile Include="HttpHandlers\YearsHandler.cs" /> <Compile Include="HttpHandlers\YearsHandler.cs" />
<Compile Include="ImageProcessor.cs" />
<Compile Include="Plugin.cs" /> <Compile Include="Plugin.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>

View File

@ -1,5 +1,4 @@
using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins;
using System.ComponentModel.Composition; using System.ComponentModel.Composition;
namespace MediaBrowser.Api namespace MediaBrowser.Api

View File

@ -10,7 +10,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.Composition; using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@ -72,6 +71,12 @@ namespace MediaBrowser.Common.Kernel
[ImportMany(typeof(BaseHandler))] [ImportMany(typeof(BaseHandler))]
private IEnumerable<BaseHandler> HttpHandlers { get; set; } private IEnumerable<BaseHandler> HttpHandlers { get; set; }
/// <summary>
/// Gets the list of currently registered Loggers
/// </summary>
[ImportMany(typeof(BaseLogger))]
public IEnumerable<BaseLogger> Loggers { get; set; }
/// <summary> /// <summary>
/// Both the Ui and server will have a built-in HttpServer. /// Both the Ui and server will have a built-in HttpServer.
/// People will inevitably want remote control apps so it's needed in the Ui too. /// People will inevitably want remote control apps so it's needed in the Ui too.
@ -83,6 +88,8 @@ namespace MediaBrowser.Common.Kernel
/// </summary> /// </summary>
private IDisposable HttpListener { get; set; } private IDisposable HttpListener { get; set; }
private CompositionContainer CompositionContainer { get; set; }
protected virtual string HttpServerUrlPrefix protected virtual string HttpServerUrlPrefix
{ {
get get
@ -101,13 +108,13 @@ namespace MediaBrowser.Common.Kernel
/// </summary> /// </summary>
public async Task Init(IProgress<TaskProgress> progress) public async Task Init(IProgress<TaskProgress> progress)
{ {
Logger.Kernel = this;
// Performs initializations that only occur once // Performs initializations that only occur once
InitializeInternal(progress); InitializeInternal(progress);
// Performs initializations that can be reloaded at anytime // Performs initializations that can be reloaded at anytime
await Reload(progress).ConfigureAwait(false); await Reload(progress).ConfigureAwait(false);
ReportProgress(progress, "Loading Complete");
} }
/// <summary> /// <summary>
@ -117,8 +124,6 @@ namespace MediaBrowser.Common.Kernel
{ {
ApplicationPaths = new TApplicationPathsType(); ApplicationPaths = new TApplicationPathsType();
ReloadLogger();
ReportProgress(progress, "Loading Configuration"); ReportProgress(progress, "Loading Configuration");
ReloadConfiguration(); ReloadConfiguration();
@ -136,6 +141,8 @@ namespace MediaBrowser.Common.Kernel
await ReloadInternal(progress).ConfigureAwait(false); await ReloadInternal(progress).ConfigureAwait(false);
OnReloadCompleted(progress); OnReloadCompleted(progress);
ReportProgress(progress, "Kernel.Reload Complete");
} }
/// <summary> /// <summary>
@ -151,23 +158,6 @@ namespace MediaBrowser.Common.Kernel
}).ConfigureAwait(false); }).ConfigureAwait(false);
} }
/// <summary>
/// Disposes the current logger and creates a new one
/// </summary>
private void ReloadLogger()
{
DisposeLogger();
DateTime now = DateTime.Now;
string logFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, "log-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
Trace.Listeners.Add(new TextWriterTraceListener(logFilePath));
Trace.AutoFlush = true;
Logger.LoggerInstance = new TraceLogger();
}
/// <summary> /// <summary>
/// Uses MEF to locate plugins /// Uses MEF to locate plugins
/// Subclasses can use this to locate types within plugins /// Subclasses can use this to locate types within plugins
@ -176,14 +166,13 @@ namespace MediaBrowser.Common.Kernel
{ {
DisposeComposableParts(); DisposeComposableParts();
var container = GetCompositionContainer(includeCurrentAssembly: true); CompositionContainer = GetCompositionContainer(includeCurrentAssembly: true);
container.ComposeParts(this); CompositionContainer.ComposeParts(this);
OnComposablePartsLoaded(); OnComposablePartsLoaded();
container.Catalog.Dispose(); CompositionContainer.Catalog.Dispose();
container.Dispose();
} }
/// <summary> /// <summary>
@ -198,8 +187,7 @@ namespace MediaBrowser.Common.Kernel
var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a))); var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
// Include composable parts in the Common assembly // Include composable parts in the Common assembly
// Uncomment this if it's ever needed catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
//catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
if (includeCurrentAssembly) if (includeCurrentAssembly)
{ {
@ -215,8 +203,13 @@ namespace MediaBrowser.Common.Kernel
/// </summary> /// </summary>
protected virtual void OnComposablePartsLoaded() protected virtual void OnComposablePartsLoaded()
{ {
foreach (var logger in Loggers)
{
logger.Initialize(this);
}
// Start-up each plugin // Start-up each plugin
foreach (BasePlugin plugin in Plugins) foreach (var plugin in Plugins)
{ {
plugin.Initialize(this); plugin.Initialize(this);
} }
@ -230,17 +223,16 @@ namespace MediaBrowser.Common.Kernel
//Configuration information for anything other than server-specific configuration will have to come via the API... -ebr //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
// Deserialize config // Deserialize config
if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath)) // Use try/catch to avoid the extra file system lookup using File.Exists
try
{
Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
}
catch (FileNotFoundException)
{ {
Configuration = new TConfigurationType(); Configuration = new TConfigurationType();
XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath); XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
} }
else
{
Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
}
Logger.LoggerInstance.LogSeverity = Configuration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info;
} }
/// <summary> /// <summary>
@ -275,11 +267,9 @@ namespace MediaBrowser.Common.Kernel
{ {
Logger.LogInfo("Beginning Kernel.Dispose"); Logger.LogInfo("Beginning Kernel.Dispose");
DisposeComposableParts();
DisposeHttpServer(); DisposeHttpServer();
DisposeLogger(); DisposeComposableParts();
} }
/// <summary> /// <summary>
@ -287,22 +277,9 @@ namespace MediaBrowser.Common.Kernel
/// </summary> /// </summary>
protected virtual void DisposeComposableParts() protected virtual void DisposeComposableParts()
{ {
DisposePlugins(); if (CompositionContainer != null)
}
/// <summary>
/// Disposes all plugins
/// </summary>
private void DisposePlugins()
{ {
if (Plugins != null) CompositionContainer.Dispose();
{
Logger.LogInfo("Disposing Plugins");
foreach (BasePlugin plugin in Plugins)
{
plugin.Dispose();
}
} }
} }
@ -324,21 +301,6 @@ namespace MediaBrowser.Common.Kernel
} }
} }
/// <summary>
/// Disposes the current Logger instance
/// </summary>
private void DisposeLogger()
{
Trace.Listeners.Clear();
if (Logger.LoggerInstance != null)
{
Logger.LogInfo("Disposing Logger");
Logger.LoggerInstance.Dispose();
}
}
/// <summary> /// <summary>
/// Gets the current application version /// Gets the current application version
/// </summary> /// </summary>
@ -354,11 +316,8 @@ namespace MediaBrowser.Common.Kernel
{ {
progress.Report(new TaskProgress { Description = message }); progress.Report(new TaskProgress { Description = message });
if (Logger.LoggerInstance != null)
{
Logger.LogInfo(message); Logger.LogInfo(message);
} }
}
BaseApplicationPaths IKernel.ApplicationPaths BaseApplicationPaths IKernel.ApplicationPaths
{ {
@ -373,6 +332,7 @@ namespace MediaBrowser.Common.Kernel
Task Init(IProgress<TaskProgress> progress); Task Init(IProgress<TaskProgress> progress);
Task Reload(IProgress<TaskProgress> progress); Task Reload(IProgress<TaskProgress> progress);
IEnumerable<BaseLogger> Loggers { get; }
void Dispose(); void Dispose();
} }
} }

View File

@ -1,92 +1,16 @@
using System; using MediaBrowser.Common.Kernel;
using System.Text; using System;
using System.Threading;
namespace MediaBrowser.Common.Logging namespace MediaBrowser.Common.Logging
{ {
public abstract class BaseLogger : IDisposable public abstract class BaseLogger : IDisposable
{ {
public LogSeverity LogSeverity { get; set; } public abstract void Initialize(IKernel kernel);
public abstract void LogEntry(LogRow row);
public void LogInfo(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Info, paramList);
}
public void LogDebugInfo(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Debug, paramList);
}
public void LogError(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Error, paramList);
}
public void LogException(string message, Exception exception, params object[] paramList)
{
var builder = new StringBuilder();
if (exception != null)
{
builder.AppendFormat("Exception. Type={0} Msg={1} StackTrace={3}{2}",
exception.GetType().FullName,
exception.Message,
exception.StackTrace,
Environment.NewLine);
}
message = FormatMessage(message, paramList);
LogError(string.Format("{0} ( {1} )", message, builder));
}
public void LogWarning(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Warning, paramList);
}
private string FormatMessage(string message, params object[] paramList)
{
if (paramList != null)
{
for (int i = 0; i < paramList.Length; i++)
{
message = message.Replace("{" + i + "}", paramList[i].ToString());
}
}
return message;
}
private void LogEntry(string message, LogSeverity severity, params object[] paramList)
{
if (severity < LogSeverity) return;
message = FormatMessage(message, paramList);
Thread currentThread = Thread.CurrentThread;
var row = new LogRow
{
Severity = severity,
Message = message,
ThreadId = currentThread.ManagedThreadId,
ThreadName = currentThread.Name,
Time = DateTime.Now
};
LogEntry(row);
}
protected virtual void Flush()
{
}
public virtual void Dispose() public virtual void Dispose()
{ {
Logger.LogInfo("Disposing " + GetType().Name);
} }
protected abstract void LogEntry(LogRow row);
} }
} }

View File

@ -1,4 +1,4 @@
using System; using System;
namespace MediaBrowser.Common.Logging namespace MediaBrowser.Common.Logging
{ {

View File

@ -1,24 +1,28 @@
using System; using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using MediaBrowser.Common.Kernel;
namespace MediaBrowser.Common.Logging namespace MediaBrowser.Common.Logging
{ {
public static class Logger public static class Logger
{ {
public static BaseLogger LoggerInstance { get; set; } internal static IKernel Kernel { get; set; }
public static void LogInfo(string message, params object[] paramList) public static void LogInfo(string message, params object[] paramList)
{ {
LoggerInstance.LogInfo(message, paramList); LogEntry(message, LogSeverity.Info, paramList);
} }
public static void LogDebugInfo(string message, params object[] paramList) public static void LogDebugInfo(string message, params object[] paramList)
{ {
LoggerInstance.LogDebugInfo(message, paramList); LogEntry(message, LogSeverity.Debug, paramList);
} }
public static void LogError(string message, params object[] paramList) public static void LogError(string message, params object[] paramList)
{ {
LoggerInstance.LogError(message, paramList); LogEntry(message, LogSeverity.Error, paramList);
} }
public static void LogException(Exception ex, params object[] paramList) public static void LogException(Exception ex, params object[] paramList)
@ -28,12 +32,62 @@ namespace MediaBrowser.Common.Logging
public static void LogException(string message, Exception ex, params object[] paramList) public static void LogException(string message, Exception ex, params object[] paramList)
{ {
LoggerInstance.LogException(message, ex, paramList); var builder = new StringBuilder();
if (ex != null)
{
builder.AppendFormat("Exception. Type={0} Msg={1} StackTrace={3}{2}",
ex.GetType().FullName,
ex.Message,
ex.StackTrace,
Environment.NewLine);
}
message = FormatMessage(message, paramList);
LogError(string.Format("{0} ( {1} )", message, builder));
} }
public static void LogWarning(string message, params object[] paramList) public static void LogWarning(string message, params object[] paramList)
{ {
LoggerInstance.LogWarning(message, paramList); LogEntry(message, LogSeverity.Warning, paramList);
}
private static void LogEntry(string message, LogSeverity severity, params object[] paramList)
{
message = FormatMessage(message, paramList);
Thread currentThread = Thread.CurrentThread;
var row = new LogRow
{
Severity = severity,
Message = message,
ThreadId = currentThread.ManagedThreadId,
ThreadName = currentThread.Name,
Time = DateTime.Now
};
if (Kernel.Loggers != null)
{
foreach (var logger in Kernel.Loggers)
{
logger.LogEntry(row);
}
}
}
private static string FormatMessage(string message, params object[] paramList)
{
if (paramList != null)
{
for (int i = 0; i < paramList.Length; i++)
{
message = message.Replace("{" + i + "}", paramList[i].ToString());
}
}
return message;
} }
} }
} }

View File

@ -1,37 +0,0 @@
using System;
using System.IO;
using System.Text;
namespace MediaBrowser.Common.Logging
{
/// <summary>
/// Provides a Logger that can write to any Stream
/// </summary>
public class StreamLogger : BaseLogger
{
private Stream Stream { get; set; }
public StreamLogger(Stream stream)
: base()
{
Stream = stream;
}
protected override void LogEntry(LogRow row)
{
byte[] bytes = new UTF8Encoding().GetBytes(row.ToString() + Environment.NewLine);
lock (Stream)
{
Stream.Write(bytes, 0, bytes.Length);
Stream.Flush();
}
}
public override void Dispose()
{
base.Dispose();
Stream.Dispose();
}
}
}

View File

@ -0,0 +1,38 @@
using MediaBrowser.Common.Kernel;
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
namespace MediaBrowser.Common.Logging
{
[Export(typeof(BaseLogger))]
public class TraceFileLogger : BaseLogger
{
private TraceListener Listener { get; set; }
public override void Initialize(IKernel kernel)
{
DateTime now = DateTime.Now;
string logFilePath = Path.Combine(kernel.ApplicationPaths.LogDirectoryPath, "log-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
Listener = new TextWriterTraceListener(logFilePath);
Trace.Listeners.Add(Listener);
Trace.AutoFlush = true;
}
public override void Dispose()
{
base.Dispose();
Trace.Listeners.Remove(Listener);
Listener.Dispose();
}
public override void LogEntry(LogRow row)
{
Trace.WriteLine(row.ToString());
}
}
}

View File

@ -1,12 +0,0 @@
using System.Diagnostics;
namespace MediaBrowser.Common.Logging
{
public class TraceLogger : BaseLogger
{
protected override void LogEntry(LogRow row)
{
Trace.WriteLine(row.ToString());
}
}
}

View File

@ -83,8 +83,9 @@
<ItemGroup> <ItemGroup>
<Compile Include="Events\GenericEventArgs.cs" /> <Compile Include="Events\GenericEventArgs.cs" />
<Compile Include="Kernel\BaseApplicationPaths.cs" /> <Compile Include="Kernel\BaseApplicationPaths.cs" />
<Compile Include="Drawing\DrawingUtils.cs" /> <Compile Include="Logging\BaseLogger.cs" />
<Compile Include="Logging\TraceLogger.cs" /> <Compile Include="Logging\LogSeverity.cs" />
<Compile Include="Logging\TraceFileLogger.cs" />
<Compile Include="Net\Handlers\StaticFileHandler.cs" /> <Compile Include="Net\Handlers\StaticFileHandler.cs" />
<Compile Include="Net\MimeTypes.cs" /> <Compile Include="Net\MimeTypes.cs" />
<Compile Include="Plugins\BaseTheme.cs" /> <Compile Include="Plugins\BaseTheme.cs" />
@ -96,11 +97,8 @@
<Compile Include="Serialization\JsonSerializer.cs" /> <Compile Include="Serialization\JsonSerializer.cs" />
<Compile Include="Kernel\BaseKernel.cs" /> <Compile Include="Kernel\BaseKernel.cs" />
<Compile Include="Kernel\KernelContext.cs" /> <Compile Include="Kernel\KernelContext.cs" />
<Compile Include="Logging\BaseLogger.cs" />
<Compile Include="Logging\Logger.cs" /> <Compile Include="Logging\Logger.cs" />
<Compile Include="Logging\LogRow.cs" /> <Compile Include="Logging\LogRow.cs" />
<Compile Include="Logging\LogSeverity.cs" />
<Compile Include="Logging\StreamLogger.cs" />
<Compile Include="Net\Handlers\BaseEmbeddedResourceHandler.cs" /> <Compile Include="Net\Handlers\BaseEmbeddedResourceHandler.cs" />
<Compile Include="Net\Handlers\BaseHandler.cs" /> <Compile Include="Net\Handlers\BaseHandler.cs" />
<Compile Include="Net\Handlers\BaseSerializationHandler.cs" /> <Compile Include="Net\Handlers\BaseSerializationHandler.cs" />

View File

@ -1,4 +1,5 @@
using MediaBrowser.Common.Kernel; using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Logging;
using MediaBrowser.Common.Serialization; using MediaBrowser.Common.Serialization;
using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Plugins;
using System; using System;
@ -200,6 +201,8 @@ namespace MediaBrowser.Common.Plugins
/// </summary> /// </summary>
public void Dispose() public void Dispose()
{ {
Logger.LogInfo("Disposing {0} Plugin", Name);
if (Context == KernelContext.Server) if (Context == KernelContext.Server)
{ {
DisposeOnServer(); DisposeOnServer();

View File

@ -63,11 +63,8 @@ namespace MediaBrowser.Common.UI
InstantiateMainWindow().Show(); InstantiateMainWindow().Show();
} }
catch (Exception ex) catch (Exception ex)
{
if (Logger.LoggerInstance != null)
{ {
Logger.LogException(ex); Logger.LogException(ex);
}
MessageBox.Show("There was an error launching Media Browser: " + ex.Message); MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
splash.Close(); splash.Close();

View File

@ -0,0 +1,33 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities;
using System.Drawing;
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 the primary image for a BaseEntity (Person, Studio, User, etc)
/// </summary>
/// <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>
public abstract void ProcessImage(Bitmap bitmap, Graphics graphics, BaseEntity entity);
/// <summary>
/// Processes an image for a BaseItem
/// </summary>
/// <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(Bitmap bitmap, Graphics graphics, BaseItem entity, ImageType imageType, int imageIndex);
}
}

View File

@ -1,7 +1,7 @@
using System; using System;
using System.Drawing; using System.Drawing;
namespace MediaBrowser.Common.Drawing namespace MediaBrowser.Controller.Drawing
{ {
public static class DrawingUtils public static class DrawingUtils
{ {

View File

@ -1,26 +1,34 @@
using MediaBrowser.Common.Drawing; using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities;
using System; using System;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Linq;
namespace MediaBrowser.Api namespace MediaBrowser.Controller.Drawing
{ {
public static class ImageProcessor public static class ImageProcessor
{ {
/// <summary> /// <summary>
/// Resizes an image from a source stream and saves the result to an output stream /// Processes an image by resizing to target dimensions
/// </summary> /// </summary>
/// <param name="sourceImageStream">The stream containing the source image</param>
/// <param name="toStream">The stream to save the new image to</param>
/// <param name="width">Use if a fixed width is required. Aspect ratio will be preserved.</param> /// <param name="width">Use if a fixed width is required. Aspect ratio will be preserved.</param>
/// <param name="height">Use if a fixed height is required. Aspect ratio will be preserved.</param> /// <param name="height">Use if a fixed height is required. Aspect ratio will be preserved.</param>
/// <param name="maxWidth">Use if a max width is required. Aspect ratio will be preserved.</param> /// <param name="maxWidth">Use if a max width is required. Aspect ratio will be preserved.</param>
/// <param name="maxHeight">Use if a max height is required. Aspect ratio will be preserved.</param> /// <param name="maxHeight">Use if a max height is required. Aspect ratio will be preserved.</param>
/// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param> /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
public static void ProcessImage(Stream sourceImageStream, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality) /// <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 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); Image originalImage = Image.FromStream(sourceImageStream);
// Determine the output size based on incoming parameters
Size newSize = DrawingUtils.Resize(originalImage.Size, width, height, maxWidth, maxHeight); Size newSize = DrawingUtils.Resize(originalImage.Size, width, height, maxWidth, maxHeight);
Bitmap thumbnail; Bitmap thumbnail;
@ -35,6 +43,7 @@ namespace MediaBrowser.Api
thumbnail = new Bitmap(newSize.Width, newSize.Height, originalImage.PixelFormat); thumbnail = new Bitmap(newSize.Width, newSize.Height, originalImage.PixelFormat);
} }
// Preserve the original resolution
thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution); thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
Graphics thumbnailGraph = Graphics.FromImage(thumbnail); Graphics thumbnailGraph = Graphics.FromImage(thumbnail);
@ -47,32 +56,67 @@ namespace MediaBrowser.Api
thumbnailGraph.DrawImage(originalImage, 0, 0, newSize.Width, newSize.Height); thumbnailGraph.DrawImage(originalImage, 0, 0, newSize.Width, newSize.Height);
Write(originalImage, thumbnail, toStream, quality); // 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(); thumbnailGraph.Dispose();
thumbnail.Dispose(); thumbnail.Dispose();
originalImage.Dispose(); originalImage.Dispose();
} }
private static void Write(Image originalImage, Image newImage, Stream toStream, int? quality) /// <summary>
/// Executes additional image processors that are registered with the Kernel
/// </summary>
/// <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(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 // 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 // All other formats use the generic Image.Save
if (ImageFormat.Jpeg.Equals(originalImage.RawFormat)) if (ImageFormat.Jpeg.Equals(originalImageRawFormat))
{ {
SaveJpeg(newImage, toStream, quality); SaveJpeg(newImage, toStream, quality);
} }
else if (ImageFormat.Png.Equals(originalImage.RawFormat)) else if (ImageFormat.Png.Equals(originalImageRawFormat))
{ {
newImage.Save(toStream, ImageFormat.Png); newImage.Save(toStream, ImageFormat.Png);
} }
else else
{ {
newImage.Save(toStream, originalImage.RawFormat); newImage.Save(toStream, originalImageRawFormat);
} }
} }
private static void SaveJpeg(Image newImage, Stream target, int? quality) public static void SaveJpeg(Image image, Stream target, int? quality)
{ {
if (!quality.HasValue) if (!quality.HasValue)
{ {
@ -82,11 +126,11 @@ namespace MediaBrowser.Api
using (var encoderParameters = new EncoderParameters(1)) using (var encoderParameters = new EncoderParameters(1))
{ {
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality.Value); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality.Value);
newImage.Save(target, GetImageCodeInfo("image/jpeg"), encoderParameters); image.Save(target, GetImageCodecInfo("image/jpeg"), encoderParameters);
} }
} }
private static ImageCodecInfo GetImageCodeInfo(string mimeType) public static ImageCodecInfo GetImageCodecInfo(string mimeType)
{ {
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();

View File

@ -1,5 +1,6 @@
using MediaBrowser.Common.Kernel; using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Logging; using MediaBrowser.Common.Logging;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.IO; using MediaBrowser.Controller.IO;
@ -27,7 +28,6 @@ namespace MediaBrowser.Controller
public static Kernel Instance { get; private set; } public static Kernel Instance { get; private set; }
public ItemController ItemController { get; private set; } public ItemController ItemController { get; private set; }
public WeatherClient WeatherClient { get; private set; }
public IEnumerable<User> Users { get; private set; } public IEnumerable<User> Users { get; private set; }
public Folder RootFolder { get; private set; } public Folder RootFolder { get; private set; }
@ -47,6 +47,12 @@ namespace MediaBrowser.Controller
get { return KernelContext.Server; } get { return KernelContext.Server; }
} }
/// <summary>
/// Gets the list of currently registered weather prvoiders
/// </summary>
[ImportMany(typeof(BaseWeatherProvider))]
public IEnumerable<BaseWeatherProvider> WeatherProviders { get; private set; }
/// <summary> /// <summary>
/// Gets the list of currently registered metadata prvoiders /// Gets the list of currently registered metadata prvoiders
/// </summary> /// </summary>
@ -71,6 +77,12 @@ namespace MediaBrowser.Controller
/// </summary> /// </summary>
internal IBaseItemResolver[] EntityResolvers { get; private set; } internal IBaseItemResolver[] EntityResolvers { get; private set; }
/// <summary>
/// Gets the list of currently registered entity resolvers
/// </summary>
[ImportMany(typeof(BaseImageProcessor))]
internal IEnumerable<BaseImageProcessor> ImageProcessors { get; private set; }
/// <summary> /// <summary>
/// Creates a kernel based on a Data path, which is akin to our current programdata path /// Creates a kernel based on a Data path, which is akin to our current programdata path
/// </summary> /// </summary>
@ -85,13 +97,15 @@ namespace MediaBrowser.Controller
/// </summary> /// </summary>
protected override void InitializeInternal(IProgress<TaskProgress> progress) protected override void InitializeInternal(IProgress<TaskProgress> progress)
{ {
base.InitializeInternal(progress);
ItemController = new ItemController(); ItemController = new ItemController();
DirectoryWatchers = new DirectoryWatchers(); DirectoryWatchers = new DirectoryWatchers();
ItemController.PreBeginResolvePath += ItemController_PreBeginResolvePath; ItemController.PreBeginResolvePath += ItemController_PreBeginResolvePath;
ItemController.BeginResolvePath += ItemController_BeginResolvePath; ItemController.BeginResolvePath += ItemController_BeginResolvePath;
base.InitializeInternal(progress); ExtractFFMpeg();
} }
/// <summary> /// <summary>
@ -101,14 +115,11 @@ namespace MediaBrowser.Controller
{ {
await base.ReloadInternal(progress).ConfigureAwait(false); await base.ReloadInternal(progress).ConfigureAwait(false);
ReloadWeatherClient();
ExtractFFMpeg();
ReportProgress(progress, "Loading Users"); ReportProgress(progress, "Loading Users");
ReloadUsers(); ReloadUsers();
ReportProgress(progress, "Loading Media Library"); ReportProgress(progress, "Loading Media Library");
await ReloadRoot(allowInternetProviders: false).ConfigureAwait(false); await ReloadRoot(allowInternetProviders: false).ConfigureAwait(false);
} }
@ -121,8 +132,6 @@ namespace MediaBrowser.Controller
DirectoryWatchers.Stop(); DirectoryWatchers.Stop();
DisposeWeatherClient();
ItemController.PreBeginResolvePath -= ItemController_PreBeginResolvePath; ItemController.PreBeginResolvePath -= ItemController_PreBeginResolvePath;
ItemController.BeginResolvePath -= ItemController_BeginResolvePath; ItemController.BeginResolvePath -= ItemController_BeginResolvePath;
} }
@ -413,26 +422,5 @@ namespace MediaBrowser.Controller
} }
} }
} }
/// <summary>
/// Disposes the current WeatherClient
/// </summary>
private void DisposeWeatherClient()
{
if (WeatherClient != null)
{
WeatherClient.Dispose();
}
}
/// <summary>
/// Disposes the current WeatherClient and creates a new one
/// </summary>
private void ReloadWeatherClient()
{
DisposeWeatherClient();
WeatherClient = new WeatherClient();
}
} }
} }

View File

@ -36,6 +36,7 @@
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" /> <Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" /> <Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Reactive.Core, Version=2.0.20823.0, Culture=neutral, PublicKeyToken=f300afd708cefcd3, processorArchitecture=MSIL"> <Reference Include="System.Reactive.Core, Version=2.0.20823.0, Culture=neutral, PublicKeyToken=f300afd708cefcd3, processorArchitecture=MSIL">
@ -58,6 +59,9 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Drawing\BaseImageProcessor.cs" />
<Compile Include="Drawing\DrawingUtils.cs" />
<Compile Include="Drawing\ImageProcessor.cs" />
<Compile Include="Entities\Audio.cs" /> <Compile Include="Entities\Audio.cs" />
<Compile Include="Entities\BaseEntity.cs" /> <Compile Include="Entities\BaseEntity.cs" />
<Compile Include="Entities\BaseItem.cs" /> <Compile Include="Entities\BaseItem.cs" />
@ -107,7 +111,8 @@
<Compile Include="Resolvers\BaseItemResolver.cs" /> <Compile Include="Resolvers\BaseItemResolver.cs" />
<Compile Include="Resolvers\FolderResolver.cs" /> <Compile Include="Resolvers\FolderResolver.cs" />
<Compile Include="Resolvers\VideoResolver.cs" /> <Compile Include="Resolvers\VideoResolver.cs" />
<Compile Include="Weather\WeatherClient.cs" /> <Compile Include="Weather\BaseWeatherProvider.cs" />
<Compile Include="Weather\WeatherProvider.cs" />
<Compile Include="Providers\BaseItemXmlParser.cs" /> <Compile Include="Providers\BaseItemXmlParser.cs" />
<Compile Include="Xml\XmlExtensions.cs" /> <Compile Include="Xml\XmlExtensions.cs" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,34 @@
using MediaBrowser.Common.Logging;
using MediaBrowser.Model.Weather;
using System;
using System.Net;
using System.Net.Cache;
using System.Net.Http;
using System.Threading.Tasks;
namespace MediaBrowser.Controller.Weather
{
public abstract class BaseWeatherProvider : IDisposable
{
protected HttpClient HttpClient { get; private set; }
protected BaseWeatherProvider()
{
var handler = new WebRequestHandler { };
handler.AutomaticDecompression = DecompressionMethods.Deflate;
handler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
HttpClient = new HttpClient(handler);
}
public virtual void Dispose()
{
Logger.LogInfo("Disposing " + GetType().Name);
HttpClient.Dispose();
}
public abstract Task<WeatherInfo> GetWeatherInfoAsync(string zipCode);
}
}

View File

@ -2,11 +2,9 @@
using MediaBrowser.Common.Serialization; using MediaBrowser.Common.Serialization;
using MediaBrowser.Model.Weather; using MediaBrowser.Model.Weather;
using System; using System;
using System.ComponentModel.Composition;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace MediaBrowser.Controller.Weather namespace MediaBrowser.Controller.Weather
@ -15,21 +13,10 @@ namespace MediaBrowser.Controller.Weather
/// Based on http://www.worldweatheronline.com/free-weather-feed.aspx /// Based on http://www.worldweatheronline.com/free-weather-feed.aspx
/// The classes in this file are a reproduction of the json output, which will then be converted to our weather model classes /// The classes in this file are a reproduction of the json output, which will then be converted to our weather model classes
/// </summary> /// </summary>
public class WeatherClient : IDisposable [Export(typeof(BaseWeatherProvider))]
public class WeatherProvider : BaseWeatherProvider
{ {
private HttpClient HttpClient { get; set; } public override async Task<WeatherInfo> GetWeatherInfoAsync(string zipCode)
public WeatherClient()
{
var handler = new WebRequestHandler { };
handler.AutomaticDecompression = DecompressionMethods.Deflate;
handler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
HttpClient = new HttpClient(handler);
}
public async Task<WeatherInfo> GetWeatherInfoAsync(string zipCode)
{ {
if (string.IsNullOrWhiteSpace(zipCode)) if (string.IsNullOrWhiteSpace(zipCode))
{ {
@ -73,11 +60,6 @@ namespace MediaBrowser.Controller.Weather
return info; return info;
} }
public void Dispose()
{
HttpClient.Dispose();
}
} }
class WeatherResult class WeatherResult

View File

@ -52,4 +52,7 @@ Global
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
EndGlobal EndGlobal