BaseApplicationHost.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Implementations.Logging;
  4. using MediaBrowser.Common.Implementations.NetworkManagement;
  5. using MediaBrowser.Common.Implementations.ScheduledTasks;
  6. using MediaBrowser.Common.Implementations.Security;
  7. using MediaBrowser.Common.Implementations.Serialization;
  8. using MediaBrowser.Common.Implementations.Updates;
  9. using MediaBrowser.Common.Net;
  10. using MediaBrowser.Common.Plugins;
  11. using MediaBrowser.Common.ScheduledTasks;
  12. using MediaBrowser.Common.Security;
  13. using MediaBrowser.Common.Updates;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Model.Serialization;
  16. using MediaBrowser.Model.Updates;
  17. using SimpleInjector;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Reflection;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. namespace MediaBrowser.Common.Implementations
  26. {
  27. /// <summary>
  28. /// Class BaseApplicationHost
  29. /// </summary>
  30. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  31. public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationHost
  32. where TApplicationPathsType : class, IApplicationPaths, new()
  33. {
  34. /// <summary>
  35. /// Occurs when [has pending restart changed].
  36. /// </summary>
  37. public event EventHandler HasPendingRestartChanged;
  38. /// <summary>
  39. /// Occurs when [application updated].
  40. /// </summary>
  41. public event EventHandler<GenericEventArgs<Version>> ApplicationUpdated;
  42. /// <summary>
  43. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  44. /// </summary>
  45. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  46. public bool HasPendingRestart { get; private set; }
  47. /// <summary>
  48. /// Gets or sets the logger.
  49. /// </summary>
  50. /// <value>The logger.</value>
  51. protected ILogger Logger { get; private set; }
  52. /// <summary>
  53. /// Gets or sets the plugins.
  54. /// </summary>
  55. /// <value>The plugins.</value>
  56. public IEnumerable<IPlugin> Plugins { get; protected set; }
  57. /// <summary>
  58. /// Gets or sets the log manager.
  59. /// </summary>
  60. /// <value>The log manager.</value>
  61. public ILogManager LogManager { get; protected set; }
  62. /// <summary>
  63. /// Gets the application paths.
  64. /// </summary>
  65. /// <value>The application paths.</value>
  66. protected TApplicationPathsType ApplicationPaths = new TApplicationPathsType();
  67. /// <summary>
  68. /// The container
  69. /// </summary>
  70. protected readonly Container Container = new Container();
  71. /// <summary>
  72. /// The json serializer
  73. /// </summary>
  74. public readonly IJsonSerializer JsonSerializer = new JsonSerializer();
  75. /// <summary>
  76. /// The _XML serializer
  77. /// </summary>
  78. protected readonly IXmlSerializer XmlSerializer = new XmlSerializer();
  79. /// <summary>
  80. /// Gets assemblies that failed to load
  81. /// </summary>
  82. /// <value>The failed assemblies.</value>
  83. public List<string> FailedAssemblies { get; protected set; }
  84. /// <summary>
  85. /// Gets all types within all running assemblies
  86. /// </summary>
  87. /// <value>All types.</value>
  88. public Type[] AllTypes { get; protected set; }
  89. /// <summary>
  90. /// Gets all concrete types.
  91. /// </summary>
  92. /// <value>All concrete types.</value>
  93. public Type[] AllConcreteTypes { get; protected set; }
  94. /// <summary>
  95. /// The disposable parts
  96. /// </summary>
  97. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  98. /// <summary>
  99. /// Gets a value indicating whether this instance is first run.
  100. /// </summary>
  101. /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
  102. public bool IsFirstRun { get; private set; }
  103. /// <summary>
  104. /// Gets the kernel.
  105. /// </summary>
  106. /// <value>The kernel.</value>
  107. protected ITaskManager TaskManager { get; private set; }
  108. /// <summary>
  109. /// Gets the security manager.
  110. /// </summary>
  111. /// <value>The security manager.</value>
  112. protected ISecurityManager SecurityManager { get; private set; }
  113. /// <summary>
  114. /// Gets the package manager.
  115. /// </summary>
  116. /// <value>The package manager.</value>
  117. protected IPackageManager PackageManager { get; private set; }
  118. /// <summary>
  119. /// Gets the HTTP client.
  120. /// </summary>
  121. /// <value>The HTTP client.</value>
  122. protected IHttpClient HttpClient { get; private set; }
  123. /// <summary>
  124. /// Gets the network manager.
  125. /// </summary>
  126. /// <value>The network manager.</value>
  127. protected INetworkManager NetworkManager { get; private set; }
  128. /// <summary>
  129. /// Gets the configuration manager.
  130. /// </summary>
  131. /// <value>The configuration manager.</value>
  132. protected IConfigurationManager ConfigurationManager { get; private set; }
  133. /// <summary>
  134. /// Initializes a new instance of the <see cref="BaseApplicationHost" /> class.
  135. /// </summary>
  136. protected BaseApplicationHost()
  137. {
  138. FailedAssemblies = new List<string>();
  139. LogManager = new NlogManager(ApplicationPaths.LogDirectoryPath, LogFilePrefixName);
  140. ConfigurationManager = GetConfigurationManager();
  141. }
  142. /// <summary>
  143. /// Inits this instance.
  144. /// </summary>
  145. /// <returns>Task.</returns>
  146. public virtual async Task Init()
  147. {
  148. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  149. Logger = LogManager.GetLogger("App");
  150. LogManager.ReloadLogger(ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info);
  151. DiscoverTypes();
  152. Logger.Info("Version {0} initializing", ApplicationVersion);
  153. await RegisterResources().ConfigureAwait(false);
  154. FindParts();
  155. await RunStartupTasks().ConfigureAwait(false);
  156. }
  157. /// <summary>
  158. /// Runs the startup tasks.
  159. /// </summary>
  160. /// <returns>Task.</returns>
  161. protected virtual Task RunStartupTasks()
  162. {
  163. return Task.Run(() =>
  164. {
  165. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  166. Task.Run(() => ConfigureAutoRunAtStartup());
  167. Task.Run(() => SecurityManager.LoadAllRegistrationInfo());
  168. ConfigurationManager.ConfigurationUpdated += ConfigurationManager_ConfigurationUpdated;
  169. });
  170. }
  171. /// <summary>
  172. /// Gets the composable part assemblies.
  173. /// </summary>
  174. /// <returns>IEnumerable{Assembly}.</returns>
  175. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  176. /// <summary>
  177. /// Gets the name of the log file prefix.
  178. /// </summary>
  179. /// <value>The name of the log file prefix.</value>
  180. protected abstract string LogFilePrefixName { get; }
  181. /// <summary>
  182. /// Gets the configuration manager.
  183. /// </summary>
  184. /// <returns>IConfigurationManager.</returns>
  185. protected abstract IConfigurationManager GetConfigurationManager();
  186. /// <summary>
  187. /// Finds the parts.
  188. /// </summary>
  189. protected virtual void FindParts()
  190. {
  191. Plugins = GetExports<IPlugin>();
  192. }
  193. /// <summary>
  194. /// Discovers the types.
  195. /// </summary>
  196. protected void DiscoverTypes()
  197. {
  198. FailedAssemblies.Clear();
  199. var assemblies = GetComposablePartAssemblies().ToArray();
  200. foreach (var assembly in assemblies)
  201. {
  202. Logger.Info("Loading {0}", assembly.FullName);
  203. }
  204. AllTypes = assemblies.SelectMany(GetTypes).ToArray();
  205. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  206. }
  207. /// <summary>
  208. /// Registers resources that classes will depend on
  209. /// </summary>
  210. /// <returns>Task.</returns>
  211. protected virtual Task RegisterResources()
  212. {
  213. return Task.Run(() =>
  214. {
  215. RegisterSingleInstance(ConfigurationManager);
  216. RegisterSingleInstance<IApplicationHost>(this);
  217. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  218. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger);
  219. RegisterSingleInstance(JsonSerializer);
  220. RegisterSingleInstance(XmlSerializer);
  221. RegisterSingleInstance(LogManager);
  222. RegisterSingleInstance(Logger);
  223. RegisterSingleInstance(TaskManager);
  224. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger);
  225. RegisterSingleInstance(HttpClient);
  226. NetworkManager = new NetworkManager();
  227. RegisterSingleInstance(NetworkManager);
  228. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths);
  229. RegisterSingleInstance(SecurityManager);
  230. PackageManager = new PackageManager(SecurityManager, NetworkManager, HttpClient, ApplicationPaths, JsonSerializer, Logger);
  231. RegisterSingleInstance(PackageManager);
  232. });
  233. }
  234. /// <summary>
  235. /// Gets a list of types within an assembly
  236. /// This will handle situations that would normally throw an exception - such as a type within the assembly that depends on some other non-existant reference
  237. /// </summary>
  238. /// <param name="assembly">The assembly.</param>
  239. /// <returns>IEnumerable{Type}.</returns>
  240. /// <exception cref="System.ArgumentNullException">assembly</exception>
  241. protected IEnumerable<Type> GetTypes(Assembly assembly)
  242. {
  243. if (assembly == null)
  244. {
  245. throw new ArgumentNullException("assembly");
  246. }
  247. try
  248. {
  249. return assembly.GetTypes();
  250. }
  251. catch (ReflectionTypeLoadException ex)
  252. {
  253. // If it fails we can still get a list of the Types it was able to resolve
  254. return ex.Types.Where(t => t != null);
  255. }
  256. }
  257. /// <summary>
  258. /// Creates an instance of type and resolves all constructor dependancies
  259. /// </summary>
  260. /// <param name="type">The type.</param>
  261. /// <returns>System.Object.</returns>
  262. public object CreateInstance(Type type)
  263. {
  264. try
  265. {
  266. return Container.GetInstance(type);
  267. }
  268. catch
  269. {
  270. Logger.Error("Error creating {0}", type.Name);
  271. throw;
  272. }
  273. }
  274. /// <summary>
  275. /// Registers the specified obj.
  276. /// </summary>
  277. /// <typeparam name="T"></typeparam>
  278. /// <param name="obj">The obj.</param>
  279. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  280. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  281. where T : class
  282. {
  283. Logger.Info("Registering " + obj.GetType().Name);
  284. Container.RegisterSingle(obj);
  285. if (manageLifetime)
  286. {
  287. var disposable = obj as IDisposable;
  288. if (disposable != null)
  289. {
  290. DisposableParts.Add(disposable);
  291. }
  292. }
  293. }
  294. /// <summary>
  295. /// Registers the single instance.
  296. /// </summary>
  297. /// <typeparam name="T"></typeparam>
  298. /// <param name="func">The func.</param>
  299. protected void RegisterSingleInstance<T>(Func<T> func)
  300. where T : class
  301. {
  302. Container.RegisterSingle(func);
  303. }
  304. /// <summary>
  305. /// Resolves this instance.
  306. /// </summary>
  307. /// <typeparam name="T"></typeparam>
  308. /// <returns>``0.</returns>
  309. public T Resolve<T>()
  310. {
  311. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  312. }
  313. /// <summary>
  314. /// Resolves this instance.
  315. /// </summary>
  316. /// <typeparam name="T"></typeparam>
  317. /// <returns>``0.</returns>
  318. public T TryResolve<T>()
  319. {
  320. var result = Container.GetRegistration(typeof(T), false);
  321. if (result == null)
  322. {
  323. return default(T);
  324. }
  325. return (T)result.GetInstance();
  326. }
  327. /// <summary>
  328. /// Loads the assembly.
  329. /// </summary>
  330. /// <param name="file">The file.</param>
  331. /// <returns>Assembly.</returns>
  332. protected Assembly LoadAssembly(string file)
  333. {
  334. try
  335. {
  336. return Assembly.Load(File.ReadAllBytes((file)));
  337. }
  338. catch (Exception ex)
  339. {
  340. FailedAssemblies.Add(file);
  341. Logger.ErrorException("Error loading assembly {0}", ex, file);
  342. return null;
  343. }
  344. }
  345. /// <summary>
  346. /// Gets the exports.
  347. /// </summary>
  348. /// <typeparam name="T"></typeparam>
  349. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  350. /// <returns>IEnumerable{``0}.</returns>
  351. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  352. {
  353. var currentType = typeof(T);
  354. Logger.Info("Composing instances of " + currentType.Name);
  355. var parts = AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom).Select(CreateInstance).Cast<T>().ToArray();
  356. if (manageLiftime)
  357. {
  358. lock (DisposableParts)
  359. {
  360. DisposableParts.AddRange(parts.OfType<IDisposable>());
  361. }
  362. }
  363. return parts;
  364. }
  365. /// <summary>
  366. /// Gets the current application version
  367. /// </summary>
  368. /// <value>The application version.</value>
  369. public Version ApplicationVersion
  370. {
  371. get
  372. {
  373. return GetType().Assembly.GetName().Version;
  374. }
  375. }
  376. /// <summary>
  377. /// Defines the full path to our shortcut in the start menu
  378. /// </summary>
  379. protected abstract string ProductShortcutPath { get; }
  380. /// <summary>
  381. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  382. /// </summary>
  383. /// <param name="sender">The source of the event.</param>
  384. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  385. /// <exception cref="System.NotImplementedException"></exception>
  386. void ConfigurationManager_ConfigurationUpdated(object sender, EventArgs e)
  387. {
  388. ConfigureAutoRunAtStartup();
  389. }
  390. /// <summary>
  391. /// Configures the auto run at startup.
  392. /// </summary>
  393. private void ConfigureAutoRunAtStartup()
  394. {
  395. if (ConfigurationManager.CommonConfiguration.RunAtStartup)
  396. {
  397. //Copy our shortut into the startup folder for this user
  398. File.Copy(ProductShortcutPath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup),Path.GetFileName(ProductShortcutPath) ?? "MBstartup.lnk"), true);
  399. }
  400. else
  401. {
  402. //Remove our shortcut from the startup folder for this user
  403. try
  404. {
  405. File.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), Path.GetFileName(ProductShortcutPath) ?? "MBstartup.lnk"));
  406. }
  407. catch (FileNotFoundException)
  408. {
  409. //This is okay - trying to remove it anyway
  410. }
  411. }
  412. }
  413. /// <summary>
  414. /// Removes the plugin.
  415. /// </summary>
  416. /// <param name="plugin">The plugin.</param>
  417. public void RemovePlugin(IPlugin plugin)
  418. {
  419. var list = Plugins.ToList();
  420. list.Remove(plugin);
  421. Plugins = list;
  422. }
  423. /// <summary>
  424. /// Performs the pending restart.
  425. /// </summary>
  426. /// <returns>Task.</returns>
  427. public void PerformPendingRestart()
  428. {
  429. if (HasPendingRestart)
  430. {
  431. Logger.Info("Restarting the application");
  432. Restart();
  433. }
  434. else
  435. {
  436. Logger.Info("PerformPendingRestart - not needed");
  437. }
  438. }
  439. /// <summary>
  440. /// Notifies that the kernel that a change has been made that requires a restart
  441. /// </summary>
  442. public void NotifyPendingRestart()
  443. {
  444. HasPendingRestart = true;
  445. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  446. }
  447. /// <summary>
  448. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  449. /// </summary>
  450. public void Dispose()
  451. {
  452. Dispose(true);
  453. }
  454. /// <summary>
  455. /// Releases unmanaged and - optionally - managed resources.
  456. /// </summary>
  457. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  458. protected virtual void Dispose(bool dispose)
  459. {
  460. if (dispose)
  461. {
  462. var type = GetType();
  463. Logger.Info("Disposing " + type.Name);
  464. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  465. DisposableParts.Clear();
  466. foreach (var part in parts)
  467. {
  468. Logger.Info("Disposing " + part.GetType().Name);
  469. part.Dispose();
  470. }
  471. }
  472. }
  473. /// <summary>
  474. /// Restarts this instance.
  475. /// </summary>
  476. public abstract void Restart();
  477. /// <summary>
  478. /// Gets or sets a value indicating whether this instance can self update.
  479. /// </summary>
  480. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  481. public abstract bool CanSelfUpdate { get; }
  482. /// <summary>
  483. /// Checks for update.
  484. /// </summary>
  485. /// <param name="cancellationToken">The cancellation token.</param>
  486. /// <param name="progress">The progress.</param>
  487. /// <returns>Task{CheckForUpdateResult}.</returns>
  488. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress);
  489. /// <summary>
  490. /// Updates the application.
  491. /// </summary>
  492. /// <param name="package">The package that contains the update</param>
  493. /// <param name="cancellationToken">The cancellation token.</param>
  494. /// <param name="progress">The progress.</param>
  495. /// <returns>Task.</returns>
  496. public async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  497. {
  498. await PackageManager.InstallPackage(progress, package, cancellationToken).ConfigureAwait(false);
  499. EventHelper.QueueEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<Version> { Argument = package.version }, Logger);
  500. NotifyPendingRestart();
  501. }
  502. /// <summary>
  503. /// Shuts down.
  504. /// </summary>
  505. public abstract void Shutdown();
  506. }
  507. }