BaseKernel.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 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. ReloadLogger();
  86. ReloadConfiguration();
  87. ReloadHttpServer();
  88. ReloadComposableParts();
  89. }
  90. private void ReloadLogger()
  91. {
  92. DisposeLogger();
  93. if (!Directory.Exists(LogDirectoryPath))
  94. {
  95. Directory.CreateDirectory(LogDirectoryPath);
  96. }
  97. DateTime now = DateTime.Now;
  98. LogFilePath = Path.Combine(LogDirectoryPath, now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
  99. FileStream fs = new FileStream(LogFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
  100. Logger.LoggerInstance = new StreamLogger(fs);
  101. }
  102. /// <summary>
  103. /// Uses MEF to locate plugins
  104. /// Subclasses can use this to locate types within plugins
  105. /// </summary>
  106. protected void ReloadComposableParts()
  107. {
  108. if (!Directory.Exists(PluginsPath))
  109. {
  110. Directory.CreateDirectory(PluginsPath);
  111. }
  112. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  113. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  114. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(PluginsPath, "*.dll", SearchOption.AllDirectories).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  115. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  116. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  117. //catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  118. var container = new CompositionContainer(catalog);
  119. container.ComposeParts(this);
  120. OnComposablePartsLoaded();
  121. catalog.Dispose();
  122. container.Dispose();
  123. }
  124. /// <summary>
  125. /// Fires after MEF finishes finding composable parts within plugin assemblies
  126. /// </summary>
  127. protected virtual void OnComposablePartsLoaded()
  128. {
  129. // This event handler will allow any plugin to reference another
  130. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  131. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  132. StartPlugins();
  133. }
  134. /// <summary>
  135. /// Initializes all plugins
  136. /// </summary>
  137. private void StartPlugins()
  138. {
  139. foreach (BasePlugin plugin in Plugins)
  140. {
  141. Assembly assembly = plugin.GetType().Assembly;
  142. AssemblyName assemblyName = assembly.GetName();
  143. plugin.Version = assemblyName.Version;
  144. plugin.Path = Path.Combine(PluginsPath, assemblyName.Name);
  145. plugin.Context = KernelContext;
  146. plugin.ReloadConfiguration();
  147. if (plugin.Enabled)
  148. {
  149. plugin.Init();
  150. }
  151. }
  152. }
  153. /// <summary>
  154. /// Gets the path to the application's ProgramDataFolder
  155. /// </summary>
  156. private string GetProgramDataPath()
  157. {
  158. string programDataPath = ConfigurationManager.AppSettings["ProgramDataPath"];
  159. // If it's a relative path, e.g. "..\"
  160. if (!Path.IsPathRooted(programDataPath))
  161. {
  162. string path = Assembly.GetExecutingAssembly().Location;
  163. path = Path.GetDirectoryName(path);
  164. programDataPath = Path.Combine(path, programDataPath);
  165. programDataPath = Path.GetFullPath(programDataPath);
  166. }
  167. if (!Directory.Exists(programDataPath))
  168. {
  169. Directory.CreateDirectory(programDataPath);
  170. }
  171. return programDataPath;
  172. }
  173. /// <summary>
  174. /// Reloads application configuration from the config file
  175. /// </summary>
  176. private void ReloadConfiguration()
  177. {
  178. // Deserialize config
  179. if (!File.Exists(ConfigurationPath))
  180. {
  181. Configuration = new TConfigurationType();
  182. }
  183. else
  184. {
  185. Configuration = JsonSerializer.DeserializeFromFile<TConfigurationType>(ConfigurationPath);
  186. }
  187. Logger.LoggerInstance.LogSeverity = Configuration.LogSeverity;
  188. }
  189. /// <summary>
  190. /// Saves the current application configuration to the config file
  191. /// </summary>
  192. public void SaveConfiguration()
  193. {
  194. JsonSerializer.SerializeToFile(Configuration, ConfigurationPath);
  195. }
  196. /// <summary>
  197. /// Restarts the Http Server, or starts it if not currently running
  198. /// </summary>
  199. private void ReloadHttpServer()
  200. {
  201. DisposeHttpServer();
  202. HttpServer = new HttpServer("http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/");
  203. }
  204. /// <summary>
  205. /// This snippet will allow any plugin to reference another
  206. /// </summary>
  207. Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  208. {
  209. AssemblyName assemblyName = new AssemblyName(args.Name);
  210. // Look for the .dll recursively within the plugins directory
  211. string dll = Directory.GetFiles(PluginsPath, "*.dll", SearchOption.AllDirectories)
  212. .FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
  213. // If we found a matching assembly, load it now
  214. if (!string.IsNullOrEmpty(dll))
  215. {
  216. return Assembly.Load(File.ReadAllBytes(dll));
  217. }
  218. return null;
  219. }
  220. /// <summary>
  221. /// Disposes all resources currently in use.
  222. /// </summary>
  223. public void Dispose()
  224. {
  225. DisposeHttpServer();
  226. DisposeLogger();
  227. }
  228. /// <summary>
  229. /// Disposes the current HttpServer
  230. /// </summary>
  231. private void DisposeHttpServer()
  232. {
  233. if (HttpServer != null)
  234. {
  235. HttpServer.Dispose();
  236. }
  237. }
  238. /// <summary>
  239. /// Disposes the current Logger instance
  240. /// </summary>
  241. private void DisposeLogger()
  242. {
  243. if (Logger.LoggerInstance != null)
  244. {
  245. Logger.LoggerInstance.Dispose();
  246. }
  247. }
  248. }
  249. }