2
0

BaseKernel.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.Composition;
  4. using System.ComponentModel.Composition.Hosting;
  5. using System.Configuration;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Common.Logging;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Common.Plugins;
  13. using MediaBrowser.Common.Serialization;
  14. using MediaBrowser.Model.Progress;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Common.Kernel
  17. {
  18. /// <summary>
  19. /// Represents a shared base kernel for both the UI and server apps
  20. /// </summary>
  21. public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable
  22. where TConfigurationType : BaseApplicationConfiguration, new()
  23. where TApplicationPathsType : BaseApplicationPaths, new()
  24. {
  25. /// <summary>
  26. /// Gets the current configuration
  27. /// </summary>
  28. public TConfigurationType Configuration { get; private set; }
  29. public TApplicationPathsType ApplicationPaths { get; private set; }
  30. /// <summary>
  31. /// Gets the list of currently loaded plugins
  32. /// </summary>
  33. [ImportMany(typeof(BasePlugin))]
  34. public IEnumerable<BasePlugin> Plugins { get; private set; }
  35. /// <summary>
  36. /// Both the UI and server will have a built-in HttpServer.
  37. /// People will inevitably want remote control apps so it's needed in the UI too.
  38. /// </summary>
  39. public HttpServer HttpServer { get; private set; }
  40. /// <summary>
  41. /// Gets the kernel context. The UI kernel will have to override this.
  42. /// </summary>
  43. protected KernelContext KernelContext { get { return KernelContext.Server; } }
  44. public BaseKernel()
  45. {
  46. ApplicationPaths = new TApplicationPathsType();
  47. }
  48. public virtual Task Init(IProgress<TaskProgress> progress)
  49. {
  50. return Task.Run(() =>
  51. {
  52. ReloadLogger();
  53. progress.Report(new TaskProgress() { Description = "Loading configuration", PercentComplete = 0 });
  54. ReloadConfiguration();
  55. progress.Report(new TaskProgress() { Description = "Starting Http server", PercentComplete = 5 });
  56. ReloadHttpServer();
  57. progress.Report(new TaskProgress() { Description = "Loading Plugins", PercentComplete = 10 });
  58. ReloadComposableParts();
  59. });
  60. }
  61. /// <summary>
  62. /// Gets or sets the path to the current log file
  63. /// </summary>
  64. public static string LogFilePath { get; set; }
  65. private void ReloadLogger()
  66. {
  67. DisposeLogger();
  68. DateTime now = DateTime.Now;
  69. LogFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, Assembly.GetExecutingAssembly().GetType().Name + "-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
  70. FileStream fs = new FileStream(LogFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
  71. Logger.LoggerInstance = new StreamLogger(fs);
  72. }
  73. /// <summary>
  74. /// Uses MEF to locate plugins
  75. /// Subclasses can use this to locate types within plugins
  76. /// </summary>
  77. protected void ReloadComposableParts()
  78. {
  79. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  80. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  81. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  82. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  83. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  84. //catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  85. var container = new CompositionContainer(catalog);
  86. container.ComposeParts(this);
  87. OnComposablePartsLoaded();
  88. catalog.Dispose();
  89. container.Dispose();
  90. }
  91. /// <summary>
  92. /// Fires after MEF finishes finding composable parts within plugin assemblies
  93. /// </summary>
  94. protected virtual void OnComposablePartsLoaded()
  95. {
  96. // This event handler will allow any plugin to reference another
  97. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  98. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  99. StartPlugins();
  100. }
  101. /// <summary>
  102. /// Initializes all plugins
  103. /// </summary>
  104. private void StartPlugins()
  105. {
  106. foreach (BasePlugin plugin in Plugins)
  107. {
  108. Assembly assembly = plugin.GetType().Assembly;
  109. AssemblyName assemblyName = assembly.GetName();
  110. plugin.Version = assemblyName.Version;
  111. plugin.Path = Path.Combine(ApplicationPaths.PluginsPath, assemblyName.Name);
  112. plugin.Context = KernelContext;
  113. plugin.ReloadConfiguration();
  114. if (plugin.Enabled)
  115. {
  116. plugin.Init();
  117. }
  118. }
  119. }
  120. /// <summary>
  121. /// Reloads application configuration from the config file
  122. /// </summary>
  123. protected virtual void ReloadConfiguration()
  124. {
  125. //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
  126. // Deserialize config
  127. if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath))
  128. {
  129. Configuration = new TConfigurationType();
  130. }
  131. else
  132. {
  133. Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
  134. }
  135. Logger.LoggerInstance.LogSeverity = Configuration.LogSeverity;
  136. }
  137. /// <summary>
  138. /// Restarts the Http Server, or starts it if not currently running
  139. /// </summary>
  140. private void ReloadHttpServer()
  141. {
  142. DisposeHttpServer();
  143. HttpServer = new HttpServer("http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/");
  144. }
  145. /// <summary>
  146. /// This snippet will allow any plugin to reference another
  147. /// </summary>
  148. Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  149. {
  150. AssemblyName assemblyName = new AssemblyName(args.Name);
  151. // Look for the .dll recursively within the plugins directory
  152. string dll = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories)
  153. .FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
  154. // If we found a matching assembly, load it now
  155. if (!string.IsNullOrEmpty(dll))
  156. {
  157. return Assembly.Load(File.ReadAllBytes(dll));
  158. }
  159. return null;
  160. }
  161. /// <summary>
  162. /// Disposes all resources currently in use.
  163. /// </summary>
  164. public virtual void Dispose()
  165. {
  166. DisposeHttpServer();
  167. DisposeLogger();
  168. }
  169. /// <summary>
  170. /// Disposes the current HttpServer
  171. /// </summary>
  172. private void DisposeHttpServer()
  173. {
  174. if (HttpServer != null)
  175. {
  176. HttpServer.Dispose();
  177. }
  178. }
  179. /// <summary>
  180. /// Disposes the current Logger instance
  181. /// </summary>
  182. private void DisposeLogger()
  183. {
  184. if (Logger.LoggerInstance != null)
  185. {
  186. Logger.LoggerInstance.Dispose();
  187. }
  188. }
  189. }
  190. }