BaseApplicationHost.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Implementations.Devices;
  4. using MediaBrowser.Common.Implementations.IO;
  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.Progress;
  12. using MediaBrowser.Common.ScheduledTasks;
  13. using MediaBrowser.Common.Security;
  14. using MediaBrowser.Common.Updates;
  15. using MediaBrowser.Model.Events;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Logging;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Model.Updates;
  20. using System;
  21. using System.Collections.Generic;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Net;
  25. using System.Reflection;
  26. using System.Runtime.InteropServices;
  27. using System.Text;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. using MediaBrowser.Common.Extensions;
  31. using MediaBrowser.Common.Implementations.Cryptography;
  32. using MediaBrowser.Common.IO;
  33. using MediaBrowser.Model.Cryptography;
  34. using MediaBrowser.Model.Tasks;
  35. namespace MediaBrowser.Common.Implementations
  36. {
  37. /// <summary>
  38. /// Class BaseApplicationHost
  39. /// </summary>
  40. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  41. public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationHost
  42. where TApplicationPathsType : class, IApplicationPaths
  43. {
  44. /// <summary>
  45. /// Occurs when [has pending restart changed].
  46. /// </summary>
  47. public event EventHandler HasPendingRestartChanged;
  48. /// <summary>
  49. /// Occurs when [application updated].
  50. /// </summary>
  51. public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
  52. /// <summary>
  53. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  54. /// </summary>
  55. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  56. public bool HasPendingRestart { get; private set; }
  57. /// <summary>
  58. /// Gets or sets the logger.
  59. /// </summary>
  60. /// <value>The logger.</value>
  61. protected ILogger Logger { get; private set; }
  62. /// <summary>
  63. /// Gets or sets the plugins.
  64. /// </summary>
  65. /// <value>The plugins.</value>
  66. public IPlugin[] Plugins { get; protected set; }
  67. /// <summary>
  68. /// Gets or sets the log manager.
  69. /// </summary>
  70. /// <value>The log manager.</value>
  71. public ILogManager LogManager { get; protected set; }
  72. /// <summary>
  73. /// Gets the application paths.
  74. /// </summary>
  75. /// <value>The application paths.</value>
  76. protected TApplicationPathsType ApplicationPaths { get; private set; }
  77. /// <summary>
  78. /// The json serializer
  79. /// </summary>
  80. public IJsonSerializer JsonSerializer { get; private set; }
  81. /// <summary>
  82. /// The _XML serializer
  83. /// </summary>
  84. protected readonly IXmlSerializer XmlSerializer;
  85. /// <summary>
  86. /// Gets assemblies that failed to load
  87. /// </summary>
  88. /// <value>The failed assemblies.</value>
  89. public List<string> FailedAssemblies { 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. public 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; private set; }
  134. protected IFileSystem FileSystemManager { get; private set; }
  135. protected IIsoManager IsoManager { get; private set; }
  136. /// <summary>
  137. /// Gets the name.
  138. /// </summary>
  139. /// <value>The name.</value>
  140. public abstract string Name { get; }
  141. /// <summary>
  142. /// Gets a value indicating whether this instance is running as service.
  143. /// </summary>
  144. /// <value><c>true</c> if this instance is running as service; otherwise, <c>false</c>.</value>
  145. public abstract bool IsRunningAsService { get; }
  146. protected ICryptographyProvider CryptographyProvider = new CryptographyProvider();
  147. private DeviceId _deviceId;
  148. public string SystemId
  149. {
  150. get
  151. {
  152. if (_deviceId == null)
  153. {
  154. _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager);
  155. }
  156. return _deviceId.Value;
  157. }
  158. }
  159. public virtual string OperatingSystemDisplayName
  160. {
  161. get { return Environment.OSVersion.VersionString; }
  162. }
  163. public IMemoryStreamProvider MemoryStreamProvider { get; set; }
  164. /// <summary>
  165. /// Initializes a new instance of the <see cref="BaseApplicationHost{TApplicationPathsType}"/> class.
  166. /// </summary>
  167. protected BaseApplicationHost(TApplicationPathsType applicationPaths,
  168. ILogManager logManager,
  169. IFileSystem fileSystem)
  170. {
  171. // hack alert, until common can target .net core
  172. BaseExtensions.CryptographyProvider = CryptographyProvider;
  173. XmlSerializer = new XmlSerializer(fileSystem, logManager.GetLogger("XmlSerializer"));
  174. FailedAssemblies = new List<string>();
  175. ApplicationPaths = applicationPaths;
  176. LogManager = logManager;
  177. FileSystemManager = fileSystem;
  178. ConfigurationManager = GetConfigurationManager();
  179. // Initialize this early in case the -v command line option is used
  180. Logger = LogManager.GetLogger("App");
  181. }
  182. /// <summary>
  183. /// Inits this instance.
  184. /// </summary>
  185. /// <returns>Task.</returns>
  186. public virtual async Task Init(IProgress<double> progress)
  187. {
  188. progress.Report(1);
  189. JsonSerializer = CreateJsonSerializer();
  190. MemoryStreamProvider = CreateMemoryStreamProvider();
  191. OnLoggerLoaded(true);
  192. LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
  193. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  194. progress.Report(2);
  195. LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
  196. ? LogSeverity.Debug
  197. : LogSeverity.Info;
  198. progress.Report(3);
  199. DiscoverTypes();
  200. progress.Report(14);
  201. SetHttpLimit();
  202. progress.Report(15);
  203. var innerProgress = new ActionableProgress<double>();
  204. innerProgress.RegisterAction(p => progress.Report(.8 * p + 15));
  205. await RegisterResources(innerProgress).ConfigureAwait(false);
  206. FindParts();
  207. progress.Report(95);
  208. await InstallIsoMounters(CancellationToken.None).ConfigureAwait(false);
  209. progress.Report(100);
  210. }
  211. protected abstract IMemoryStreamProvider CreateMemoryStreamProvider();
  212. protected virtual void OnLoggerLoaded(bool isFirstLoad)
  213. {
  214. Logger.Info("Application version: {0}", ApplicationVersion);
  215. if (!isFirstLoad)
  216. {
  217. LogEnvironmentInfo(Logger, ApplicationPaths, false);
  218. }
  219. // Put the app config in the log for troubleshooting purposes
  220. Logger.LogMultiline("Application configuration:", LogSeverity.Info, new StringBuilder(JsonSerializer.SerializeToString(ConfigurationManager.CommonConfiguration)));
  221. if (Plugins != null)
  222. {
  223. var pluginBuilder = new StringBuilder();
  224. foreach (var plugin in Plugins)
  225. {
  226. pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
  227. }
  228. Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder);
  229. }
  230. }
  231. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, bool isStartup)
  232. {
  233. logger.LogMultiline("Emby", LogSeverity.Info, GetBaseExceptionMessage(appPaths));
  234. }
  235. protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths)
  236. {
  237. var builder = new StringBuilder();
  238. builder.AppendLine(string.Format("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs())));
  239. builder.AppendLine(string.Format("Operating system: {0}", Environment.OSVersion));
  240. builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount));
  241. builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem));
  242. builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess));
  243. builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath));
  244. Type type = Type.GetType("Mono.Runtime");
  245. if (type != null)
  246. {
  247. MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
  248. if (displayName != null)
  249. {
  250. builder.AppendLine("Mono: " + displayName.Invoke(null, null));
  251. }
  252. }
  253. builder.AppendLine(string.Format("Application Path: {0}", appPaths.ApplicationPath));
  254. return builder;
  255. }
  256. protected abstract IJsonSerializer CreateJsonSerializer();
  257. private void SetHttpLimit()
  258. {
  259. try
  260. {
  261. // Increase the max http request limit
  262. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  263. }
  264. catch (Exception ex)
  265. {
  266. Logger.ErrorException("Error setting http limit", ex);
  267. }
  268. }
  269. /// <summary>
  270. /// Installs the iso mounters.
  271. /// </summary>
  272. /// <param name="cancellationToken">The cancellation token.</param>
  273. /// <returns>Task.</returns>
  274. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  275. {
  276. var list = new List<IIsoMounter>();
  277. foreach (var isoMounter in GetExports<IIsoMounter>())
  278. {
  279. try
  280. {
  281. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  282. {
  283. Logger.Info("Installing {0}", isoMounter.Name);
  284. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  285. }
  286. list.Add(isoMounter);
  287. }
  288. catch (Exception ex)
  289. {
  290. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  291. }
  292. }
  293. IsoManager.AddParts(list);
  294. }
  295. /// <summary>
  296. /// Runs the startup tasks.
  297. /// </summary>
  298. /// <returns>Task.</returns>
  299. public virtual Task RunStartupTasks()
  300. {
  301. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  302. ConfigureAutorun();
  303. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  304. return Task.FromResult(true);
  305. }
  306. /// <summary>
  307. /// Configures the autorun.
  308. /// </summary>
  309. private void ConfigureAutorun()
  310. {
  311. try
  312. {
  313. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  314. }
  315. catch (Exception ex)
  316. {
  317. Logger.ErrorException("Error configuring autorun", ex);
  318. }
  319. }
  320. /// <summary>
  321. /// Gets the composable part assemblies.
  322. /// </summary>
  323. /// <returns>IEnumerable{Assembly}.</returns>
  324. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  325. /// <summary>
  326. /// Gets the configuration manager.
  327. /// </summary>
  328. /// <returns>IConfigurationManager.</returns>
  329. protected abstract IConfigurationManager GetConfigurationManager();
  330. /// <summary>
  331. /// Finds the parts.
  332. /// </summary>
  333. protected virtual void FindParts()
  334. {
  335. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  336. Plugins = GetExports<IPlugin>().Select(LoadPlugin).Where(i => i != null).ToArray();
  337. }
  338. private IPlugin LoadPlugin(IPlugin plugin)
  339. {
  340. try
  341. {
  342. var assemblyPlugin = plugin as IPluginAssembly;
  343. if (assemblyPlugin != null)
  344. {
  345. var assembly = plugin.GetType().Assembly;
  346. var assemblyName = assembly.GetName();
  347. var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
  348. var assemblyId = new Guid(attribute.Value);
  349. var assemblyFileName = assemblyName.Name + ".dll";
  350. var assemblyFilePath = Path.Combine(ApplicationPaths.PluginsPath, assemblyFileName);
  351. assemblyPlugin.SetAttributes(assemblyFilePath, assemblyFileName, assemblyName.Version, assemblyId);
  352. }
  353. var isFirstRun = !File.Exists(plugin.ConfigurationFilePath);
  354. plugin.SetStartupInfo(isFirstRun, File.GetLastWriteTimeUtc, s => Directory.CreateDirectory(s));
  355. }
  356. catch (Exception ex)
  357. {
  358. Logger.ErrorException("Error loading plugin {0}", ex, plugin.GetType().FullName);
  359. return null;
  360. }
  361. return plugin;
  362. }
  363. /// <summary>
  364. /// Discovers the types.
  365. /// </summary>
  366. protected void DiscoverTypes()
  367. {
  368. FailedAssemblies.Clear();
  369. var assemblies = GetComposablePartAssemblies().ToList();
  370. foreach (var assembly in assemblies)
  371. {
  372. Logger.Info("Loading {0}", assembly.FullName);
  373. }
  374. AllConcreteTypes = assemblies
  375. .SelectMany(GetTypes)
  376. .Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType)
  377. .ToArray();
  378. }
  379. /// <summary>
  380. /// Registers resources that classes will depend on
  381. /// </summary>
  382. /// <returns>Task.</returns>
  383. protected virtual Task RegisterResources(IProgress<double> progress)
  384. {
  385. RegisterSingleInstance(ConfigurationManager);
  386. RegisterSingleInstance<IApplicationHost>(this);
  387. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  388. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager);
  389. RegisterSingleInstance(JsonSerializer);
  390. RegisterSingleInstance(XmlSerializer);
  391. RegisterSingleInstance(MemoryStreamProvider);
  392. RegisterSingleInstance(LogManager);
  393. RegisterSingleInstance(Logger);
  394. RegisterSingleInstance(TaskManager);
  395. RegisterSingleInstance(FileSystemManager);
  396. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, MemoryStreamProvider);
  397. RegisterSingleInstance(HttpClient);
  398. NetworkManager = CreateNetworkManager(LogManager.GetLogger("NetworkManager"));
  399. RegisterSingleInstance(NetworkManager);
  400. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager);
  401. RegisterSingleInstance(SecurityManager);
  402. InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager);
  403. RegisterSingleInstance(InstallationManager);
  404. IsoManager = new IsoManager();
  405. RegisterSingleInstance(IsoManager);
  406. return Task.FromResult(true);
  407. }
  408. /// <summary>
  409. /// Gets a list of types within an assembly
  410. /// 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
  411. /// </summary>
  412. /// <param name="assembly">The assembly.</param>
  413. /// <returns>IEnumerable{Type}.</returns>
  414. /// <exception cref="System.ArgumentNullException">assembly</exception>
  415. protected IEnumerable<Type> GetTypes(Assembly assembly)
  416. {
  417. if (assembly == null)
  418. {
  419. throw new ArgumentNullException("assembly");
  420. }
  421. try
  422. {
  423. return assembly.GetTypes();
  424. }
  425. catch (ReflectionTypeLoadException ex)
  426. {
  427. if (ex.LoaderExceptions != null)
  428. {
  429. foreach (var loaderException in ex.LoaderExceptions)
  430. {
  431. Logger.Error("LoaderException: " + loaderException.Message);
  432. }
  433. }
  434. // If it fails we can still get a list of the Types it was able to resolve
  435. return ex.Types.Where(t => t != null);
  436. }
  437. }
  438. protected abstract INetworkManager CreateNetworkManager(ILogger logger);
  439. /// <summary>
  440. /// Creates an instance of type and resolves all constructor dependancies
  441. /// </summary>
  442. /// <param name="type">The type.</param>
  443. /// <returns>System.Object.</returns>
  444. public abstract object CreateInstance(Type type);
  445. /// <summary>
  446. /// Creates the instance safe.
  447. /// </summary>
  448. /// <param name="type">The type.</param>
  449. /// <returns>System.Object.</returns>
  450. protected abstract object CreateInstanceSafe(Type type);
  451. /// <summary>
  452. /// Registers the specified obj.
  453. /// </summary>
  454. /// <typeparam name="T"></typeparam>
  455. /// <param name="obj">The obj.</param>
  456. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  457. protected abstract void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  458. where T : class;
  459. /// <summary>
  460. /// Registers the single instance.
  461. /// </summary>
  462. /// <typeparam name="T"></typeparam>
  463. /// <param name="func">The func.</param>
  464. protected abstract void RegisterSingleInstance<T>(Func<T> func)
  465. where T : class;
  466. /// <summary>
  467. /// Resolves this instance.
  468. /// </summary>
  469. /// <typeparam name="T"></typeparam>
  470. /// <returns>``0.</returns>
  471. public abstract T Resolve<T>();
  472. /// <summary>
  473. /// Resolves this instance.
  474. /// </summary>
  475. /// <typeparam name="T"></typeparam>
  476. /// <returns>``0.</returns>
  477. public abstract T TryResolve<T>();
  478. /// <summary>
  479. /// Loads the assembly.
  480. /// </summary>
  481. /// <param name="file">The file.</param>
  482. /// <returns>Assembly.</returns>
  483. protected Assembly LoadAssembly(string file)
  484. {
  485. try
  486. {
  487. return Assembly.Load(File.ReadAllBytes(file));
  488. }
  489. catch (Exception ex)
  490. {
  491. FailedAssemblies.Add(file);
  492. Logger.ErrorException("Error loading assembly {0}", ex, file);
  493. return null;
  494. }
  495. }
  496. /// <summary>
  497. /// Gets the export types.
  498. /// </summary>
  499. /// <typeparam name="T"></typeparam>
  500. /// <returns>IEnumerable{Type}.</returns>
  501. public IEnumerable<Type> GetExportTypes<T>()
  502. {
  503. var currentType = typeof(T);
  504. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  505. }
  506. /// <summary>
  507. /// Gets the exports.
  508. /// </summary>
  509. /// <typeparam name="T"></typeparam>
  510. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  511. /// <returns>IEnumerable{``0}.</returns>
  512. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  513. {
  514. var parts = GetExportTypes<T>()
  515. .Select(CreateInstanceSafe)
  516. .Where(i => i != null)
  517. .Cast<T>()
  518. .ToList();
  519. if (manageLiftime)
  520. {
  521. lock (DisposableParts)
  522. {
  523. DisposableParts.AddRange(parts.OfType<IDisposable>());
  524. }
  525. }
  526. return parts;
  527. }
  528. /// <summary>
  529. /// Gets the application version.
  530. /// </summary>
  531. /// <value>The application version.</value>
  532. public abstract Version ApplicationVersion { get; }
  533. /// <summary>
  534. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  535. /// </summary>
  536. /// <param name="sender">The source of the event.</param>
  537. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  538. /// <exception cref="System.NotImplementedException"></exception>
  539. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  540. {
  541. ConfigureAutorun();
  542. }
  543. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  544. /// <summary>
  545. /// Removes the plugin.
  546. /// </summary>
  547. /// <param name="plugin">The plugin.</param>
  548. public void RemovePlugin(IPlugin plugin)
  549. {
  550. var list = Plugins.ToList();
  551. list.Remove(plugin);
  552. Plugins = list.ToArray();
  553. }
  554. /// <summary>
  555. /// Gets a value indicating whether this instance can self restart.
  556. /// </summary>
  557. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  558. public abstract bool CanSelfRestart { get; }
  559. /// <summary>
  560. /// Notifies that the kernel that a change has been made that requires a restart
  561. /// </summary>
  562. public void NotifyPendingRestart()
  563. {
  564. var changed = !HasPendingRestart;
  565. HasPendingRestart = true;
  566. if (changed)
  567. {
  568. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  569. }
  570. }
  571. /// <summary>
  572. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  573. /// </summary>
  574. public void Dispose()
  575. {
  576. Dispose(true);
  577. }
  578. /// <summary>
  579. /// Releases unmanaged and - optionally - managed resources.
  580. /// </summary>
  581. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  582. protected virtual void Dispose(bool dispose)
  583. {
  584. if (dispose)
  585. {
  586. var type = GetType();
  587. Logger.Info("Disposing " + type.Name);
  588. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  589. DisposableParts.Clear();
  590. foreach (var part in parts)
  591. {
  592. Logger.Info("Disposing " + part.GetType().Name);
  593. try
  594. {
  595. part.Dispose();
  596. }
  597. catch (Exception ex)
  598. {
  599. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  600. }
  601. }
  602. }
  603. }
  604. /// <summary>
  605. /// Restarts this instance.
  606. /// </summary>
  607. public abstract Task Restart();
  608. /// <summary>
  609. /// Gets or sets a value indicating whether this instance can self update.
  610. /// </summary>
  611. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  612. public abstract bool CanSelfUpdate { get; }
  613. /// <summary>
  614. /// Checks for update.
  615. /// </summary>
  616. /// <param name="cancellationToken">The cancellation token.</param>
  617. /// <param name="progress">The progress.</param>
  618. /// <returns>Task{CheckForUpdateResult}.</returns>
  619. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  620. IProgress<double> progress);
  621. /// <summary>
  622. /// Updates the application.
  623. /// </summary>
  624. /// <param name="package">The package that contains the update</param>
  625. /// <param name="cancellationToken">The cancellation token.</param>
  626. /// <param name="progress">The progress.</param>
  627. /// <returns>Task.</returns>
  628. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  629. IProgress<double> progress);
  630. /// <summary>
  631. /// Shuts down.
  632. /// </summary>
  633. public abstract Task Shutdown();
  634. /// <summary>
  635. /// Called when [application updated].
  636. /// </summary>
  637. /// <param name="package">The package.</param>
  638. protected void OnApplicationUpdated(PackageVersionInfo package)
  639. {
  640. Logger.Info("Application has been updated to version {0}", package.versionStr);
  641. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  642. {
  643. Argument = package
  644. }, Logger);
  645. NotifyPendingRestart();
  646. }
  647. }
  648. }