BaseKernel.cs 7.5 KB

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