BaseKernel.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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.Model.Progress;
  14. using MediaBrowser.Common.Json;
  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 path to the program data folder
  25. /// </summary>
  26. public string ProgramDataPath { get; private set; }
  27. /// <summary>
  28. /// Gets the path to the plugin directory
  29. /// </summary>
  30. protected string PluginsPath
  31. {
  32. get
  33. {
  34. return Path.Combine(ProgramDataPath, "plugins");
  35. }
  36. }
  37. /// <summary>
  38. /// Gets the path to the application configuration file
  39. /// </summary>
  40. protected string ConfigurationPath
  41. {
  42. get
  43. {
  44. return Path.Combine(ProgramDataPath, "config.js");
  45. }
  46. }
  47. /// <summary>
  48. /// Gets the path to the log directory
  49. /// </summary>
  50. private string LogDirectoryPath
  51. {
  52. get
  53. {
  54. return Path.Combine(ProgramDataPath, "logs");
  55. }
  56. }
  57. /// <summary>
  58. /// Gets or sets the path to the current log file
  59. /// </summary>
  60. private string LogFilePath { get; set; }
  61. /// <summary>
  62. /// Gets the current configuration
  63. /// </summary>
  64. public TConfigurationType Configuration { get; private set; }
  65. /// <summary>
  66. /// Gets the list of currently loaded plugins
  67. /// </summary>
  68. [ImportMany(typeof(BasePlugin))]
  69. public IEnumerable<BasePlugin> Plugins { get; private set; }
  70. /// <summary>
  71. /// Both the UI and server will have a built-in HttpServer.
  72. /// People will inevitably want remote control apps so it's needed in the UI too.
  73. /// </summary>
  74. public HttpServer HttpServer { get; private set; }
  75. /// <summary>
  76. /// Gets the kernel context. The UI kernel will have to override this.
  77. /// </summary>
  78. protected KernelContext KernelContext { get { return KernelContext.Server; } }
  79. public BaseKernel()
  80. {
  81. ProgramDataPath = GetProgramDataPath();
  82. }
  83. public virtual void Init(IProgress<TaskProgress> progress)
  84. {
  85. JsonSerializer.Configure();
  86. ReloadLogger();
  87. ReloadConfiguration();
  88. ReloadHttpServer();
  89. ReloadComposableParts();
  90. }
  91. private void ReloadLogger()
  92. {
  93. DisposeLogger();
  94. if (!Directory.Exists(LogDirectoryPath))
  95. {
  96. Directory.CreateDirectory(LogDirectoryPath);
  97. }
  98. DateTime now = DateTime.Now;
  99. LogFilePath = Path.Combine(LogDirectoryPath, now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
  100. FileStream fs = new FileStream(LogFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
  101. Logger.LoggerInstance = new StreamLogger(fs);
  102. }
  103. /// <summary>
  104. /// Uses MEF to locate plugins
  105. /// Subclasses can use this to locate types within plugins
  106. /// </summary>
  107. protected void ReloadComposableParts()
  108. {
  109. if (!Directory.Exists(PluginsPath))
  110. {
  111. Directory.CreateDirectory(PluginsPath);
  112. }
  113. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  114. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  115. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(PluginsPath, "*.dll", SearchOption.AllDirectories).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  116. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  117. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  118. //catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  119. var container = new CompositionContainer(catalog);
  120. container.ComposeParts(this);
  121. OnComposablePartsLoaded();
  122. catalog.Dispose();
  123. container.Dispose();
  124. }
  125. /// <summary>
  126. /// Fires after MEF finishes finding composable parts within plugin assemblies
  127. /// </summary>
  128. protected virtual void OnComposablePartsLoaded()
  129. {
  130. // This event handler will allow any plugin to reference another
  131. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  132. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  133. StartPlugins();
  134. }
  135. /// <summary>
  136. /// Initializes all plugins
  137. /// </summary>
  138. private void StartPlugins()
  139. {
  140. foreach (BasePlugin plugin in Plugins)
  141. {
  142. Assembly assembly = plugin.GetType().Assembly;
  143. AssemblyName assemblyName = assembly.GetName();
  144. plugin.Version = assemblyName.Version;
  145. plugin.Path = Path.Combine(PluginsPath, assemblyName.Name);
  146. plugin.Context = KernelContext;
  147. plugin.ReloadConfiguration();
  148. if (plugin.Enabled)
  149. {
  150. plugin.Init();
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// Gets the path to the application's ProgramDataFolder
  156. /// </summary>
  157. private string GetProgramDataPath()
  158. {
  159. string programDataPath = ConfigurationManager.AppSettings["ProgramDataPath"];
  160. // If it's a relative path, e.g. "..\"
  161. if (!Path.IsPathRooted(programDataPath))
  162. {
  163. string path = Assembly.GetExecutingAssembly().Location;
  164. path = Path.GetDirectoryName(path);
  165. programDataPath = Path.Combine(path, programDataPath);
  166. programDataPath = Path.GetFullPath(programDataPath);
  167. }
  168. if (!Directory.Exists(programDataPath))
  169. {
  170. Directory.CreateDirectory(programDataPath);
  171. }
  172. return programDataPath;
  173. }
  174. /// <summary>
  175. /// Reloads application configuration from the config file
  176. /// </summary>
  177. private void ReloadConfiguration()
  178. {
  179. // Deserialize config
  180. if (!File.Exists(ConfigurationPath))
  181. {
  182. Configuration = new TConfigurationType();
  183. }
  184. else
  185. {
  186. Configuration = JsonSerializer.DeserializeFromFile<TConfigurationType>(ConfigurationPath);
  187. }
  188. Logger.LoggerInstance.LogSeverity = Configuration.LogSeverity;
  189. }
  190. /// <summary>
  191. /// Saves the current application configuration to the config file
  192. /// </summary>
  193. public void SaveConfiguration()
  194. {
  195. JsonSerializer.SerializeToFile(Configuration, ConfigurationPath);
  196. }
  197. /// <summary>
  198. /// Restarts the Http Server, or starts it if not currently running
  199. /// </summary>
  200. private void ReloadHttpServer()
  201. {
  202. DisposeHttpServer();
  203. HttpServer = new HttpServer("http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/");
  204. }
  205. /// <summary>
  206. /// This snippet will allow any plugin to reference another
  207. /// </summary>
  208. Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  209. {
  210. AssemblyName assemblyName = new AssemblyName(args.Name);
  211. // Look for the .dll recursively within the plugins directory
  212. string dll = Directory.GetFiles(PluginsPath, "*.dll", SearchOption.AllDirectories)
  213. .FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
  214. // If we found a matching assembly, load it now
  215. if (!string.IsNullOrEmpty(dll))
  216. {
  217. return Assembly.Load(File.ReadAllBytes(dll));
  218. }
  219. return null;
  220. }
  221. /// <summary>
  222. /// Disposes all resources currently in use.
  223. /// </summary>
  224. public void Dispose()
  225. {
  226. DisposeHttpServer();
  227. DisposeLogger();
  228. }
  229. /// <summary>
  230. /// Disposes the current HttpServer
  231. /// </summary>
  232. private void DisposeHttpServer()
  233. {
  234. if (HttpServer != null)
  235. {
  236. HttpServer.Dispose();
  237. }
  238. }
  239. /// <summary>
  240. /// Disposes the current Logger instance
  241. /// </summary>
  242. private void DisposeLogger()
  243. {
  244. if (Logger.LoggerInstance != null)
  245. {
  246. Logger.LoggerInstance.Dispose();
  247. }
  248. }
  249. }
  250. }