BaseKernel.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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.Json;
  11. using MediaBrowser.Common.Logging;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Common.Plugins;
  14. namespace MediaBrowser.Common.Kernel
  15. {
  16. /// <summary>
  17. /// Represents a shared base kernel for both the UI and server apps
  18. /// </summary>
  19. public abstract class BaseKernel<TConfigurationType>
  20. where TConfigurationType : BaseConfiguration, new()
  21. {
  22. /// <summary>
  23. /// Gets the path to the program data folder
  24. /// </summary>
  25. public string ProgramDataPath { get; private set; }
  26. /// <summary>
  27. /// Gets the path to the plugin directory
  28. /// </summary>
  29. protected string PluginsPath
  30. {
  31. get
  32. {
  33. return Path.Combine(ProgramDataPath, "plugins");
  34. }
  35. }
  36. /// <summary>
  37. /// Gets the path to the application configuration file
  38. /// </summary>
  39. protected string ConfigurationPath
  40. {
  41. get
  42. {
  43. return Path.Combine(ProgramDataPath, "config.js");
  44. }
  45. }
  46. /// <summary>
  47. /// Gets the current configuration
  48. /// </summary>
  49. public TConfigurationType Configuration { get; private set; }
  50. /// <summary>
  51. /// Gets the list of currently loaded plugins
  52. /// </summary>
  53. [ImportMany(typeof(BasePlugin))]
  54. public IEnumerable<BasePlugin> Plugins { get; private set; }
  55. /// <summary>
  56. /// Both the UI and server will have a built-in HttpServer.
  57. /// People will inevitably want remote control apps so it's needed in the UI too.
  58. /// </summary>
  59. public HttpServer HttpServer { get; private set; }
  60. /// <summary>
  61. /// Gets the kernel context. The UI kernel will have to override this.
  62. /// </summary>
  63. protected KernelContext KernelContext { get { return KernelContext.Server; } }
  64. public BaseKernel()
  65. {
  66. ProgramDataPath = GetProgramDataPath();
  67. Logger.LoggerInstance = new FileLogger(Path.Combine(ProgramDataPath, "Logs"));
  68. }
  69. public virtual void Init()
  70. {
  71. ReloadConfiguration();
  72. ReloadHttpServer();
  73. ReloadComposableParts();
  74. }
  75. /// <summary>
  76. /// Uses MEF to locate plugins
  77. /// Subclasses can use this to locate types within plugins
  78. /// </summary>
  79. protected void ReloadComposableParts()
  80. {
  81. if (!Directory.Exists(PluginsPath))
  82. {
  83. Directory.CreateDirectory(PluginsPath);
  84. }
  85. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  86. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  87. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(PluginsPath, "*.dll", SearchOption.AllDirectories).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  88. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  89. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  90. //catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  91. var container = new CompositionContainer(catalog);
  92. container.ComposeParts(this);
  93. OnComposablePartsLoaded();
  94. catalog.Dispose();
  95. container.Dispose();
  96. }
  97. /// <summary>
  98. /// Fires after MEF finishes finding composable parts within plugin assemblies
  99. /// </summary>
  100. protected virtual void OnComposablePartsLoaded()
  101. {
  102. // This event handler will allow any plugin to reference another
  103. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  104. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  105. StartPlugins();
  106. }
  107. /// <summary>
  108. /// Initializes all plugins
  109. /// </summary>
  110. private void StartPlugins()
  111. {
  112. foreach (BasePlugin plugin in Plugins)
  113. {
  114. Assembly assembly = plugin.GetType().Assembly;
  115. AssemblyName assemblyName = assembly.GetName();
  116. plugin.Version = assemblyName.Version;
  117. plugin.Path = Path.Combine(PluginsPath, assemblyName.Name);
  118. plugin.ReloadConfiguration();
  119. if (plugin.Enabled)
  120. {
  121. if (KernelContext == KernelContext.Server)
  122. {
  123. plugin.InitInServer();
  124. }
  125. else
  126. {
  127. plugin.InitInUI();
  128. }
  129. }
  130. }
  131. }
  132. /// <summary>
  133. /// Gets the path to the application's ProgramDataFolder
  134. /// </summary>
  135. private string GetProgramDataPath()
  136. {
  137. string programDataPath = ConfigurationManager.AppSettings["ProgramDataPath"];
  138. // If it's a relative path, e.g. "..\"
  139. if (!Path.IsPathRooted(programDataPath))
  140. {
  141. string path = Assembly.GetExecutingAssembly().Location;
  142. path = Path.GetDirectoryName(path);
  143. programDataPath = Path.Combine(path, programDataPath);
  144. programDataPath = Path.GetFullPath(programDataPath);
  145. }
  146. if (!Directory.Exists(programDataPath))
  147. {
  148. Directory.CreateDirectory(programDataPath);
  149. }
  150. return programDataPath;
  151. }
  152. /// <summary>
  153. /// Reloads application configuration from the config file
  154. /// </summary>
  155. private void ReloadConfiguration()
  156. {
  157. // Deserialize config
  158. if (!File.Exists(ConfigurationPath))
  159. {
  160. Configuration = new TConfigurationType();
  161. }
  162. else
  163. {
  164. Configuration = JsonSerializer.DeserializeFromFile<TConfigurationType>(ConfigurationPath);
  165. }
  166. Logger.LoggerInstance.LogSeverity = Configuration.LogSeverity;
  167. }
  168. /// <summary>
  169. /// Saves the current application configuration to the config file
  170. /// </summary>
  171. public void SaveConfiguration()
  172. {
  173. JsonSerializer.SerializeToFile(Configuration, ConfigurationPath);
  174. }
  175. /// <summary>
  176. /// Restarts the Http Server, or starts it if not currently running
  177. /// </summary>
  178. private void ReloadHttpServer()
  179. {
  180. if (HttpServer != null)
  181. {
  182. HttpServer.Dispose();
  183. }
  184. HttpServer = new HttpServer("http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/");
  185. }
  186. /// <summary>
  187. /// This snippet will allow any plugin to reference another
  188. /// </summary>
  189. Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  190. {
  191. AssemblyName assemblyName = new AssemblyName(args.Name);
  192. // Look for the .dll recursively within the plugins directory
  193. string dll = Directory.GetFiles(PluginsPath, "*.dll", SearchOption.AllDirectories)
  194. .FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
  195. // If we found a matching assembly, load it now
  196. if (!string.IsNullOrEmpty(dll))
  197. {
  198. return Assembly.Load(File.ReadAllBytes(dll));
  199. }
  200. return null;
  201. }
  202. }
  203. }