Created IConfigurationManager

This commit is contained in:
LukePulverenti
2013-03-04 00:43:06 -05:00
parent 401b56c732
commit 2ca4b7d03a
106 changed files with 1343 additions and 2437 deletions

View File

@@ -1,4 +1,9 @@
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Implementations.Logging;
using MediaBrowser.Common.Implementations.NetworkManagement;
using MediaBrowser.Common.Implementations.ScheduledTasks;
using MediaBrowser.Common.Implementations.Security;
using MediaBrowser.Common.Implementations.Serialization;
using MediaBrowser.Common.Implementations.Udp;
using MediaBrowser.Common.Implementations.Updates;
using MediaBrowser.Common.Implementations.WebSocket;
@@ -6,9 +11,11 @@ using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Common.Security;
using MediaBrowser.Common.Updates;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Updates;
using SimpleInjector;
using System;
using System.Collections.Generic;
@@ -16,16 +23,18 @@ using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Implementations
{
public abstract class BaseApplicationHost
public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationHost
where TApplicationPathsType : class, IApplicationPaths, new()
{
/// <summary>
/// Gets or sets the logger.
/// </summary>
/// <value>The logger.</value>
public ILogger Logger { get; protected set; }
protected ILogger Logger { get; private set; }
/// <summary>
/// Gets or sets the plugins.
@@ -43,13 +52,23 @@ namespace MediaBrowser.Common.Implementations
/// Gets the application paths.
/// </summary>
/// <value>The application paths.</value>
protected IApplicationPaths ApplicationPaths { get; private set; }
protected TApplicationPathsType ApplicationPaths = new TApplicationPathsType();
/// <summary>
/// The container
/// </summary>
protected readonly Container Container = new Container();
/// <summary>
/// The json serializer
/// </summary>
protected readonly IJsonSerializer JsonSerializer = new JsonSerializer();
/// <summary>
/// The _XML serializer
/// </summary>
protected readonly IXmlSerializer XmlSerializer = new XmlSerializer();
/// <summary>
/// Gets assemblies that failed to load
/// </summary>
@@ -109,12 +128,26 @@ namespace MediaBrowser.Common.Implementations
}
}
/// <summary>
/// Gets the kernel.
/// </summary>
/// <value>The kernel.</value>
protected IKernel Kernel { get; private set; }
protected ITaskManager TaskManager { get; private set; }
protected ISecurityManager SecurityManager { get; private set; }
protected IConfigurationManager ConfigurationManager { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="BaseApplicationHost" /> class.
/// </summary>
protected BaseApplicationHost()
{
FailedAssemblies = new List<string>();
LogManager = new NlogManager(ApplicationPaths.LogDirectoryPath, LogFilePrefixName);
ConfigurationManager = GetConfigurationManager();
}
/// <summary>
@@ -125,15 +158,25 @@ namespace MediaBrowser.Common.Implementations
{
return Task.Run(() =>
{
ApplicationPaths = GetApplicationPaths();
LogManager = GetLogManager();
Logger = LogManager.GetLogger("App");
IsFirstRun = !File.Exists(ApplicationPaths.SystemConfigurationFilePath);
DiscoverTypes();
LogManager.ReloadLogger(ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info);
Logger.Info("Version {0} initializing", ApplicationVersion);
Kernel = GetKernel();
RegisterResources();
FindParts();
Task.Run(() => ConfigureAutoRunAtStartup());
Kernel.Init();
});
}
@@ -144,16 +187,13 @@ namespace MediaBrowser.Common.Implementations
protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
/// <summary>
/// Gets the log manager.
/// Gets the name of the log file prefix.
/// </summary>
/// <returns>ILogManager.</returns>
protected abstract ILogManager GetLogManager();
/// <value>The name of the log file prefix.</value>
protected abstract string LogFilePrefixName { get; }
/// <summary>
/// Gets the application paths.
/// </summary>
/// <returns>IApplicationPaths.</returns>
protected abstract IApplicationPaths GetApplicationPaths();
protected abstract IKernel GetKernel();
protected abstract IConfigurationManager GetConfigurationManager();
/// <summary>
/// Finds the parts.
@@ -184,21 +224,44 @@ namespace MediaBrowser.Common.Implementations
/// <summary>
/// Registers resources that classes will depend on
/// </summary>
protected virtual void RegisterResources(ITaskManager taskManager, INetworkManager networkManager, IServerManager serverManager)
protected virtual void RegisterResources()
{
RegisterSingleInstance(ConfigurationManager);
RegisterSingleInstance<IApplicationHost>(this);
RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
var networkManager = new NetworkManager();
var serverManager = new ServerManager.ServerManager(this, Kernel, networkManager, JsonSerializer, Logger, ConfigurationManager);
TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger, serverManager);
RegisterSingleInstance(JsonSerializer);
RegisterSingleInstance(XmlSerializer);
RegisterSingleInstance(LogManager);
RegisterSingleInstance(Logger);
RegisterSingleInstance(ApplicationPaths);
RegisterSingleInstance(taskManager);
RegisterSingleInstance(Kernel);
RegisterSingleInstance(TaskManager);
RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
RegisterSingleInstance(ProtobufSerializer);
RegisterSingleInstance<IUdpServer>(new UdpServer(Logger), false);
RegisterSingleInstance<IPackageManager>(new PackageManager());
RegisterSingleInstance<IHttpClient>(new HttpClientManager.HttpClientManager(ApplicationPaths, Logger));
RegisterSingleInstance(networkManager);
RegisterSingleInstance(serverManager);
var httpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger);
RegisterSingleInstance<IHttpClient>(httpClient);
RegisterSingleInstance<INetworkManager>(networkManager);
RegisterSingleInstance<IServerManager>(serverManager);
SecurityManager = new PluginSecurityManager(Kernel, httpClient, JsonSerializer, ApplicationPaths);
RegisterSingleInstance(SecurityManager);
RegisterSingleInstance<IPackageManager>(new PackageManager(SecurityManager, networkManager, httpClient, ApplicationPaths, JsonSerializer, Logger));
}
/// <summary>
@@ -336,7 +399,7 @@ namespace MediaBrowser.Common.Implementations
Logger.Info("Composing instances of " + currentType.Name);
var parts = AllConcreteTypes.Where(currentType.IsAssignableFrom).Select(CreateInstance).Cast<T>().ToArray();
var parts = AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom).Select(CreateInstance).Cast<T>().ToArray();
if (manageLiftime)
{
@@ -361,10 +424,8 @@ namespace MediaBrowser.Common.Implementations
/// <summary>
/// Configures the auto run at startup.
/// </summary>
/// <param name="autorun">if set to <c>true</c> [autorun].</param>
public void ConfigureAutoRunAtStartup(bool autorun)
private void ConfigureAutoRunAtStartup()
{
}
/// <summary>
@@ -409,5 +470,15 @@ namespace MediaBrowser.Common.Implementations
}
}
}
public abstract void Restart();
public abstract bool CanSelfUpdate { get; }
public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress);
public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress);
public abstract void Shutdown();
}
}

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Kernel;
using System;
using System.Configuration;
using System.IO;

