aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Kernel
diff options
context:
space:
mode:
authorLukePulverenti <luke.pulverenti@gmail.com>2013-02-20 20:33:05 -0500
committerLukePulverenti <luke.pulverenti@gmail.com>2013-02-20 20:33:05 -0500
commit767cdc1f6f6a63ce997fc9476911e2c361f9d402 (patch)
tree49add55976f895441167c66cfa95e5c7688d18ce /MediaBrowser.Common/Kernel
parent845554722efaed872948a9e0f7202e3ef52f1b6e (diff)
Pushing missing changes
Diffstat (limited to 'MediaBrowser.Common/Kernel')
-rw-r--r--MediaBrowser.Common/Kernel/BaseApplicationPaths.cs458
-rw-r--r--MediaBrowser.Common/Kernel/BaseKernel.cs1116
-rw-r--r--MediaBrowser.Common/Kernel/BaseManager.cs57
-rw-r--r--MediaBrowser.Common/Kernel/BasePeriodicWebSocketListener.cs223
-rw-r--r--MediaBrowser.Common/Kernel/BaseWebSocketListener.cs98
-rw-r--r--MediaBrowser.Common/Kernel/IKernel.cs182
-rw-r--r--MediaBrowser.Common/Kernel/KernelContext.cs27
-rw-r--r--MediaBrowser.Common/Kernel/RegisterServer.bat28
-rw-r--r--MediaBrowser.Common/Kernel/TcpManager.cs485
9 files changed, 2166 insertions, 508 deletions
diff --git a/MediaBrowser.Common/Kernel/BaseApplicationPaths.cs b/MediaBrowser.Common/Kernel/BaseApplicationPaths.cs
index fefbd354a1..936c484c8a 100644
--- a/MediaBrowser.Common/Kernel/BaseApplicationPaths.cs
+++ b/MediaBrowser.Common/Kernel/BaseApplicationPaths.cs
@@ -1,154 +1,304 @@
-using System.Configuration;
-using System.IO;
-using System.Reflection;
-
-namespace MediaBrowser.Common.Kernel
-{
- /// <summary>
- /// Provides a base class to hold common application paths used by both the Ui and Server.
- /// This can be subclassed to add application-specific paths.
- /// </summary>
- public abstract class BaseApplicationPaths
- {
- private string _programDataPath;
- /// <summary>
- /// Gets the path to the program data folder
- /// </summary>
- public string ProgramDataPath
- {
- get
- {
- if (_programDataPath == null)
- {
- _programDataPath = GetProgramDataPath();
- }
-
- return _programDataPath;
- }
- }
-
- private string _pluginsPath;
- /// <summary>
- /// Gets the path to the plugin directory
- /// </summary>
- public string PluginsPath
- {
- get
- {
- if (_pluginsPath == null)
- {
- _pluginsPath = Path.Combine(ProgramDataPath, "plugins");
- if (!Directory.Exists(_pluginsPath))
- {
- Directory.CreateDirectory(_pluginsPath);
- }
- }
-
- return _pluginsPath;
- }
- }
-
- private string _pluginConfigurationsPath;
- /// <summary>
- /// Gets the path to the plugin configurations directory
- /// </summary>
- public string PluginConfigurationsPath
- {
- get
- {
- if (_pluginConfigurationsPath == null)
- {
- _pluginConfigurationsPath = Path.Combine(PluginsPath, "configurations");
- if (!Directory.Exists(_pluginConfigurationsPath))
- {
- Directory.CreateDirectory(_pluginConfigurationsPath);
- }
- }
-
- return _pluginConfigurationsPath;
- }
- }
-
- private string _logDirectoryPath;
- /// <summary>
- /// Gets the path to the log directory
- /// </summary>
- public string LogDirectoryPath
- {
- get
- {
- if (_logDirectoryPath == null)
- {
- _logDirectoryPath = Path.Combine(ProgramDataPath, "logs");
- if (!Directory.Exists(_logDirectoryPath))
- {
- Directory.CreateDirectory(_logDirectoryPath);
- }
- }
- return _logDirectoryPath;
- }
- }
-
- private string _configurationDirectoryPath;
- /// <summary>
- /// Gets the path to the application configuration root directory
- /// </summary>
- public string ConfigurationDirectoryPath
- {
- get
- {
- if (_configurationDirectoryPath == null)
- {
- _configurationDirectoryPath = Path.Combine(ProgramDataPath, "config");
- if (!Directory.Exists(_configurationDirectoryPath))
- {
- Directory.CreateDirectory(_configurationDirectoryPath);
- }
- }
- return _configurationDirectoryPath;
- }
- }
-
- private string _systemConfigurationFilePath;
- /// <summary>
- /// Gets the path to the system configuration file
- /// </summary>
- public string SystemConfigurationFilePath
- {
- get
- {
- if (_systemConfigurationFilePath == null)
- {
- _systemConfigurationFilePath = Path.Combine(ConfigurationDirectoryPath, "system.xml");
- }
- return _systemConfigurationFilePath;
- }
- }
-
- /// <summary>
- /// Gets the path to the application's ProgramDataFolder
- /// </summary>
- private static string GetProgramDataPath()
- {
- string programDataPath = ConfigurationManager.AppSettings["ProgramDataPath"];
-
- // If it's a relative path, e.g. "..\"
- if (!Path.IsPathRooted(programDataPath))
- {
- string path = Assembly.GetExecutingAssembly().Location;
- path = Path.GetDirectoryName(path);
-
- programDataPath = Path.Combine(path, programDataPath);
-
- programDataPath = Path.GetFullPath(programDataPath);
- }
-
- if (!Directory.Exists(programDataPath))
- {
- Directory.CreateDirectory(programDataPath);
- }
-
- return programDataPath;
- }
- }
-}
+using System;
+using System.Configuration;
+using System.IO;
+using System.Reflection;
+
+namespace MediaBrowser.Common.Kernel
+{
+ /// <summary>
+ /// Provides a base class to hold common application paths used by both the Ui and Server.
+ /// This can be subclassed to add application-specific paths.
+ /// </summary>
+ public abstract class BaseApplicationPaths
+ {
+ /// <summary>
+ /// The _program data path
+ /// </summary>
+ private string _programDataPath;
+ /// <summary>
+ /// Gets the path to the program data folder
+ /// </summary>
+ /// <value>The program data path.</value>
+ public string ProgramDataPath
+ {
+ get
+ {
+ return _programDataPath ?? (_programDataPath = GetProgramDataPath());
+ }
+ }
+
+ /// <summary>
+ /// The _data directory
+ /// </summary>
+ private string _dataDirectory;
+ /// <summary>
+ /// Gets the folder path to the data directory
+ /// </summary>
+ /// <value>The data directory.</value>
+ public string DataPath
+ {
+ get
+ {
+ if (_dataDirectory == null)
+ {
+ _dataDirectory = Path.Combine(ProgramDataPath, "data");
+
+ if (!Directory.Exists(_dataDirectory))
+ {
+ Directory.CreateDirectory(_dataDirectory);
+ }
+ }
+
+ return _dataDirectory;
+ }
+ }
+
+ /// <summary>
+ /// The _image cache path
+ /// </summary>
+ private string _imageCachePath;
+ /// <summary>
+ /// Gets the image cache path.
+ /// </summary>
+ /// <value>The image cache path.</value>
+ public string ImageCachePath
+ {
+ get
+ {
+ if (_imageCachePath == null)
+ {
+ _imageCachePath = Path.Combine(CachePath, "images");
+
+ if (!Directory.Exists(_imageCachePath))
+ {
+ Directory.CreateDirectory(_imageCachePath);
+ }
+ }
+
+ return _imageCachePath;
+ }
+ }
+
+ /// <summary>
+ /// The _plugins path
+ /// </summary>
+ private string _pluginsPath;
+ /// <summary>
+ /// Gets the path to the plugin directory
+ /// </summary>
+ /// <value>The plugins path.</value>
+ public string PluginsPath
+ {
+ get
+ {
+ if (_pluginsPath == null)
+ {
+ _pluginsPath = Path.Combine(ProgramDataPath, "plugins");
+ if (!Directory.Exists(_pluginsPath))
+ {
+ Directory.CreateDirectory(_pluginsPath);
+ }
+ }
+
+ return _pluginsPath;
+ }
+ }
+
+ /// <summary>
+ /// The _plugin configurations path
+ /// </summary>
+ private string _pluginConfigurationsPath;
+ /// <summary>
+ /// Gets the path to the plugin configurations directory
+ /// </summary>
+ /// <value>The plugin configurations path.</value>
+ public string PluginConfigurationsPath
+ {
+ get
+ {
+ if (_pluginConfigurationsPath == null)
+ {
+ _pluginConfigurationsPath = Path.Combine(PluginsPath, "configurations");
+ if (!Directory.Exists(_pluginConfigurationsPath))
+ {
+ Directory.CreateDirectory(_pluginConfigurationsPath);
+ }
+ }
+
+ return _pluginConfigurationsPath;
+ }
+ }
+
+ private string _tempUpdatePath;
+ /// <summary>
+ /// Gets the path to where temporary update files will be stored
+ /// </summary>
+ /// <value>The plugin configurations path.</value>
+ public string TempUpdatePath
+ {
+ get
+ {
+ if (_tempUpdatePath == null)
+ {
+ _tempUpdatePath = Path.Combine(ProgramDataPath, "Updates");
+ if (!Directory.Exists(_tempUpdatePath))
+ {
+ Directory.CreateDirectory(_tempUpdatePath);
+ }
+ }
+
+ return _tempUpdatePath;
+ }
+ }
+
+ /// <summary>
+ /// The _log directory path
+ /// </summary>
+ private string _logDirectoryPath;
+ /// <summary>
+ /// Gets the path to the log directory
+ /// </summary>
+ /// <value>The log directory path.</value>
+ public string LogDirectoryPath
+ {
+ get
+ {
+ if (_logDirectoryPath == null)
+ {
+ _logDirectoryPath = Path.Combine(ProgramDataPath, "logs");
+ if (!Directory.Exists(_logDirectoryPath))
+ {
+ Directory.CreateDirectory(_logDirectoryPath);
+ }
+ }
+ return _logDirectoryPath;
+ }
+ }
+
+ /// <summary>
+ /// The _configuration directory path
+ /// </summary>
+ private string _configurationDirectoryPath;
+ /// <summary>
+ /// Gets the path to the application configuration root directory
+ /// </summary>
+ /// <value>The configuration directory path.</value>
+ public string ConfigurationDirectoryPath
+ {
+ get
+ {
+ if (_configurationDirectoryPath == null)
+ {
+ _configurationDirectoryPath = Path.Combine(ProgramDataPath, "config");
+ if (!Directory.Exists(_configurationDirectoryPath))
+ {
+ Directory.CreateDirectory(_configurationDirectoryPath);
+ }
+ }
+ return _configurationDirectoryPath;
+ }
+ }
+
+ /// <summary>
+ /// The _system configuration file path
+ /// </summary>
+ private string _systemConfigurationFilePath;
+ /// <summary>
+ /// Gets the path to the system configuration file
+ /// </summary>
+ /// <value>The system configuration file path.</value>
+ public string SystemConfigurationFilePath
+ {
+ get
+ {
+ return _systemConfigurationFilePath ?? (_systemConfigurationFilePath = Path.Combine(ConfigurationDirectoryPath, "system.xml"));
+ }
+ }
+
+ /// <summary>
+ /// The _cache directory
+ /// </summary>
+ private string _cachePath;
+ /// <summary>
+ /// Gets the folder path to the cache directory
+ /// </summary>
+ /// <value>The cache directory.</value>
+ public string CachePath
+ {
+ get
+ {
+ if (_cachePath == null)
+ {
+ _cachePath = Path.Combine(ProgramDataPath, "cache");
+
+ if (!Directory.Exists(_cachePath))
+ {
+ Directory.CreateDirectory(_cachePath);
+ }
+ }
+
+ return _cachePath;
+ }
+ }
+
+ /// <summary>
+ /// The _temp directory
+ /// </summary>
+ private string _tempDirectory;
+ /// <summary>
+ /// Gets the folder path to the temp directory within the cache folder
+ /// </summary>
+ /// <value>The temp directory.</value>
+ public string TempDirectory
+ {
+ get
+ {
+ if (_tempDirectory == null)
+ {
+ _tempDirectory = Path.Combine(CachePath, "temp");
+
+ if (!Directory.Exists(_tempDirectory))
+ {
+ Directory.CreateDirectory(_tempDirectory);
+ }
+ }
+
+ return _tempDirectory;
+ }
+ }
+
+ /// <summary>
+ /// Gets the path to the application's ProgramDataFolder
+ /// </summary>
+ /// <returns>System.String.</returns>
+ public static string GetProgramDataPath()
+ {
+#if DEBUG
+ string programDataPath = ConfigurationManager.AppSettings["DebugProgramDataPath"];
+
+#else
+ string programDataPath = Path.Combine(ConfigurationManager.AppSettings["ReleaseProgramDataPath"], ConfigurationManager.AppSettings["ProgramDataFolderName"]);
+#endif
+
+ programDataPath = programDataPath.Replace("%CommonApplicationData%", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
+
+ // If it's a relative path, e.g. "..\"
+ if (!Path.IsPathRooted(programDataPath))
+ {
+ var path = Assembly.GetExecutingAssembly().Location;
+ path = Path.GetDirectoryName(path);
+
+ programDataPath = Path.Combine(path, programDataPath);
+
+ programDataPath = Path.GetFullPath(programDataPath);
+ }
+
+ if (!Directory.Exists(programDataPath))
+ {
+ Directory.CreateDirectory(programDataPath);
+ }
+
+ return programDataPath;
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Kernel/BaseKernel.cs b/MediaBrowser.Common/Kernel/BaseKernel.cs
index a6081a6881..a4cd81665c 100644
--- a/MediaBrowser.Common/Kernel/BaseKernel.cs
+++ b/MediaBrowser.Common/Kernel/BaseKernel.cs
@@ -1,345 +1,771 @@
-using MediaBrowser.Common.Events;
-using MediaBrowser.Common.Logging;
-using MediaBrowser.Common.Mef;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Common.Net.Handlers;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Common.Serialization;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Progress;
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Common.Kernel
-{
- /// <summary>
- /// Represents a shared base kernel for both the Ui and server apps
- /// </summary>
- public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
- where TConfigurationType : BaseApplicationConfiguration, new()
- where TApplicationPathsType : BaseApplicationPaths, new()
- {
- #region ReloadBeginning Event
- /// <summary>
- /// Fires whenever the kernel begins reloading
- /// </summary>
- public event EventHandler<GenericEventArgs<IProgress<TaskProgress>>> ReloadBeginning;
- private void OnReloadBeginning(IProgress<TaskProgress> progress)
- {
- if (ReloadBeginning != null)
- {
- ReloadBeginning(this, new GenericEventArgs<IProgress<TaskProgress>> { Argument = progress });
- }
- }
- #endregion
-
- #region ReloadCompleted Event
- /// <summary>
- /// Fires whenever the kernel completes reloading
- /// </summary>
- public event EventHandler<GenericEventArgs<IProgress<TaskProgress>>> ReloadCompleted;
- private void OnReloadCompleted(IProgress<TaskProgress> progress)
- {
- if (ReloadCompleted != null)
- {
- ReloadCompleted(this, new GenericEventArgs<IProgress<TaskProgress>> { Argument = progress });
- }
- }
- #endregion
-
- /// <summary>
- /// Gets the current configuration
- /// </summary>
- public TConfigurationType Configuration { get; private set; }
-
- public TApplicationPathsType ApplicationPaths { get; private set; }
-
- /// <summary>
- /// Gets the list of currently loaded plugins
- /// </summary>
- [ImportMany(typeof(BasePlugin))]
- public IEnumerable<BasePlugin> Plugins { get; private set; }
-
- /// <summary>
- /// Gets the list of currently registered http handlers
- /// </summary>
- [ImportMany(typeof(BaseHandler))]
- 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>
- /// 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.
- /// </summary>
- public HttpServer HttpServer { get; private set; }
-
- /// <summary>
- /// This subscribes to HttpListener requests and finds the appropate BaseHandler to process it
- /// </summary>
- private IDisposable HttpListener { get; set; }
-
- /// <summary>
- /// Gets the MEF CompositionContainer
- /// </summary>
- private CompositionContainer CompositionContainer { get; set; }
-
- protected virtual string HttpServerUrlPrefix
- {
- get
- {
- return "http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/";
- }
- }
-
- /// <summary>
- /// Gets the kernel context. Subclasses will have to override.
- /// </summary>
- public abstract KernelContext KernelContext { get; }
-
- /// <summary>
- /// Initializes the Kernel
- /// </summary>
- public async Task Init(IProgress<TaskProgress> progress)
- {
- Logger.Kernel = this;
-
- // Performs initializations that only occur once
- InitializeInternal(progress);
-
- // Performs initializations that can be reloaded at anytime
- await Reload(progress).ConfigureAwait(false);
- }
-
- /// <summary>
- /// Performs initializations that only occur once
- /// </summary>
- protected virtual void InitializeInternal(IProgress<TaskProgress> progress)
- {
- ApplicationPaths = new TApplicationPathsType();
-
- ReportProgress(progress, "Loading Configuration");
- ReloadConfiguration();
-
- ReportProgress(progress, "Loading Http Server");
- ReloadHttpServer();
- }
-
- /// <summary>
- /// Performs initializations that can be reloaded at anytime
- /// </summary>
- public async Task Reload(IProgress<TaskProgress> progress)
- {
- OnReloadBeginning(progress);
-
- await ReloadInternal(progress).ConfigureAwait(false);
-
- OnReloadCompleted(progress);
-
- ReportProgress(progress, "Kernel.Reload Complete");
- }
-
- /// <summary>
- /// Performs initializations that can be reloaded at anytime
- /// </summary>
- protected virtual async Task ReloadInternal(IProgress<TaskProgress> progress)
- {
- await Task.Run(() =>
- {
- ReportProgress(progress, "Loading Plugins");
- ReloadComposableParts();
-
- }).ConfigureAwait(false);
- }
-
- /// <summary>
- /// Uses MEF to locate plugins
- /// Subclasses can use this to locate types within plugins
- /// </summary>
- private void ReloadComposableParts()
- {
- DisposeComposableParts();
-
- CompositionContainer = GetCompositionContainer(includeCurrentAssembly: true);
-
- CompositionContainer.ComposeParts(this);
-
- OnComposablePartsLoaded();
-
- CompositionContainer.Catalog.Dispose();
- }
-
- /// <summary>
- /// Constructs an MEF CompositionContainer based on the current running assembly and all plugin assemblies
- /// </summary>
- public CompositionContainer GetCompositionContainer(bool includeCurrentAssembly = false)
- {
- // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
- // This will prevent the .dll file from getting locked, and allow us to replace it when needed
- IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly).Select(f => Assembly.Load(File.ReadAllBytes((f))));
-
- var catalogs = new List<ComposablePartCatalog>();
-
- catalogs.AddRange(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
-
- // Include composable parts in the Common assembly
- catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
-
- if (includeCurrentAssembly)
- {
- // Include composable parts in the subclass assembly
- catalogs.Add(new AssemblyCatalog(GetType().Assembly));
- }
-
- return MefUtils.GetSafeCompositionContainer(catalogs);
- }
-
- /// <summary>
- /// Fires after MEF finishes finding composable parts within plugin assemblies
- /// </summary>
- protected virtual void OnComposablePartsLoaded()
- {
- foreach (var logger in Loggers)
- {
- logger.Initialize(this);
- }
-
- // Start-up each plugin
- foreach (var plugin in Plugins)
- {
- plugin.Initialize(this);
- }
- }
-
- /// <summary>
- /// Reloads application configuration from the config file
- /// </summary>
- private void ReloadConfiguration()
- {
- //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
-
- // Deserialize config
- // 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();
- XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
- }
- }
-
- /// <summary>
- /// Restarts the Http Server, or starts it if not currently running
- /// </summary>
- private void ReloadHttpServer()
- {
- DisposeHttpServer();
-
- HttpServer = new HttpServer(HttpServerUrlPrefix);
-
- HttpListener = HttpServer.Subscribe(ctx =>
- {
- BaseHandler handler = HttpHandlers.FirstOrDefault(h => h.HandlesRequest(ctx.Request));
-
- // Find the appropiate http handler
- if (handler != null)
- {
- // Need to create a new instance because handlers are currently stateful
- handler = Activator.CreateInstance(handler.GetType()) as BaseHandler;
-
- // No need to await this, despite the compiler warning
- handler.ProcessRequest(ctx);
- }
- });
- }
-
- /// <summary>
- /// Disposes all resources currently in use.
- /// </summary>
- public virtual void Dispose()
- {
- Logger.LogInfo("Beginning Kernel.Dispose");
-
- DisposeHttpServer();
-
- DisposeComposableParts();
- }
-
- /// <summary>
- /// Disposes all objects gathered through MEF composable parts
- /// </summary>
- protected virtual void DisposeComposableParts()
- {
- if (CompositionContainer != null)
- {
- CompositionContainer.Dispose();
- }
- }
-
- /// <summary>
- /// Disposes the current HttpServer
- /// </summary>
- private void DisposeHttpServer()
- {
- if (HttpServer != null)
- {
- Logger.LogInfo("Disposing Http Server");
-
- HttpServer.Dispose();
- }
-
- if (HttpListener != null)
- {
- HttpListener.Dispose();
- }
- }
-
- /// <summary>
- /// Gets the current application version
- /// </summary>
- public Version ApplicationVersion
- {
- get
- {
- return GetType().Assembly.GetName().Version;
- }
- }
-
- protected void ReportProgress(IProgress<TaskProgress> progress, string message)
- {
- progress.Report(new TaskProgress { Description = message });
-
- Logger.LogInfo(message);
- }
-
- BaseApplicationPaths IKernel.ApplicationPaths
- {
- get { return ApplicationPaths; }
- }
- }
-
- public interface IKernel
- {
- BaseApplicationPaths ApplicationPaths { get; }
- KernelContext KernelContext { get; }
-
- Task Init(IProgress<TaskProgress> progress);
- Task Reload(IProgress<TaskProgress> progress);
- IEnumerable<BaseLogger> Loggers { get; }
- void Dispose();
- }
-}
+using MediaBrowser.Common.Events;
+using MediaBrowser.Common.IO;
+using MediaBrowser.Common.Localization;
+using MediaBrowser.Common.Mef;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Common.Net.Handlers;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Common.ScheduledTasks;
+using MediaBrowser.Common.Serialization;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Logging;
+using MediaBrowser.Model.System;
+using NLog;
+using NLog.Config;
+using NLog.Targets;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.Composition;
+using System.ComponentModel.Composition.Hosting;
+using System.ComponentModel.Composition.Primitives;
+using System.Deployment.Application;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Common.Kernel
+{
+ /// <summary>
+ /// Represents a shared base kernel for both the Ui and server apps
+ /// </summary>
+ /// <typeparam name="TConfigurationType">The type of the T configuration type.</typeparam>
+ /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
+ public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
+ where TConfigurationType : BaseApplicationConfiguration, new()
+ where TApplicationPathsType : BaseApplicationPaths, new()
+ {
+ /// <summary>
+ /// Occurs when [has pending restart changed].
+ /// </summary>
+ public event EventHandler HasPendingRestartChanged;
+
+ /// <summary>
+ /// Notifiies the containing application that a restart has been requested
+ /// </summary>
+ public event EventHandler ApplicationRestartRequested;
+
+ #region ConfigurationUpdated Event
+ /// <summary>
+ /// Occurs when [configuration updated].
+ /// </summary>
+ public event EventHandler<EventArgs> ConfigurationUpdated;
+
+ /// <summary>
+ /// Called when [configuration updated].
+ /// </summary>
+ internal void OnConfigurationUpdated()
+ {
+ EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty);
+
+ // Notify connected clients
+ TcpManager.SendWebSocketMessage("ConfigurationUpdated", Configuration);
+ }
+ #endregion
+
+ #region LoggerLoaded Event
+ /// <summary>
+ /// Fires whenever the logger is loaded
+ /// </summary>
+ public event EventHandler LoggerLoaded;
+ /// <summary>
+ /// Called when [logger loaded].
+ /// </summary>
+ private void OnLoggerLoaded()
+ {
+ EventHelper.QueueEventIfNotNull(LoggerLoaded, this, EventArgs.Empty);
+ }
+ #endregion
+
+ #region ReloadBeginning Event
+ /// <summary>
+ /// Fires whenever the kernel begins reloading
+ /// </summary>
+ public event EventHandler<EventArgs> ReloadBeginning;
+ /// <summary>
+ /// Called when [reload beginning].
+ /// </summary>
+ private void OnReloadBeginning()
+ {
+ EventHelper.QueueEventIfNotNull(ReloadBeginning, this, EventArgs.Empty);
+ }
+ #endregion
+
+ #region ReloadCompleted Event
+ /// <summary>
+ /// Fires whenever the kernel completes reloading
+ /// </summary>
+ public event EventHandler<EventArgs> ReloadCompleted;
+ /// <summary>
+ /// Called when [reload completed].
+ /// </summary>
+ private void OnReloadCompleted()
+ {
+ EventHelper.QueueEventIfNotNull(ReloadCompleted, this, EventArgs.Empty);
+ }
+ #endregion
+
+ #region ApplicationUpdated Event
+ /// <summary>
+ /// Occurs when [application updated].
+ /// </summary>
+ public event EventHandler<GenericEventArgs<Version>> ApplicationUpdated;
+ /// <summary>
+ /// Called when [application updated].
+ /// </summary>
+ /// <param name="newVersion">The new version.</param>
+ public void OnApplicationUpdated(Version newVersion)
+ {
+ EventHelper.QueueEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<Version> {Argument = newVersion});
+
+ NotifyPendingRestart();
+ }
+ #endregion
+
+ /// <summary>
+ /// The _configuration loaded
+ /// </summary>
+ private bool _configurationLoaded;
+ /// <summary>
+ /// The _configuration sync lock
+ /// </summary>
+ private object _configurationSyncLock = new object();
+ /// <summary>
+ /// The _configuration
+ /// </summary>
+ private TConfigurationType _configuration;
+ /// <summary>
+ /// Gets the system configuration
+ /// </summary>
+ /// <value>The configuration.</value>
+ public TConfigurationType Configuration
+ {
+ get
+ {
+ // Lazy load
+ LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => XmlSerializer.GetXmlConfiguration<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath));
+ return _configuration;
+ }
+ protected set
+ {
+ _configuration = value;
+
+ if (value == null)
+ {
+ _configurationLoaded = false;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this instance is first run.
+ /// </summary>
+ /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
+ public bool IsFirstRun { get; private set; }
+
+ /// <summary>
+ /// The version of the application to display
+ /// </summary>
+ /// <value>The display version.</value>
+ public string DisplayVersion { get { return ApplicationVersion.ToString(); } }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
+ /// </summary>
+ /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
+ public bool HasPendingRestart { get; private set; }
+
+ /// <summary>
+ /// Gets the application paths.
+ /// </summary>
+ /// <value>The application paths.</value>
+ public TApplicationPathsType ApplicationPaths { get; private set; }
+
+ /// <summary>
+ /// The _failed assembly loads
+ /// </summary>
+ private readonly List<string> _failedPluginAssemblies = new List<string>();
+ /// <summary>
+ /// Gets the plugin assemblies that failed to load.
+ /// </summary>
+ /// <value>The failed assembly loads.</value>
+ public IEnumerable<string> FailedPluginAssemblies
+ {
+ get { return _failedPluginAssemblies; }
+ }
+
+ /// <summary>
+ /// Gets the list of currently loaded plugins
+ /// </summary>
+ /// <value>The plugins.</value>
+ [ImportMany(typeof(IPlugin))]
+ public IEnumerable<IPlugin> Plugins { get; protected set; }
+
+ /// <summary>
+ /// Gets the list of Scheduled Tasks
+ /// </summary>
+ /// <value>The scheduled tasks.</value>
+ [ImportMany(typeof(IScheduledTask))]
+ public IEnumerable<IScheduledTask> ScheduledTasks { get; private set; }
+
+ /// <summary>
+ /// Gets the web socket listeners.
+ /// </summary>
+ /// <value>The web socket listeners.</value>
+ [ImportMany(typeof(IWebSocketListener))]
+ public IEnumerable<IWebSocketListener> WebSocketListeners { get; private set; }
+
+ /// <summary>
+ /// Gets the list of Localized string files
+ /// </summary>
+ /// <value>The string files.</value>
+ [ImportMany(typeof(LocalizedStringData))]
+ public IEnumerable<LocalizedStringData> StringFiles { get; private set; }
+
+ /// <summary>
+ /// Gets the MEF CompositionContainer
+ /// </summary>
+ /// <value>The composition container.</value>
+ private CompositionContainer CompositionContainer { get; set; }
+
+ /// <summary>
+ /// The _HTTP manager
+ /// </summary>
+ /// <value>The HTTP manager.</value>
+ public HttpManager HttpManager { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the TCP manager.
+ /// </summary>
+ /// <value>The TCP manager.</value>
+ public TcpManager TcpManager { get; private set; }
+
+ /// <summary>
+ /// Gets the task manager.
+ /// </summary>
+ /// <value>The task manager.</value>
+ public TaskManager TaskManager { get; private set; }
+
+ /// <summary>
+ /// Gets the iso manager.
+ /// </summary>
+ /// <value>The iso manager.</value>
+ public IIsoManager IsoManager { get; private set; }
+
+ /// <summary>
+ /// Gets the rest services.
+ /// </summary>
+ /// <value>The rest services.</value>
+ [ImportMany(typeof(IRestfulService))]
+ public IEnumerable<IRestfulService> RestServices { get; private set; }
+
+ /// <summary>
+ /// The _protobuf serializer initialized
+ /// </summary>
+ private bool _protobufSerializerInitialized;
+ /// <summary>
+ /// The _protobuf serializer sync lock
+ /// </summary>
+ private object _protobufSerializerSyncLock = new object();
+ /// <summary>
+ /// Gets a dynamically compiled generated serializer that can serialize protocontracts without reflection
+ /// </summary>
+ private DynamicProtobufSerializer _protobufSerializer;
+ /// <summary>
+ /// Gets the protobuf serializer.
+ /// </summary>
+ /// <value>The protobuf serializer.</value>
+ public DynamicProtobufSerializer ProtobufSerializer
+ {
+ get
+ {
+ // Lazy load
+ LazyInitializer.EnsureInitialized(ref _protobufSerializer, ref _protobufSerializerInitialized, ref _protobufSerializerSyncLock, () => DynamicProtobufSerializer.Create(Assemblies));
+ return _protobufSerializer;
+ }
+ private set
+ {
+ _protobufSerializer = value;
+
+ if (value == null)
+ {
+ _protobufSerializerInitialized = false;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets the UDP server port number.
+ /// This can't be configurable because then the user would have to configure their client to discover the server.
+ /// </summary>
+ /// <value>The UDP server port number.</value>
+ public abstract int UdpServerPortNumber { get; }
+
+ /// <summary>
+ /// Gets the name of the web application that can be used for url building.
+ /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
+ /// </summary>
+ /// <value>The name of the web application.</value>
+ public string WebApplicationName
+ {
+ get { return "mediabrowser"; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP server URL prefix.
+ /// </summary>
+ /// <value>The HTTP server URL prefix.</value>
+ public virtual string HttpServerUrlPrefix
+ {
+ get
+ {
+ return "http://+:" + Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/";
+ }
+ }
+
+ /// <summary>
+ /// Gets the kernel context. Subclasses will have to override.
+ /// </summary>
+ /// <value>The kernel context.</value>
+ public abstract KernelContext KernelContext { get; }
+
+ /// <summary>
+ /// Gets the log file path.
+ /// </summary>
+ /// <value>The log file path.</value>
+ public string LogFilePath { get; private set; }
+
+ /// <summary>
+ /// Gets the logger.
+ /// </summary>
+ /// <value>The logger.</value>
+ protected ILogger Logger { get; private set; }
+
+ /// <summary>
+ /// Gets the assemblies.
+ /// </summary>
+ /// <value>The assemblies.</value>
+ public Assembly[] Assemblies { get; private set; }
+
+ /// <summary>
+ /// Initializes the Kernel
+ /// </summary>
+ /// <param name="isoManager">The iso manager.</param>
+ /// <returns>Task.</returns>
+ public async Task Init(IIsoManager isoManager)
+ {
+ IsoManager = isoManager;
+
+ Logger = Logging.LogManager.GetLogger(GetType().Name);
+
+ ApplicationPaths = new TApplicationPathsType();
+
+ IsFirstRun = !File.Exists(ApplicationPaths.SystemConfigurationFilePath);
+
+ // Performs initializations that can be reloaded at anytime
+ await Reload().ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Performs initializations that can be reloaded at anytime
+ /// </summary>
+ /// <returns>Task.</returns>
+ public async Task Reload()
+ {
+ OnReloadBeginning();
+
+ await ReloadInternal().ConfigureAwait(false);
+
+ OnReloadCompleted();
+
+ Logger.Info("Kernel.Reload Complete");
+ }
+
+ /// <summary>
+ /// Performs initializations that can be reloaded at anytime
+ /// </summary>
+ /// <returns>Task.</returns>
+ protected virtual async Task ReloadInternal()
+ {
+ // Set these to null so that they can be lazy loaded again
+ Configuration = null;
+ ProtobufSerializer = null;
+
+ ReloadLogger();
+
+ Logger.Info("Version {0} initializing", ApplicationVersion);
+
+ DisposeHttpManager();
+ HttpManager = new HttpManager(this);
+
+ await OnConfigurationLoaded().ConfigureAwait(false);
+
+ DisposeTaskManager();
+ TaskManager = new TaskManager(this);
+
+ Logger.Info("Loading Plugins");
+ await ReloadComposableParts().ConfigureAwait(false);
+
+ DisposeTcpManager();
+ TcpManager = new TcpManager(this);
+ }
+
+ /// <summary>
+ /// Called when [configuration loaded].
+ /// </summary>
+ /// <returns>Task.</returns>
+ protected virtual Task OnConfigurationLoaded()
+ {
+ return Task.FromResult<object>(null);
+ }
+
+ /// <summary>
+ /// Disposes and reloads all loggers
+ /// </summary>
+ public void ReloadLogger()
+ {
+ DisposeLogger();
+
+ LogFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, KernelContext + "-" + DateTime.Now.Ticks + ".log");
+
+ var logFile = new FileTarget();
+
+ logFile.FileName = LogFilePath;
+ logFile.Layout = "${longdate}, ${level}, ${logger}, ${message}";
+
+ AddLogTarget(logFile, "ApplicationLogFile");
+
+ Logging.Logger.LoggerInstance = Logging.LogManager.GetLogger("Global");
+
+ OnLoggerLoaded();
+ }
+
+ /// <summary>
+ /// Adds the log target.
+ /// </summary>
+ /// <param name="target">The target.</param>
+ /// <param name="name">The name.</param>
+ private void AddLogTarget(Target target, string name)
+ {
+ var config = LogManager.Configuration;
+
+ config.RemoveTarget(name);
+
+ target.Name = name;
+ config.AddTarget(name, target);
+
+ var level = Configuration.EnableDebugLevelLogging ? LogLevel.Debug : LogLevel.Info;
+
+ var rule = new LoggingRule("*", level, target);
+ config.LoggingRules.Add(rule);
+
+ LogManager.Configuration = config;
+ }
+
+ /// <summary>
+ /// Uses MEF to locate plugins
+ /// Subclasses can use this to locate types within plugins
+ /// </summary>
+ /// <returns>Task.</returns>
+ private async Task ReloadComposableParts()
+ {
+ _failedPluginAssemblies.Clear();
+
+ DisposeComposableParts();
+
+ Assemblies = GetComposablePartAssemblies().ToArray();
+
+ CompositionContainer = MefUtils.GetSafeCompositionContainer(Assemblies.Select(i => new AssemblyCatalog(i)));
+
+ CompositionContainer.ComposeExportedValue("kernel", this);
+
+ CompositionContainer.ComposeParts(this);
+
+ await OnComposablePartsLoaded().ConfigureAwait(false);
+
+ CompositionContainer.Catalog.Dispose();
+ }
+
+ /// <summary>
+ /// Gets the composable part assemblies.
+ /// </summary>
+ /// <returns>IEnumerable{Assembly}.</returns>
+ protected virtual IEnumerable<Assembly> GetComposablePartAssemblies()
+ {
+ // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
+ // This will prevent the .dll file from getting locked, and allow us to replace it when needed
+ var pluginAssemblies = Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
+ .Select(file =>
+ {
+ try
+ {
+ return Assembly.Load(File.ReadAllBytes((file)));
+ }
+ catch (Exception ex)
+ {
+ _failedPluginAssemblies.Add(file);
+ Logger.ErrorException("Error loading {0}", ex, file);
+ return null;
+ }
+
+ }).Where(a => a != null);
+
+ foreach (var pluginAssembly in pluginAssemblies)
+ {
+ yield return pluginAssembly;
+ }
+
+ // Include composable parts in the Model assembly
+ yield return typeof (SystemInfo).Assembly;
+
+ // Include composable parts in the Common assembly
+ yield return Assembly.GetExecutingAssembly();
+
+ // Include composable parts in the subclass assembly
+ yield return GetType().Assembly;
+ }
+
+ /// <summary>
+ /// Fires after MEF finishes finding composable parts within plugin assemblies
+ /// </summary>
+ /// <returns>Task.</returns>
+ protected virtual Task OnComposablePartsLoaded()
+ {
+ return Task.Run(() =>
+ {
+ foreach (var listener in WebSocketListeners)
+ {
+ listener.Initialize(this);
+ }
+
+ foreach (var task in ScheduledTasks)
+ {
+ task.Initialize(this);
+ }
+
+ // Start-up each plugin
+ Parallel.ForEach(Plugins, plugin =>
+ {
+ Logger.Info("Initializing {0} {1}", plugin.Name, plugin.Version);
+
+ try
+ {
+ plugin.Initialize(this);
+
+ Logger.Info("{0} {1} initialized.", plugin.Name, plugin.Version);
+ }
+ catch (Exception ex)
+ {
+ Logger.ErrorException("Error initializing {0}", ex, plugin.Name);
+ }
+ });
+ });
+ }
+
+ /// <summary>
+ /// Notifies that the kernel that a change has been made that requires a restart
+ /// </summary>
+ public void NotifyPendingRestart()
+ {
+ HasPendingRestart = true;
+
+ TcpManager.SendWebSocketMessage("HasPendingRestartChanged", GetSystemInfo());
+
+ EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty);
+ }
+
+ /// <summary>
+ /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool dispose)
+ {
+ if (dispose)
+ {
+ DisposeTcpManager();
+ DisposeTaskManager();
+ DisposeIsoManager();
+ DisposeHttpManager();
+
+ DisposeComposableParts();
+ }
+ }
+
+ /// <summary>
+ /// Disposes the iso manager.
+ /// </summary>
+ private void DisposeIsoManager()
+ {
+ if (IsoManager != null)
+ {
+ IsoManager.Dispose();
+ IsoManager = null;
+ }
+ }
+
+ /// <summary>
+ /// Disposes the TCP manager.
+ /// </summary>
+ private void DisposeTcpManager()
+ {
+ if (TcpManager != null)
+ {
+ TcpManager.Dispose();
+ TcpManager = null;
+ }
+ }
+
+ /// <summary>
+ /// Disposes the task manager.
+ /// </summary>
+ private void DisposeTaskManager()
+ {
+ if (TaskManager != null)
+ {
+ TaskManager.Dispose();
+ TaskManager = null;
+ }
+ }
+
+ /// <summary>
+ /// Disposes the HTTP manager.
+ /// </summary>
+ private void DisposeHttpManager()
+ {
+ if (HttpManager != null)
+ {
+ HttpManager.Dispose();
+ HttpManager = null;
+ }
+ }
+
+ /// <summary>
+ /// Disposes all objects gathered through MEF composable parts
+ /// </summary>
+ protected virtual void DisposeComposableParts()
+ {
+ if (CompositionContainer != null)
+ {
+ CompositionContainer.Dispose();
+ }
+ }
+
+ /// <summary>
+ /// Disposes all logger resources
+ /// </summary>
+ private void DisposeLogger()
+ {
+ // Dispose all current loggers
+ var listeners = Trace.Listeners.OfType<TraceListener>().ToList();
+
+ Trace.Listeners.Clear();
+
+ foreach (var listener in listeners)
+ {
+ listener.Dispose();
+ }
+
+ }
+
+ /// <summary>
+ /// Gets the current application version
+ /// </summary>
+ /// <value>The application version.</value>
+ public Version ApplicationVersion
+ {
+ get
+ {
+ return GetType().Assembly.GetName().Version;
+ }
+ }
+
+ /// <summary>
+ /// Performs the pending restart.
+ /// </summary>
+ /// <returns>Task.</returns>
+ public void PerformPendingRestart()
+ {
+ if (HasPendingRestart)
+ {
+ RestartApplication();
+ }
+ else
+ {
+ Logger.Info("PerformPendingRestart - not needed");
+ }
+ }
+
+ /// <summary>
+ /// Restarts the application.
+ /// </summary>
+ protected void RestartApplication()
+ {
+ Logger.Info("Restarting the application");
+
+ EventHelper.QueueEventIfNotNull(ApplicationRestartRequested, this, EventArgs.Empty);
+ }
+
+ /// <summary>
+ /// Gets the system status.
+ /// </summary>
+ /// <returns>SystemInfo.</returns>
+ public virtual SystemInfo GetSystemInfo()
+ {
+ return new SystemInfo
+ {
+ HasPendingRestart = HasPendingRestart,
+ Version = DisplayVersion,
+ IsNetworkDeployed = ApplicationDeployment.IsNetworkDeployed,
+ WebSocketPortNumber = TcpManager.WebSocketPortNumber,
+ SupportsNativeWebSocket = TcpManager.SupportsNativeWebSocket,
+ FailedPluginAssemblies = FailedPluginAssemblies.ToArray()
+ };
+ }
+
+ /// <summary>
+ /// The _save lock
+ /// </summary>
+ private readonly object _configurationSaveLock = new object();
+
+ /// <summary>
+ /// Saves the current configuration
+ /// </summary>
+ public void SaveConfiguration()
+ {
+ lock (_configurationSaveLock)
+ {
+ XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
+ }
+
+ OnConfigurationUpdated();
+ }
+
+ /// <summary>
+ /// Gets the application paths.
+ /// </summary>
+ /// <value>The application paths.</value>
+ BaseApplicationPaths IKernel.ApplicationPaths
+ {
+ get { return ApplicationPaths; }
+ }
+ /// <summary>
+ /// Gets the configuration.
+ /// </summary>
+ /// <value>The configuration.</value>
+ BaseApplicationConfiguration IKernel.Configuration
+ {
+ get { return Configuration; }
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Kernel/BaseManager.cs b/MediaBrowser.Common/Kernel/BaseManager.cs
new file mode 100644
index 0000000000..a9aff4d1cc
--- /dev/null
+++ b/MediaBrowser.Common/Kernel/BaseManager.cs
@@ -0,0 +1,57 @@
+using MediaBrowser.Common.Logging;
+using MediaBrowser.Model.Logging;
+using System;
+
+namespace MediaBrowser.Common.Kernel
+{
+ /// <summary>
+ /// Class BaseManager
+ /// </summary>
+ /// <typeparam name="TKernelType">The type of the T kernel type.</typeparam>
+ public abstract class BaseManager<TKernelType> : IDisposable
+ where TKernelType : IKernel
+ {
+ /// <summary>
+ /// Gets the logger.
+ /// </summary>
+ /// <value>The logger.</value>
+ protected ILogger Logger { get; private set; }
+
+ /// <summary>
+ /// The _kernel
+ /// </summary>
+ protected readonly TKernelType Kernel;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BaseManager" /> class.
+ /// </summary>
+ /// <param name="kernel">The kernel.</param>
+ protected BaseManager(TKernelType kernel)
+ {
+ Kernel = kernel;
+
+ Logger = LogManager.GetLogger(GetType().Name);
+
+ Logger.Info("Initializing");
+ }
+
+ /// <summary>
+ /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
+ /// </summary>
+ public void Dispose()
+ {
+ Logger.Info("Disposing");
+
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool dispose)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Kernel/BasePeriodicWebSocketListener.cs b/MediaBrowser.Common/Kernel/BasePeriodicWebSocketListener.cs
new file mode 100644
index 0000000000..7db1ca36bb
--- /dev/null
+++ b/MediaBrowser.Common/Kernel/BasePeriodicWebSocketListener.cs
@@ -0,0 +1,223 @@
+using MediaBrowser.Common.Logging;
+using MediaBrowser.Common.Net;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.WebSockets;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Common.Kernel
+{
+ /// <summary>
+ /// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received
+ /// </summary>
+ /// <typeparam name="TKernelType">The type of the T kernel type.</typeparam>
+ /// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam>
+ /// <typeparam name="TStateType">The type of the T state type.</typeparam>
+ public abstract class BasePeriodicWebSocketListener<TKernelType, TReturnDataType, TStateType> : BaseWebSocketListener<TKernelType>
+ where TKernelType : IKernel
+ where TStateType : class, new()
+ {
+ /// <summary>
+ /// The _active connections
+ /// </summary>
+ protected readonly List<Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim>> ActiveConnections =
+ new List<Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim>>();
+
+ /// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ protected abstract string Name { get; }
+
+ /// <summary>
+ /// Gets the data to send.
+ /// </summary>
+ /// <param name="state">The state.</param>
+ /// <returns>Task{`1}.</returns>
+ protected abstract Task<TReturnDataType> GetDataToSend(TStateType state);
+
+ /// <summary>
+ /// Processes the message internal.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>Task.</returns>
+ protected override Task ProcessMessageInternal(WebSocketMessageInfo message)
+ {
+ if (message.MessageType.Equals(Name + "Start", StringComparison.OrdinalIgnoreCase))
+ {
+ Start(message);
+ }
+
+ if (message.MessageType.Equals(Name + "Stop", StringComparison.OrdinalIgnoreCase))
+ {
+ Stop(message);
+ }
+
+ return NullTaskResult;
+ }
+
+ /// <summary>
+ /// Starts sending messages over a web socket
+ /// </summary>
+ /// <param name="message">The message.</param>
+ private void Start(WebSocketMessageInfo message)
+ {
+ var vals = message.Data.Split(',');
+
+ var dueTimeMs = long.Parse(vals[0]);
+ var periodMs = long.Parse(vals[1]);
+
+ var cancellationTokenSource = new CancellationTokenSource();
+
+ Logger.LogInfo("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
+
+ var timer = new Timer(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite);
+
+ var state = new TStateType();
+
+ var semaphore = new SemaphoreSlim(1, 1);
+
+ lock (ActiveConnections)
+ {
+ ActiveConnections.Add(new Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim>(message.Connection, cancellationTokenSource, timer, state, semaphore));
+ }
+
+ timer.Change(TimeSpan.FromMilliseconds(dueTimeMs), TimeSpan.FromMilliseconds(periodMs));
+ }
+
+ /// <summary>
+ /// Timers the callback.
+ /// </summary>
+ /// <param name="state">The state.</param>
+ private async void TimerCallback(object state)
+ {
+ var connection = (WebSocketConnection)state;
+
+ Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim> tuple;
+
+ lock (ActiveConnections)
+ {
+ tuple = ActiveConnections.FirstOrDefault(c => c.Item1 == connection);
+ }
+
+ if (tuple == null)
+ {
+ return;
+ }
+
+ if (connection.State != WebSocketState.Open || tuple.Item2.IsCancellationRequested)
+ {
+ DisposeConnection(tuple);
+ return;
+ }
+
+ try
+ {
+ await tuple.Item5.WaitAsync(tuple.Item2.Token).ConfigureAwait(false);
+
+ var data = await GetDataToSend(tuple.Item4).ConfigureAwait(false);
+
+ await connection.SendAsync(new WebSocketMessage<TReturnDataType>
+ {
+ MessageType = Name,
+ Data = data
+
+ }, tuple.Item2.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ if (tuple.Item2.IsCancellationRequested)
+ {
+ DisposeConnection(tuple);
+ }
+ }
+ catch (Exception ex)
+ {
+ Logger.LogException("Error sending web socket message {0}", ex, Name);
+ DisposeConnection(tuple);
+ }
+ finally
+ {
+ tuple.Item5.Release();
+ }
+ }
+
+ /// <summary>
+ /// Stops sending messages over a web socket
+ /// </summary>
+ /// <param name="message">The message.</param>
+ private void Stop(WebSocketMessageInfo message)
+ {
+ lock (ActiveConnections)
+ {
+ var connection = ActiveConnections.FirstOrDefault(c => c.Item1 == message.Connection);
+
+ if (connection != null)
+ {
+ DisposeConnection(connection);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Disposes the connection.
+ /// </summary>
+ /// <param name="connection">The connection.</param>
+ private void DisposeConnection(Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim> connection)
+ {
+ Logger.LogInfo("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
+
+ try
+ {
+ connection.Item3.Dispose();
+ }
+ catch (ObjectDisposedException)
+ {
+
+ }
+
+ try
+ {
+ connection.Item2.Cancel();
+ connection.Item2.Dispose();
+ }
+ catch (ObjectDisposedException)
+ {
+
+ }
+
+ try
+ {
+ connection.Item5.Dispose();
+ }
+ catch (ObjectDisposedException)
+ {
+
+ }
+
+ ActiveConnections.Remove(connection);
+ }
+
+ /// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected override void Dispose(bool dispose)
+ {
+ if (dispose)
+ {
+ lock (ActiveConnections)
+ {
+ foreach (var connection in ActiveConnections.ToList())
+ {
+ DisposeConnection(connection);
+ }
+ }
+ }
+
+ base.Dispose(dispose);
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Kernel/BaseWebSocketListener.cs b/MediaBrowser.Common/Kernel/BaseWebSocketListener.cs
new file mode 100644
index 0000000000..2870403b26
--- /dev/null
+++ b/MediaBrowser.Common/Kernel/BaseWebSocketListener.cs
@@ -0,0 +1,98 @@
+using MediaBrowser.Common.Net;
+using System;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Common.Kernel
+{
+ /// <summary>
+ /// Represents a class that is notified everytime the server receives a message over a WebSocket
+ /// </summary>
+ /// <typeparam name="TKernelType">The type of the T kernel type.</typeparam>
+ public abstract class BaseWebSocketListener<TKernelType> : IWebSocketListener
+ where TKernelType : IKernel
+ {
+ /// <summary>
+ /// The null task result
+ /// </summary>
+ protected Task NullTaskResult = Task.FromResult(true);
+
+ /// <summary>
+ /// Gets the kernel.
+ /// </summary>
+ /// <value>The kernel.</value>
+ protected TKernelType Kernel { get; private set; }
+
+ /// <summary>
+ /// Initializes the specified kernel.
+ /// </summary>
+ /// <param name="kernel">The kernel.</param>
+ public virtual void Initialize(IKernel kernel)
+ {
+ if (kernel == null)
+ {
+ throw new ArgumentNullException("kernel");
+ }
+
+ Kernel = (TKernelType)kernel;
+ }
+
+ /// <summary>
+ /// Processes the message.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>Task.</returns>
+ /// <exception cref="System.ArgumentNullException">message</exception>
+ public Task ProcessMessage(WebSocketMessageInfo message)
+ {
+ if (message == null)
+ {
+ throw new ArgumentNullException("message");
+ }
+
+ return ProcessMessageInternal(message);
+ }
+
+ /// <summary>
+ /// Processes the message internal.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>Task.</returns>
+ protected abstract Task ProcessMessageInternal(WebSocketMessageInfo message);
+
+ /// <summary>
+ /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool dispose)
+ {
+ }
+ }
+
+ /// <summary>
+ /// Interface IWebSocketListener
+ /// </summary>
+ public interface IWebSocketListener : IDisposable
+ {
+ /// <summary>
+ /// Processes the message.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>Task.</returns>
+ Task ProcessMessage(WebSocketMessageInfo message);
+
+ /// <summary>
+ /// Initializes the specified kernel.
+ /// </summary>
+ /// <param name="kernel">The kernel.</param>
+ void Initialize(IKernel kernel);
+ }
+}
diff --git a/MediaBrowser.Common/Kernel/IKernel.cs b/MediaBrowser.Common/Kernel/IKernel.cs
new file mode 100644
index 0000000000..1a68dd320a
--- /dev/null
+++ b/MediaBrowser.Common/Kernel/IKernel.cs
@@ -0,0 +1,182 @@
+using MediaBrowser.Common.IO;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Common.Net.Handlers;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Common.ScheduledTasks;
+using MediaBrowser.Common.Serialization;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.System;
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Common.Kernel
+{
+ /// <summary>
+ /// Interface IKernel
+ /// </summary>
+ public interface IKernel
+ {
+ /// <summary>
+ /// Occurs when [application restart requested].
+ /// </summary>
+ event EventHandler ApplicationRestartRequested;
+
+ /// <summary>
+ /// Gets the application paths.
+ /// </summary>
+ /// <value>The application paths.</value>
+ BaseApplicationPaths ApplicationPaths { get; }
+
+ /// <summary>
+ /// Gets the configuration.
+ /// </summary>
+ /// <value>The configuration.</value>
+ BaseApplicationConfiguration Configuration { get; }
+
+ /// <summary>
+ /// Gets the kernel context.
+ /// </summary>
+ /// <value>The kernel context.</value>
+ KernelContext KernelContext { get; }
+
+ /// <summary>
+ /// Gets the protobuf serializer.
+ /// </summary>
+ /// <value>The protobuf serializer.</value>
+ DynamicProtobufSerializer ProtobufSerializer { get; }
+
+ /// <summary>
+ /// Inits this instance.
+ /// </summary>
+ /// <returns>Task.</returns>
+ Task Init(IIsoManager isoManager);
+
+ /// <summary>
+ /// Reloads this instance.
+ /// </summary>
+ /// <returns>Task.</returns>
+ Task Reload();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance has pending kernel reload.
+ /// </summary>
+ /// <value><c>true</c> if this instance has pending kernel reload; otherwise, <c>false</c>.</value>
+ bool HasPendingRestart { get; }
+
+ /// <summary>
+ /// Disposes this instance.
+ /// </summary>
+ void Dispose();
+
+ /// <summary>
+ /// Gets the system status.
+ /// </summary>
+ /// <returns>SystemInfo.</returns>
+ SystemInfo GetSystemInfo();
+
+ /// <summary>
+ /// Gets the scheduled tasks.
+ /// </summary>
+ /// <value>The scheduled tasks.</value>
+ IEnumerable<IScheduledTask> ScheduledTasks { get; }
+
+ /// <summary>
+ /// Reloads the logger.
+ /// </summary>
+ void ReloadLogger();
+
+ /// <summary>
+ /// Called when [application updated].
+ /// </summary>
+ /// <param name="newVersion">The new version.</param>
+ void OnApplicationUpdated(Version newVersion);
+
+ /// <summary>
+ /// Gets the name of the web application.
+ /// </summary>
+ /// <value>The name of the web application.</value>
+ string WebApplicationName { get; }
+
+ /// <summary>
+ /// Gets the log file path.
+ /// </summary>
+ /// <value>The log file path.</value>
+ string LogFilePath { get; }
+
+ /// <summary>
+ /// Performs the pending restart.
+ /// </summary>
+ void PerformPendingRestart();
+
+ /// <summary>
+ /// Gets the plugins.
+ /// </summary>
+ /// <value>The plugins.</value>
+ IEnumerable<IPlugin> Plugins { get; }
+
+ /// <summary>
+ /// Gets the UDP server port number.
+ /// </summary>
+ /// <value>The UDP server port number.</value>
+ int UdpServerPortNumber { get; }
+
+ /// <summary>
+ /// Gets the HTTP server URL prefix.
+ /// </summary>
+ /// <value>The HTTP server URL prefix.</value>
+ string HttpServerUrlPrefix { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether this instance is first run.
+ /// </summary>
+ /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
+ bool IsFirstRun { get; }
+
+ /// <summary>
+ /// Gets the TCP manager.
+ /// </summary>
+ /// <value>The TCP manager.</value>
+ TcpManager TcpManager { get; }
+
+ /// <summary>
+ /// Gets the task manager.
+ /// </summary>
+ /// <value>The task manager.</value>
+ TaskManager TaskManager { get; }
+
+ /// <summary>
+ /// Gets the web socket listeners.
+ /// </summary>
+ /// <value>The web socket listeners.</value>
+ IEnumerable<IWebSocketListener> WebSocketListeners { get; }
+
+ /// <summary>
+ /// Occurs when [logger loaded].
+ /// </summary>
+ event EventHandler LoggerLoaded;
+
+ /// <summary>
+ /// Occurs when [reload completed].
+ /// </summary>
+ event EventHandler<EventArgs> ReloadCompleted;
+
+ /// <summary>
+ /// Occurs when [configuration updated].
+ /// </summary>
+ event EventHandler<EventArgs> ConfigurationUpdated;
+
+ /// <summary>
+ /// Gets the assemblies.
+ /// </summary>
+ /// <value>The assemblies.</value>
+ Assembly[] Assemblies { get; }
+
+ /// <summary>
+ /// Gets the rest services.
+ /// </summary>
+ /// <value>The rest services.</value>
+ IEnumerable<IRestfulService> RestServices { get; }
+ }
+}
diff --git a/MediaBrowser.Common/Kernel/KernelContext.cs b/MediaBrowser.Common/Kernel/KernelContext.cs
index 4d13ebb7b0..1f84c02426 100644
--- a/MediaBrowser.Common/Kernel/KernelContext.cs
+++ b/MediaBrowser.Common/Kernel/KernelContext.cs
@@ -1,9 +1,18 @@
-
-namespace MediaBrowser.Common.Kernel
-{
- public enum KernelContext
- {
- Server,
- Ui
- }
-}
+
+namespace MediaBrowser.Common.Kernel
+{
+ /// <summary>
+ /// Enum KernelContext
+ /// </summary>
+ public enum KernelContext
+ {
+ /// <summary>
+ /// The server
+ /// </summary>
+ Server,
+ /// <summary>
+ /// The UI
+ /// </summary>
+ Ui
+ }
+}
diff --git a/MediaBrowser.Common/Kernel/RegisterServer.bat b/MediaBrowser.Common/Kernel/RegisterServer.bat
new file mode 100644
index 0000000000..d762dfaf76
--- /dev/null
+++ b/MediaBrowser.Common/Kernel/RegisterServer.bat
@@ -0,0 +1,28 @@
+rem %1 = http server port
+rem %2 = http server url
+rem %3 = udp server port
+rem %4 = tcp server port (web socket)
+
+if [%1]==[] GOTO DONE
+
+netsh advfirewall firewall delete rule name="Port %1" protocol=TCP localport=%1
+netsh advfirewall firewall add rule name="Port %1" dir=in action=allow protocol=TCP localport=%1
+
+if [%2]==[] GOTO DONE
+
+netsh http del urlacl url="%2" user="NT AUTHORITY\Authenticated Users"
+netsh http add urlacl url="%2" user="NT AUTHORITY\Authenticated Users"
+
+if [%3]==[] GOTO DONE
+
+netsh advfirewall firewall delete rule name="Port %3" protocol=UDP localport=%3
+netsh advfirewall firewall add rule name="Port %3" dir=in action=allow protocol=UDP localport=%3
+
+if [%4]==[] GOTO DONE
+
+netsh advfirewall firewall delete rule name="Port %4" protocol=TCP localport=%4
+netsh advfirewall firewall add rule name="Port %4" dir=in action=allow protocol=TCP localport=%4
+
+
+:DONE
+Exit \ No newline at end of file
diff --git a/MediaBrowser.Common/Kernel/TcpManager.cs b/MediaBrowser.Common/Kernel/TcpManager.cs
new file mode 100644
index 0000000000..02b078c797
--- /dev/null
+++ b/MediaBrowser.Common/Kernel/TcpManager.cs
@@ -0,0 +1,485 @@
+using Alchemy;
+using Alchemy.Classes;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Common.Serialization;
+using MediaBrowser.Model.Configuration;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Net.WebSockets;
+using System.Reflection;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Common.Kernel
+{
+ /// <summary>
+ /// Manages the Http Server, Udp Server and WebSocket connections
+ /// </summary>
+ public class TcpManager : BaseManager<IKernel>
+ {
+ /// <summary>
+ /// This is the udp server used for server discovery by clients
+ /// </summary>
+ /// <value>The UDP server.</value>
+ private UdpServer UdpServer { get; set; }
+
+ /// <summary>
+ /// Gets or sets the UDP listener.
+ /// </summary>
+ /// <value>The UDP listener.</value>
+ private IDisposable UdpListener { get; set; }
+
+ /// <summary>
+ /// 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.
+ /// </summary>
+ /// <value>The HTTP server.</value>
+ public HttpServer HttpServer { get; private set; }
+
+ /// <summary>
+ /// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
+ /// </summary>
+ /// <value>The HTTP listener.</value>
+ private IDisposable HttpListener { get; set; }
+
+ /// <summary>
+ /// The web socket connections
+ /// </summary>
+ private readonly List<WebSocketConnection> _webSocketConnections = new List<WebSocketConnection>();
+
+ /// <summary>
+ /// Gets or sets the external web socket server.
+ /// </summary>
+ /// <value>The external web socket server.</value>
+ private WebSocketServer ExternalWebSocketServer { get; set; }
+
+ /// <summary>
+ /// The _supports native web socket
+ /// </summary>
+ private bool? _supportsNativeWebSocket;
+
+ /// <summary>
+ /// Gets a value indicating whether [supports web socket].
+ /// </summary>
+ /// <value><c>true</c> if [supports web socket]; otherwise, <c>false</c>.</value>
+ internal bool SupportsNativeWebSocket
+ {
+ get
+ {
+ if (!_supportsNativeWebSocket.HasValue)
+ {
+ try
+ {
+ new ClientWebSocket();
+
+ _supportsNativeWebSocket = true;
+ }
+ catch (PlatformNotSupportedException)
+ {
+ _supportsNativeWebSocket = false;
+ }
+ }
+
+ return _supportsNativeWebSocket.Value;
+ }
+ }
+
+ /// <summary>
+ /// Gets the web socket port number.
+ /// </summary>
+ /// <value>The web socket port number.</value>
+ public int WebSocketPortNumber
+ {
+ get { return SupportsNativeWebSocket ? Kernel.Configuration.HttpServerPortNumber : Kernel.Configuration.LegacyWebSocketPortNumber; }
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TcpManager" /> class.
+ /// </summary>
+ /// <param name="kernel">The kernel.</param>
+ public TcpManager(IKernel kernel)
+ : base(kernel)
+ {
+ if (kernel.IsFirstRun)
+ {
+ RegisterServerWithAdministratorAccess();
+ }
+
+ ReloadUdpServer();
+ ReloadHttpServer();
+
+ if (!SupportsNativeWebSocket)
+ {
+ ReloadExternalWebSocketServer();
+ }
+ }
+
+ /// <summary>
+ /// Starts the external web socket server.
+ /// </summary>
+ private void ReloadExternalWebSocketServer()
+ {
+ // Avoid windows firewall prompts in the ui
+ if (Kernel.KernelContext != KernelContext.Server)
+ {
+ return;
+ }
+
+ DisposeExternalWebSocketServer();
+
+ ExternalWebSocketServer = new WebSocketServer(Kernel.Configuration.LegacyWebSocketPortNumber, IPAddress.Any)
+ {
+ OnConnected = OnAlchemyWebSocketClientConnected,
+ TimeOut = TimeSpan.FromMinutes(60)
+ };
+
+ ExternalWebSocketServer.Start();
+
+ Logger.Info("Alchemy Web Socket Server started");
+ }
+
+ /// <summary>
+ /// Called when [alchemy web socket client connected].
+ /// </summary>
+ /// <param name="context">The context.</param>
+ private void OnAlchemyWebSocketClientConnected(UserContext context)
+ {
+ var connection = new WebSocketConnection(new AlchemyWebSocket(context), context.ClientAddress, ProcessWebSocketMessageReceived);
+
+ _webSocketConnections.Add(connection);
+ }
+
+ /// <summary>
+ /// Restarts the Http Server, or starts it if not currently running
+ /// </summary>
+ /// <param name="registerServerOnFailure">if set to <c>true</c> [register server on failure].</param>
+ public void ReloadHttpServer(bool registerServerOnFailure = true)
+ {
+ // Only reload if the port has changed, so that we don't disconnect any active users
+ if (HttpServer != null && HttpServer.UrlPrefix.Equals(Kernel.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
+ {
+ return;
+ }
+
+ DisposeHttpServer();
+
+ Logger.Info("Loading Http Server");
+
+ try
+ {
+ HttpServer = new HttpServer(Kernel.HttpServerUrlPrefix, "Media Browser", Kernel);
+ }
+ catch (HttpListenerException ex)
+ {
+ Logger.ErrorException("Error starting Http Server", ex);
+
+ if (registerServerOnFailure)
+ {
+ RegisterServerWithAdministratorAccess();
+
+ // Don't get stuck in a loop
+ ReloadHttpServer(false);
+
+ return;
+ }
+
+ throw;
+ }
+
+ HttpServer.WebSocketConnected += HttpServer_WebSocketConnected;
+ }
+
+ /// <summary>
+ /// Handles the WebSocketConnected event of the HttpServer control.
+ /// </summary>
+ /// <param name="sender">The source of the event.</param>
+ /// <param name="e">The <see cref="WebSocketConnectEventArgs" /> instance containing the event data.</param>
+ void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e)
+ {
+ var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, ProcessWebSocketMessageReceived);
+
+ _webSocketConnections.Add(connection);
+ }
+
+ /// <summary>
+ /// Processes the web socket message received.
+ /// </summary>
+ /// <param name="result">The result.</param>
+ private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
+ {
+ var tasks = Kernel.WebSocketListeners.Select(i => Task.Run(async () =>
+ {
+ try
+ {
+ await i.ProcessMessage(result).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ Logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType);
+ }
+ }));
+
+ await Task.WhenAll(tasks).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Starts or re-starts the udp server
+ /// </summary>
+ private void ReloadUdpServer()
+ {
+ // For now, there's no reason to keep reloading this over and over
+ if (UdpServer != null)
+ {
+ return;
+ }
+
+ // Avoid windows firewall prompts in the ui
+ if (Kernel.KernelContext != KernelContext.Server)
+ {
+ return;
+ }
+
+ DisposeUdpServer();
+
+ try
+ {
+ // The port number can't be in configuration because we don't want it to ever change
+ UdpServer = new UdpServer(new IPEndPoint(IPAddress.Any, Kernel.UdpServerPortNumber));
+ }
+ catch (SocketException ex)
+ {
+ Logger.ErrorException("Failed to start UDP Server", ex);
+ return;
+ }
+
+ UdpListener = UdpServer.Subscribe(async res =>
+ {
+ var expectedMessage = String.Format("who is MediaBrowser{0}?", Kernel.KernelContext);
+ var expectedMessageBytes = Encoding.UTF8.GetBytes(expectedMessage);
+
+ if (expectedMessageBytes.SequenceEqual(res.Buffer))
+ {
+ Logger.Info("Received UDP server request from " + res.RemoteEndPoint.ToString());
+
+ // Send a response back with our ip address and port
+ var response = String.Format("MediaBrowser{0}|{1}:{2}", Kernel.KernelContext, NetUtils.GetLocalIpAddress(), Kernel.UdpServerPortNumber);
+
+ await UdpServer.SendAsync(response, res.RemoteEndPoint);
+ }
+ });
+ }
+
+ /// <summary>
+ /// Sends a message to all clients currently connected via a web socket
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="messageType">Type of the message.</param>
+ /// <param name="data">The data.</param>
+ /// <returns>Task.</returns>
+ public void SendWebSocketMessage<T>(string messageType, T data)
+ {
+ SendWebSocketMessage(messageType, () => data);
+ }
+
+ /// <summary>
+ /// Sends a message to all clients currently connected via a web socket
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="messageType">Type of the message.</param>
+ /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
+ public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
+ {
+ Task.Run(async () => await SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None).ConfigureAwait(false));
+ }
+
+ /// <summary>
+ /// Sends a message to all clients currently connected via a web socket
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="messageType">Type of the message.</param>
+ /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ /// <exception cref="System.ArgumentNullException">messageType</exception>
+ public async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrEmpty(messageType))
+ {
+ throw new ArgumentNullException("messageType");
+ }
+
+ if (dataFunction == null)
+ {
+ throw new ArgumentNullException("dataFunction");
+ }
+
+ if (cancellationToken == null)
+ {
+ throw new ArgumentNullException("cancellationToken");
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var connections = _webSocketConnections.Where(s => s.State == WebSocketState.Open).ToList();
+
+ if (connections.Count > 0)
+ {
+ Logger.Info("Sending web socket message {0}", messageType);
+
+ var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
+ var bytes = JsonSerializer.SerializeToBytes(message);
+
+ var tasks = connections.Select(s => Task.Run(() =>
+ {
+ try
+ {
+ s.SendAsync(bytes, cancellationToken);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ Logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
+ }
+ }));
+
+ await Task.WhenAll(tasks).ConfigureAwait(false);
+ }
+ }
+
+ /// <summary>
+ /// Disposes the udp server
+ /// </summary>
+ private void DisposeUdpServer()
+ {
+ if (UdpServer != null)
+ {
+ UdpServer.Dispose();
+ }
+
+ if (UdpListener != null)
+ {
+ UdpListener.Dispose();
+ }
+ }
+
+ /// <summary>
+ /// Disposes the current HttpServer
+ /// </summary>
+ private void DisposeHttpServer()
+ {
+ foreach (var socket in _webSocketConnections)
+ {
+ // Dispose the connection
+ socket.Dispose();
+ }
+
+ _webSocketConnections.Clear();
+
+ if (HttpServer != null)
+ {
+ Logger.Info("Disposing Http Server");
+
+ HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
+ HttpServer.Dispose();
+ }
+
+ if (HttpListener != null)
+ {
+ HttpListener.Dispose();
+ }
+
+ DisposeExternalWebSocketServer();
+ }
+
+ /// <summary>
+ /// Registers the server with administrator access.
+ /// </summary>
+ private void RegisterServerWithAdministratorAccess()
+ {
+ // Create a temp file path to extract the bat file to
+ var tmpFile = Path.Combine(Kernel.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".bat");
+
+ // Extract the bat file
+ using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.Common.Kernel.RegisterServer.bat"))
+ {
+ using (var fileStream = File.Create(tmpFile))
+ {
+ stream.CopyTo(fileStream);
+ }
+ }
+
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = tmpFile,
+
+ Arguments = string.Format("{0} {1} {2} {3}", Kernel.Configuration.HttpServerPortNumber,
+ Kernel.HttpServerUrlPrefix,
+ Kernel.UdpServerPortNumber,
+ Kernel.Configuration.LegacyWebSocketPortNumber),
+
+ CreateNoWindow = true,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ Verb = "runas",
+ ErrorDialog = false
+ };
+
+ using (var process = Process.Start(startInfo))
+ {
+ process.WaitForExit();
+ }
+ }
+
+ /// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected override void Dispose(bool dispose)
+ {
+ if (dispose)
+ {
+ DisposeUdpServer();
+ DisposeHttpServer();
+ }
+
+ base.Dispose(dispose);
+ }
+
+ /// <summary>
+ /// Disposes the external web socket server.
+ /// </summary>
+ private void DisposeExternalWebSocketServer()
+ {
+ if (ExternalWebSocketServer != null)
+ {
+ ExternalWebSocketServer.Dispose();
+ }
+ }
+
+ /// <summary>
+ /// Called when [application configuration changed].
+ /// </summary>
+ /// <param name="oldConfig">The old config.</param>
+ /// <param name="newConfig">The new config.</param>
+ public void OnApplicationConfigurationChanged(BaseApplicationConfiguration oldConfig, BaseApplicationConfiguration newConfig)
+ {
+ if (oldConfig.HttpServerPortNumber != newConfig.HttpServerPortNumber)
+ {
+ ReloadHttpServer();
+ }
+
+ if (!SupportsNativeWebSocket && oldConfig.LegacyWebSocketPortNumber != newConfig.LegacyWebSocketPortNumber)
+ {
+ ReloadExternalWebSocketServer();
+ }
+ }
+ }
+}