BaseApplicationHost.cs 20 KB

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