View File

@@ -0,0 +1,123 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Threading;
namespace MediaBrowser.Common.Implementations.Configuration
{
/// <summary>
/// Class BaseConfigurationManager
/// </summary>
public abstract class BaseConfigurationManager : IConfigurationManager
{
/// <summary>
/// Gets the type of the configuration.
/// </summary>
/// <value>The type of the configuration.</value>
protected abstract Type ConfigurationType { get; }
/// <summary>
/// Occurs when [configuration updated].
/// </summary>
public event EventHandler<EventArgs> ConfigurationUpdated;
/// <summary>
/// Gets the logger.
/// </summary>
/// <value>The logger.</value>
protected ILogger Logger { get; private set; }
/// <summary>
/// Gets the XML serializer.
/// </summary>
/// <value>The XML serializer.</value>
protected IXmlSerializer XmlSerializer { get; private set; }
/// <summary>
/// Gets or sets the application paths.
/// </summary>
/// <value>The application paths.</value>
public IApplicationPaths CommonApplicationPaths { get; private set; }
/// <summary>
/// The _configuration loaded
/// </summary>
private bool _configurationLoaded;
/// <summary>
/// The _configuration sync lock
/// </summary>
private object _configurationSyncLock = new object();
/// <summary>
/// The _configuration
/// </summary>
private BaseApplicationConfiguration _configuration;
/// <summary>
/// Gets the system configuration
/// </summary>
/// <value>The configuration.</value>
public BaseApplicationConfiguration CommonConfiguration
{
get
{
// Lazy load
LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer));
return _configuration;
}
protected set
{
_configuration = value;
_configurationLoaded = value != null;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="BaseConfigurationManager" /> class.
/// </summary>
/// <param name="applicationPaths">The application paths.</param>
/// <param name="logManager">The log manager.</param>
/// <param name="xmlSerializer">The XML serializer.</param>
protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer)
{
CommonApplicationPaths = applicationPaths;
XmlSerializer = xmlSerializer;
Logger = logManager.GetLogger(GetType().Name);
}
/// <summary>
/// The _save lock
/// </summary>
private readonly object _configurationSaveLock = new object();
/// <summary>
/// Saves the configuration.
/// </summary>
public void SaveConfiguration()
{
lock (_configurationSaveLock)
{
XmlSerializer.SerializeToFile(CommonConfiguration, CommonApplicationPaths.SystemConfigurationFilePath);
}
EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
}
/// <summary>
/// Replaces the configuration.
/// </summary>
/// <param name="newConfiguration">The new configuration.</param>
/// <exception cref="System.ArgumentNullException">newConfiguration</exception>
public void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
{
if (newConfiguration == null)
{
throw new ArgumentNullException("newConfiguration");
}
CommonConfiguration = newConfiguration;
SaveConfiguration();
}
}
}

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Logging;

View File

@@ -1,7 +1,5 @@
using System.Collections.Generic;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Logging;
using ServiceStack.Common;
@@ -9,6 +7,7 @@ using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
@@ -22,12 +21,6 @@ namespace MediaBrowser.Common.Implementations.HttpServer
/// </summary>
public class BaseRestService : Service, IRestfulService
{
/// <summary>
/// Gets or sets the kernel.
/// </summary>
/// <value>The kernel.</value>
public IKernel Kernel { get; set; }
/// <summary>
/// Gets or sets the logger.
/// </summary>

View File

@@ -38,6 +38,9 @@
<Reference Include="Alchemy">
<HintPath>..\packages\Alchemy.2.2.1\lib\net40\Alchemy.dll</HintPath>
</Reference>
<Reference Include="Mediabrowser.PluginSecurity">
<HintPath>..\ThirdParty\PluginSecurity\Mediabrowser.PluginSecurity.dll</HintPath>
</Reference>
<Reference Include="NLog">
<HintPath>..\packages\NLog.2.0.0.2000\lib\net40\NLog.dll</HintPath>
</Reference>
@@ -104,6 +107,7 @@
</Compile>
<Compile Include="BaseApplicationHost.cs" />
<Compile Include="BaseApplicationPaths.cs" />
<Compile Include="Configuration\BaseConfigurationManager.cs" />
<Compile Include="HttpClientManager\HttpClientManager.cs" />
<Compile Include="HttpServer\BaseRestService.cs" />
<Compile Include="HttpServer\HttpServer.cs" />
@@ -123,6 +127,7 @@
<Compile Include="ScheduledTasks\Tasks\DeleteLogFileTask.cs" />
<Compile Include="ScheduledTasks\Tasks\ReloadLoggerTask.cs" />
<Compile Include="ScheduledTasks\Tasks\SystemUpdateTask.cs" />
<Compile Include="Security\PluginSecurityManager.cs" />
<Compile Include="Serialization\JsonSerializer.cs" />
<Compile Include="Serialization\ProtobufSerializer.cs" />
<Compile Include="Serialization\XmlSerializer.cs" />

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Model.Logging;

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;

View File

@@ -1,4 +1,4 @@
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Model.Logging;
using System;
@@ -16,10 +16,10 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
public class DeleteCacheFileTask : IScheduledTask
{
/// <summary>
/// Gets or sets the kernel.
/// Gets or sets the application paths.
/// </summary>
/// <value>The kernel.</value>
private IKernel Kernel { get; set; }
/// <value>The application paths.</value>
private IApplicationPaths ApplicationPaths { get; set; }
/// <summary>
/// Gets or sets the logger.
/// </summary>
@@ -29,11 +29,11 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
/// <summary>
/// Initializes a new instance of the <see cref="DeleteCacheFileTask" /> class.
/// </summary>
/// <param name="kernel">The kernel.</param>
/// <param name="appPaths">The app paths.</param>
/// <param name="logger">The logger.</param>
public DeleteCacheFileTask(IKernel kernel, ILogger logger)
public DeleteCacheFileTask(IApplicationPaths appPaths, ILogger logger)
{
Kernel = kernel;
ApplicationPaths = appPaths;
Logger = logger;
}
@@ -60,7 +60,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
{
var minDateModified = DateTime.UtcNow.AddMonths(-2);
DeleteCacheFilesFromDirectory(cancellationToken, Kernel.ApplicationPaths.CachePath, minDateModified, progress);
DeleteCacheFilesFromDirectory(cancellationToken, ApplicationPaths.CachePath, minDateModified, progress);
});
}

View File

@@ -1,4 +1,4 @@
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Model.Logging;
using System;
@@ -16,10 +16,10 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
public class DeleteLogFileTask : IScheduledTask
{
/// <summary>
/// Gets or sets the kernel.
/// Gets or sets the configuration manager.
/// </summary>
/// <value>The kernel.</value>
private IKernel Kernel { get; set; }
/// <value>The configuration manager.</value>
private IConfigurationManager ConfigurationManager { get; set; }
/// <summary>
/// Gets or sets the logger.
/// </summary>
@@ -29,11 +29,11 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
/// <summary>
/// Initializes a new instance of the <see cref="DeleteLogFileTask" /> class.
/// </summary>
/// <param name="kernel">The kernel.</param>
/// <param name="configurationManager">The configuration manager.</param>
/// <param name="logger">The logger.</param>
public DeleteLogFileTask(IKernel kernel, ILogger logger)
public DeleteLogFileTask(IConfigurationManager configurationManager, ILogger logger)
{
Kernel = kernel;
ConfigurationManager = configurationManager;
Logger = logger;
}
@@ -59,9 +59,9 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
return Task.Run(() =>
{
// Delete log files more than n days old
var minDateModified = DateTime.UtcNow.AddDays(-(Kernel.Configuration.LogFileRetentionDays));
var minDateModified = DateTime.UtcNow.AddDays(-(ConfigurationManager.CommonConfiguration.LogFileRetentionDays));
var filesToDelete = new DirectoryInfo(Kernel.ApplicationPaths.LogDirectoryPath).EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
var filesToDelete = new DirectoryInfo(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath).EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
.Where(f => f.LastWriteTimeUtc < minDateModified)
.ToList();
@@ -100,7 +100,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
/// <value>The description.</value>
public string Description
{
get { return string.Format("Deletes log files that are more than {0} days old.", Kernel.Configuration.LogFileRetentionDays); }
get { return string.Format("Deletes log files that are more than {0} days old.", ConfigurationManager.CommonConfiguration.LogFileRetentionDays); }
}
/// <summary>

View File

@@ -1,4 +1,4 @@
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Model.Logging;
using System;
@@ -24,22 +24,22 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
/// <value>The logger.</value>
private ILogger Logger { get; set; }
/// <summary>
/// Gets or sets the kernel.
/// Gets or sets the configuration manager.
/// </summary>
/// <value>The kernel.</value>
private IKernel Kernel { get; set; }
/// <value>The configuration manager.</value>
private IConfigurationManager ConfigurationManager { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ReloadLoggerFileTask" /> class.
/// </summary>
/// <param name="logManager">The logManager.</param>
/// <param name="logger">The logger.</param>
/// <param name="kernel">The kernel.</param>
public ReloadLoggerFileTask(ILogManager logManager, ILogger logger, IKernel kernel)
/// <param name="configurationManager">The configuration manager.</param>
public ReloadLoggerFileTask(ILogManager logManager, ILogger logger, IConfigurationManager configurationManager)
{
LogManager = logManager;
Logger = logger;
Kernel = kernel;
ConfigurationManager = configurationManager;
}
/// <summary>
@@ -65,7 +65,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
progress.Report(0);
return Task.Run(() => LogManager.ReloadLogger(Kernel.Configuration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info));
return Task.Run(() => LogManager.ReloadLogger(ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info));
}
/// <summary>

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Model.Logging;
using System;
@@ -19,27 +20,35 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
private readonly IApplicationHost _appHost;
/// <summary>
/// Gets or sets the kernel.
/// Gets or sets the configuration manager.
/// </summary>
/// <value>The kernel.</value>
private IKernel Kernel { get; set; }
/// <value>The configuration manager.</value>
private IConfigurationManager ConfigurationManager { get; set; }
/// <summary>
/// Gets or sets the logger.
/// </summary>
/// <value>The logger.</value>
private ILogger Logger { get; set; }
/// <summary>
/// Gets or sets the kernel.
/// </summary>
/// <value>The kernel.</value>
private IKernel Kernel { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="SystemUpdateTask" /> class.
/// </summary>
/// <param name="appHost">The app host.</param>
/// <param name="kernel">The kernel.</param>
/// <param name="configurationManager">The configuration manager.</param>
/// <param name="logger">The logger.</param>
public SystemUpdateTask(IApplicationHost appHost, IKernel kernel, ILogger logger)
/// <param name="kernel">The kernel.</param>
public SystemUpdateTask(IApplicationHost appHost, IConfigurationManager configurationManager, ILogger logger, IKernel kernel)
{
_appHost = appHost;
Kernel = kernel;
ConfigurationManager = configurationManager;
Logger = logger;
Kernel = kernel;
}
/// <summary>
@@ -88,7 +97,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
cancellationToken.ThrowIfCancellationRequested();
if (Kernel.Configuration.EnableAutoUpdate)
if (ConfigurationManager.CommonConfiguration.EnableAutoUpdate)
{
Logger.Info("Update Revision {0} available. Updating...", updateInfo.AvailableVersion);

View File

@@ -0,0 +1,131 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Security;
using MediaBrowser.Model.Serialization;
using Mediabrowser.Model.Entities;
using Mediabrowser.PluginSecurity;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Net;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Implementations.Security
{
/// <summary>
/// Class PluginSecurityManager
/// </summary>
public class PluginSecurityManager : ISecurityManager
{
/// <summary>
/// The _is MB supporter
/// </summary>
private bool? _isMBSupporter;
/// <summary>
/// The _is MB supporter initialized
/// </summary>
private bool _isMBSupporterInitialized;
/// <summary>
/// The _is MB supporter sync lock
/// </summary>
private object _isMBSupporterSyncLock = new object();
/// <summary>
/// Gets a value indicating whether this instance is MB supporter.
/// </summary>
/// <value><c>true</c> if this instance is MB supporter; otherwise, <c>false</c>.</value>
public bool IsMBSupporter
{
get
{
LazyInitializer.EnsureInitialized(ref _isMBSupporter, ref _isMBSupporterInitialized, ref _isMBSupporterSyncLock, () => GetRegistrationStatus("MBSupporter").Result.IsRegistered);
return _isMBSupporter.Value;
}
}
private IHttpClient _httpClient;
private IJsonSerializer _jsonSerializer;
/// <summary>
/// The _kernel
/// </summary>
private readonly IKernel _kernel;
/// <summary>
/// Initializes a new instance of the <see cref="PluginSecurityManager" /> class.
/// </summary>
/// <param name="kernel">The kernel.</param>
public PluginSecurityManager(IKernel kernel, IHttpClient httpClient, IJsonSerializer jsonSerializer, IApplicationPaths appPaths)
{
if (kernel == null)
{
throw new ArgumentNullException("kernel");
}
if (httpClient == null)
{
throw new ArgumentNullException("httpClient");
}
_kernel = kernel;
_httpClient = httpClient;
_jsonSerializer = jsonSerializer;
//MBRegistration.Init(appPaths);
}
/// <summary>
/// Gets the registration status.
/// </summary>
/// <param name="feature">The feature.</param>
/// <param name="mb2Equivalent">The MB2 equivalent.</param>
/// <returns>Task{MBRegistrationRecord}.</returns>
public async Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent = null)
{
return await MBRegistration.GetRegistrationStatus(_httpClient, _jsonSerializer, feature, mb2Equivalent).ConfigureAwait(false);
}
/// <summary>
/// Gets or sets the supporter key.
/// </summary>
/// <value>The supporter key.</value>
public string SupporterKey
{
get { return MBRegistration.SupporterKey; }
set
{
if (value != MBRegistration.SupporterKey)
{
MBRegistration.SupporterKey = value;
// Clear this so it will re-evaluate
ResetSupporterInfo();
// And we'll need to restart to re-evaluate the status of plug-ins
_kernel.NotifyPendingRestart();
}
}
}
/// <summary>
/// Gets or sets the legacy key.
/// </summary>
/// <value>The legacy key.</value>
public string LegacyKey
{
get { return MBRegistration.LegacyKey; }
set
{
MBRegistration.LegacyKey = value;
// And we'll need to restart to re-evaluate the status of plug-ins
_kernel.NotifyPendingRestart();
}
}
/// <summary>
/// Resets the supporter info.
/// </summary>
private void ResetSupporterInfo()
{
_isMBSupporter = null;
_isMBSupporterInitialized = false;
}
}
}

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
@@ -77,6 +78,12 @@ namespace MediaBrowser.Common.Implementations.ServerManager
/// </summary>
private readonly IKernel _kernel;
/// <summary>
/// Gets or sets the configuration manager.
/// </summary>
/// <value>The configuration manager.</value>
private IConfigurationManager ConfigurationManager { get; set; }
/// <summary>
/// Gets a value indicating whether [supports web socket].
/// </summary>
@@ -92,14 +99,14 @@ namespace MediaBrowser.Common.Implementations.ServerManager
/// <value>The web socket port number.</value>
public int WebSocketPortNumber
{
get { return SupportsNativeWebSocket ? _kernel.Configuration.HttpServerPortNumber : _kernel.Configuration.LegacyWebSocketPortNumber; }
get { return SupportsNativeWebSocket ? ConfigurationManager.CommonConfiguration.HttpServerPortNumber : ConfigurationManager.CommonConfiguration.LegacyWebSocketPortNumber; }
}
/// <summary>
/// Gets the web socket listeners.
/// </summary>
/// <value>The web socket listeners.</value>
private List<IWebSocketListener> WebSocketListeners = new List<IWebSocketListener>();
private readonly List<IWebSocketListener> _webSocketListeners = new List<IWebSocketListener>();
/// <summary>
/// Initializes a new instance of the <see cref="ServerManager" /> class.
@@ -109,8 +116,9 @@ namespace MediaBrowser.Common.Implementations.ServerManager
/// <param name="networkManager">The network manager.</param>
/// <param name="jsonSerializer">The json serializer.</param>
/// <param name="logger">The logger.</param>
/// <param name="configurationManager">The configuration manager.</param>
/// <exception cref="System.ArgumentNullException">applicationHost</exception>
public ServerManager(IApplicationHost applicationHost, IKernel kernel, INetworkManager networkManager, IJsonSerializer jsonSerializer, ILogger logger)
public ServerManager(IApplicationHost applicationHost, IKernel kernel, INetworkManager networkManager, IJsonSerializer jsonSerializer, ILogger logger, IConfigurationManager configurationManager)
{
if (applicationHost == null)
{
@@ -138,6 +146,7 @@ namespace MediaBrowser.Common.Implementations.ServerManager
_kernel = kernel;
_applicationHost = applicationHost;
_networkManager = networkManager;
ConfigurationManager = configurationManager;
}
/// <summary>
@@ -158,7 +167,7 @@ namespace MediaBrowser.Common.Implementations.ServerManager
ReloadExternalWebSocketServer();
}
_kernel.ConfigurationUpdated += _kernel_ConfigurationUpdated;
ConfigurationManager.ConfigurationUpdated += _kernel_ConfigurationUpdated;
}
/// <summary>
@@ -176,7 +185,7 @@ namespace MediaBrowser.Common.Implementations.ServerManager
ExternalWebSocketServer = _applicationHost.Resolve<IWebSocketServer>();
ExternalWebSocketServer.Start(_kernel.Configuration.LegacyWebSocketPortNumber);
ExternalWebSocketServer.Start(ConfigurationManager.CommonConfiguration.LegacyWebSocketPortNumber);
ExternalWebSocketServer.WebSocketConnected += HttpServer_WebSocketConnected;
}
@@ -199,7 +208,7 @@ namespace MediaBrowser.Common.Implementations.ServerManager
try
{
HttpServer = _applicationHost.Resolve<IHttpServer>();
HttpServer.EnableHttpRequestLogging = _kernel.Configuration.EnableHttpLevelLogging;
HttpServer.EnableHttpRequestLogging = ConfigurationManager.CommonConfiguration.EnableHttpLevelLogging;
HttpServer.Start(_kernel.HttpServerUrlPrefix);
}
catch (HttpListenerException ex)
@@ -240,7 +249,7 @@ namespace MediaBrowser.Common.Implementations.ServerManager
/// <param name="result">The result.</param>
private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
{
var tasks = WebSocketListeners.Select(i => Task.Run(async () =>
var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
{
try
{
@@ -435,7 +444,7 @@ namespace MediaBrowser.Common.Implementations.ServerManager
private void RegisterServerWithAdministratorAccess()
{
// Create a temp file path to extract the bat file to
var tmpFile = Path.Combine(_kernel.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".bat");
var tmpFile = Path.Combine(ConfigurationManager.CommonApplicationPaths.TempDirectory, Guid.NewGuid() + ".bat");
// Extract the bat file
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.Common.Implementations.ServerManager.RegisterServer.bat"))
@@ -450,10 +459,10 @@ namespace MediaBrowser.Common.Implementations.ServerManager
{
FileName = tmpFile,
Arguments = string.Format("{0} {1} {2} {3}", _kernel.Configuration.HttpServerPortNumber,
Arguments = string.Format("{0} {1} {2} {3}", ConfigurationManager.CommonConfiguration.HttpServerPortNumber,
_kernel.HttpServerUrlPrefix,
_kernel.UdpServerPortNumber,
_kernel.Configuration.LegacyWebSocketPortNumber),
ConfigurationManager.CommonConfiguration.LegacyWebSocketPortNumber),
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
@@ -508,14 +517,14 @@ namespace MediaBrowser.Common.Implementations.ServerManager
/// <exception cref="System.NotImplementedException"></exception>
void _kernel_ConfigurationUpdated(object sender, EventArgs e)
{
HttpServer.EnableHttpRequestLogging = _kernel.Configuration.EnableHttpLevelLogging;
HttpServer.EnableHttpRequestLogging = ConfigurationManager.CommonConfiguration.EnableHttpLevelLogging;
if (!string.Equals(HttpServer.UrlPrefix, _kernel.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
{
ReloadHttpServer();
}
if (!SupportsNativeWebSocket && ExternalWebSocketServer != null && ExternalWebSocketServer.Port != _kernel.Configuration.LegacyWebSocketPortNumber)
if (!SupportsNativeWebSocket && ExternalWebSocketServer != null && ExternalWebSocketServer.Port != ConfigurationManager.CommonConfiguration.LegacyWebSocketPortNumber)
{
ReloadExternalWebSocketServer();
}
@@ -527,7 +536,7 @@ namespace MediaBrowser.Common.Implementations.ServerManager
/// <param name="listeners">The listeners.</param>
public void AddWebSocketListeners(IEnumerable<IWebSocketListener> listeners)
{
WebSocketListeners.AddRange(listeners);
_webSocketListeners.AddRange(listeners);
}
}
}

View File

@@ -1,37 +1,57 @@
using System;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Security;
using MediaBrowser.Common.Updates;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Updates;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Security;
using MediaBrowser.Common.Updates;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Updates;
namespace MediaBrowser.Common.Implementations.Updates
{
public class PackageManager : IPackageManager
{
public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(IHttpClient client,
INetworkManager networkManager,
ISecurityManager securityManager,
ResourcePool resourcePool,
IJsonSerializer serializer,
CancellationToken cancellationToken)
{
var data = new Dictionary<string, string> { { "key", securityManager.SupporterKey }, { "mac", networkManager.GetMacAddress() } };
private readonly ISecurityManager _securityManager;
private readonly INetworkManager _networkManager;
private readonly IHttpClient _httpClient;
private readonly IApplicationPaths _appPaths;
private readonly IJsonSerializer _jsonSerializer;
private readonly ILogger _logger;
using (var json = await client.Post(Constants.Constants.MBAdminUrl + "service/package/retrieveall", data, resourcePool.Mb, cancellationToken).ConfigureAwait(false))
/// <summary>
/// Initializes a new instance of the <see cref="PackageManager" /> class.
/// </summary>
/// <param name="securityManager">The security manager.</param>
/// <param name="networkManager">The network manager.</param>
/// <param name="httpClient">The HTTP client.</param>
/// <param name="applicationPaths">The application paths.</param>
/// <param name="jsonSerializer">The json serializer.</param>
/// <param name="logger">The logger.</param>
public PackageManager(ISecurityManager securityManager, INetworkManager networkManager, IHttpClient httpClient, IApplicationPaths applicationPaths, IJsonSerializer jsonSerializer, ILogger logger)
{
_securityManager = securityManager;
_networkManager = networkManager;
_httpClient = httpClient;
_appPaths = applicationPaths;
_jsonSerializer = jsonSerializer;
_logger = logger;
}
public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken)
{
var data = new Dictionary<string, string> { { "key", _securityManager.SupporterKey }, { "mac", _networkManager.GetMacAddress() } };
using (var json = await _httpClient.Post(Constants.Constants.MBAdminUrl + "service/package/retrieveall", data, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
var packages = serializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
foreach (var package in packages)
{
package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
@@ -43,15 +63,15 @@ namespace MediaBrowser.Common.Implementations.Updates
}
public async Task InstallPackage(IHttpClient client, ILogger logger, ResourcePool resourcePool, IProgress<double> progress, IApplicationPaths appPaths, PackageVersionInfo package, CancellationToken cancellationToken)
public async Task InstallPackage(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
{
// Target based on if it is an archive or single assembly
// zip archives are assumed to contain directory structures relative to our ProgramDataPath
var isArchive = string.Equals(Path.GetExtension(package.targetFilename), ".zip", StringComparison.OrdinalIgnoreCase);
var target = Path.Combine(isArchive ? appPaths.TempUpdatePath : appPaths.PluginsPath, package.targetFilename);
var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
// Download to temporary file so that, if interrupted, it won't destroy the existing installation
var tempFile = await client.GetTempFile(package.sourceUrl, resourcePool.Mb, cancellationToken, progress).ConfigureAwait(false);
var tempFile = await _httpClient.GetTempFile(package.sourceUrl, cancellationToken, progress).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
@@ -79,7 +99,7 @@ namespace MediaBrowser.Common.Implementations.Updates
}
catch (IOException e)
{
logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
_logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
throw;
}