InstallationManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Common.Plugins;
  4. using MediaBrowser.Common.Progress;
  5. using MediaBrowser.Common.Updates;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using MediaBrowser.Model.Updates;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Common.Implementations.Updates
  17. {
  18. /// <summary>
  19. /// Manages all install, uninstall and update operations (both plugins and system)
  20. /// </summary>
  21. public class InstallationManager : IInstallationManager
  22. {
  23. public event EventHandler<InstallationEventArgs> PackageInstalling;
  24. public event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
  25. public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
  26. public event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
  27. /// <summary>
  28. /// The current installations
  29. /// </summary>
  30. public List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations { get; set; }
  31. /// <summary>
  32. /// The completed installations
  33. /// </summary>
  34. public ConcurrentBag<InstallationInfo> CompletedInstallations { get; set; }
  35. #region PluginUninstalled Event
  36. /// <summary>
  37. /// Occurs when [plugin uninstalled].
  38. /// </summary>
  39. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  40. /// <summary>
  41. /// Called when [plugin uninstalled].
  42. /// </summary>
  43. /// <param name="plugin">The plugin.</param>
  44. private void OnPluginUninstalled(IPlugin plugin)
  45. {
  46. EventHelper.QueueEventIfNotNull(PluginUninstalled, this, new GenericEventArgs<IPlugin> { Argument = plugin }, _logger);
  47. }
  48. #endregion
  49. #region PluginUpdated Event
  50. /// <summary>
  51. /// Occurs when [plugin updated].
  52. /// </summary>
  53. public event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
  54. /// <summary>
  55. /// Called when [plugin updated].
  56. /// </summary>
  57. /// <param name="plugin">The plugin.</param>
  58. /// <param name="newVersion">The new version.</param>
  59. private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
  60. {
  61. _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.version, newVersion.classification);
  62. EventHelper.QueueEventIfNotNull(PluginUpdated, this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) }, _logger);
  63. ApplicationHost.NotifyPendingRestart();
  64. }
  65. #endregion
  66. #region PluginInstalled Event
  67. /// <summary>
  68. /// Occurs when [plugin updated].
  69. /// </summary>
  70. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  71. /// <summary>
  72. /// Called when [plugin installed].
  73. /// </summary>
  74. /// <param name="package">The package.</param>
  75. private void OnPluginInstalled(PackageVersionInfo package)
  76. {
  77. _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.version, package.classification);
  78. EventHelper.QueueEventIfNotNull(PluginInstalled, this, new GenericEventArgs<PackageVersionInfo> { Argument = package }, _logger);
  79. ApplicationHost.NotifyPendingRestart();
  80. }
  81. #endregion
  82. /// <summary>
  83. /// The _logger
  84. /// </summary>
  85. private readonly ILogger _logger;
  86. /// <summary>
  87. /// The package manager
  88. /// </summary>
  89. private readonly IPackageManager _packageManager;
  90. /// <summary>
  91. /// Gets the json serializer.
  92. /// </summary>
  93. /// <value>The json serializer.</value>
  94. protected IJsonSerializer JsonSerializer { get; private set; }
  95. /// <summary>
  96. /// Gets the HTTP client.
  97. /// </summary>
  98. /// <value>The HTTP client.</value>
  99. protected IHttpClient HttpClient { get; private set; }
  100. /// <summary>
  101. /// Gets the application host.
  102. /// </summary>
  103. /// <value>The application host.</value>
  104. protected IApplicationHost ApplicationHost { get; private set; }
  105. /// <summary>
  106. /// Initializes a new instance of the <see cref="InstallationManager" /> class.
  107. /// </summary>
  108. /// <param name="httpClient">The HTTP client.</param>
  109. /// <param name="packageManager">The package manager.</param>
  110. /// <param name="jsonSerializer">The json serializer.</param>
  111. /// <param name="logger">The logger.</param>
  112. /// <param name="appHost">The app host.</param>
  113. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  114. public InstallationManager(IHttpClient httpClient, IPackageManager packageManager, IJsonSerializer jsonSerializer, ILogger logger, IApplicationHost appHost)
  115. {
  116. if (packageManager == null)
  117. {
  118. throw new ArgumentNullException("packageManager");
  119. }
  120. if (logger == null)
  121. {
  122. throw new ArgumentNullException("logger");
  123. }
  124. if (jsonSerializer == null)
  125. {
  126. throw new ArgumentNullException("jsonSerializer");
  127. }
  128. if (httpClient == null)
  129. {
  130. throw new ArgumentNullException("httpClient");
  131. }
  132. CurrentInstallations = new List<Tuple<InstallationInfo, CancellationTokenSource>>();
  133. CompletedInstallations = new ConcurrentBag<InstallationInfo>();
  134. JsonSerializer = jsonSerializer;
  135. HttpClient = httpClient;
  136. ApplicationHost = appHost;
  137. _packageManager = packageManager;
  138. _logger = logger;
  139. }
  140. /// <summary>
  141. /// Gets all available packages.
  142. /// </summary>
  143. /// <param name="cancellationToken">The cancellation token.</param>
  144. /// <param name="packageType">Type of the package.</param>
  145. /// <param name="applicationVersion">The application version.</param>
  146. /// <returns>Task{List{PackageInfo}}.</returns>
  147. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  148. PackageType? packageType = null,
  149. Version applicationVersion = null)
  150. {
  151. var packages = (await _packageManager.GetAvailablePackages(cancellationToken).ConfigureAwait(false)).ToList();
  152. return FilterPackages(packages, packageType, applicationVersion);
  153. }
  154. /// <summary>
  155. /// Gets all available packages.
  156. /// </summary>
  157. /// <param name="cancellationToken">The cancellation token.</param>
  158. /// <param name="packageType">Type of the package.</param>
  159. /// <param name="applicationVersion">The application version.</param>
  160. /// <returns>Task{List{PackageInfo}}.</returns>
  161. protected async Task<IEnumerable<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken,
  162. PackageType? packageType = null,
  163. Version applicationVersion = null)
  164. {
  165. var packages = (await _packageManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false)).ToList();
  166. return FilterPackages(packages, packageType, applicationVersion);
  167. }
  168. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages, PackageType? packageType, Version applicationVersion)
  169. {
  170. if (packageType.HasValue)
  171. {
  172. packages = packages.Where(p => p.type == packageType.Value).ToList();
  173. }
  174. // If an app version was supplied, filter the versions for each package to only include supported versions
  175. if (applicationVersion != null)
  176. {
  177. foreach (var package in packages)
  178. {
  179. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  180. }
  181. }
  182. // Remove packages with no versions
  183. packages = packages.Where(p => p.versions.Any()).ToList();
  184. return packages;
  185. }
  186. /// <summary>
  187. /// Determines whether [is package version up to date] [the specified package version info].
  188. /// </summary>
  189. /// <param name="packageVersionInfo">The package version info.</param>
  190. /// <param name="applicationVersion">The application version.</param>
  191. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  192. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version applicationVersion)
  193. {
  194. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  195. {
  196. return true;
  197. }
  198. Version requiredVersion;
  199. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && applicationVersion >= requiredVersion;
  200. }
  201. /// <summary>
  202. /// Gets the package.
  203. /// </summary>
  204. /// <param name="name">The name.</param>
  205. /// <param name="classification">The classification.</param>
  206. /// <param name="version">The version.</param>
  207. /// <returns>Task{PackageVersionInfo}.</returns>
  208. public async Task<PackageVersionInfo> GetPackage(string name, PackageVersionClass classification, Version version)
  209. {
  210. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  211. var package = packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  212. if (package == null)
  213. {
  214. return null;
  215. }
  216. return package.versions.FirstOrDefault(v => v.version.Equals(version) && v.classification == classification);
  217. }
  218. /// <summary>
  219. /// Gets the latest compatible version.
  220. /// </summary>
  221. /// <param name="name">The name.</param>
  222. /// <param name="classification">The classification.</param>
  223. /// <returns>Task{PackageVersionInfo}.</returns>
  224. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, PackageVersionClass classification = PackageVersionClass.Release)
  225. {
  226. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  227. return GetLatestCompatibleVersion(packages, name, classification);
  228. }
  229. /// <summary>
  230. /// Gets the latest compatible version.
  231. /// </summary>
  232. /// <param name="availablePackages">The available packages.</param>
  233. /// <param name="name">The name.</param>
  234. /// <param name="classification">The classification.</param>
  235. /// <returns>PackageVersionInfo.</returns>
  236. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, PackageVersionClass classification = PackageVersionClass.Release)
  237. {
  238. var package = availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  239. if (package == null)
  240. {
  241. return null;
  242. }
  243. return package.versions
  244. .OrderByDescending(v => v.version)
  245. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, ApplicationHost.ApplicationVersion));
  246. }
  247. /// <summary>
  248. /// Gets the available plugin updates including registration information for each one.
  249. /// Used with API and catalog.
  250. /// </summary>
  251. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  252. /// <param name="cancellationToken">The cancellation token.</param>
  253. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  254. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  255. {
  256. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  257. return FilterCatalog(catalog, withAutoUpdateEnabled);
  258. }
  259. /// <summary>
  260. /// Gets the available plugin updates from a static resource - no registration information.
  261. /// Used for update checks.
  262. /// </summary>
  263. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  264. /// <param name="cancellationToken">The cancellation token.</param>
  265. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  266. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdatesWithoutRegistrationInfo(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  267. {
  268. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  269. return FilterCatalog(catalog, withAutoUpdateEnabled);
  270. }
  271. protected IEnumerable<PackageVersionInfo> FilterCatalog(IEnumerable<PackageInfo> catalog, bool withAutoUpdateEnabled)
  272. {
  273. var plugins = ApplicationHost.Plugins;
  274. if (withAutoUpdateEnabled)
  275. {
  276. plugins = plugins.Where(p => p.Configuration.EnableAutoUpdate);
  277. }
  278. // Figure out what needs to be installed
  279. return plugins.Select(p =>
  280. {
  281. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Configuration.UpdateClass);
  282. return latestPluginInfo != null && latestPluginInfo.version > p.Version ? latestPluginInfo : null;
  283. }).Where(p => !CompletedInstallations.Any(i => string.Equals(i.Name, p.name, StringComparison.OrdinalIgnoreCase)))
  284. .Where(p => p != null && !string.IsNullOrWhiteSpace(p.sourceUrl));
  285. }
  286. /// <summary>
  287. /// Installs the package.
  288. /// </summary>
  289. /// <param name="package">The package.</param>
  290. /// <param name="progress">The progress.</param>
  291. /// <param name="cancellationToken">The cancellation token.</param>
  292. /// <returns>Task.</returns>
  293. /// <exception cref="System.ArgumentNullException">package</exception>
  294. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  295. {
  296. if (package == null)
  297. {
  298. throw new ArgumentNullException("package");
  299. }
  300. if (progress == null)
  301. {
  302. throw new ArgumentNullException("progress");
  303. }
  304. if (cancellationToken == null)
  305. {
  306. throw new ArgumentNullException("cancellationToken");
  307. }
  308. var installationInfo = new InstallationInfo
  309. {
  310. Id = Guid.NewGuid(),
  311. Name = package.name,
  312. UpdateClass = package.classification,
  313. Version = package.versionStr
  314. };
  315. var innerCancellationTokenSource = new CancellationTokenSource();
  316. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  317. // Add it to the in-progress list
  318. lock (CurrentInstallations)
  319. {
  320. CurrentInstallations.Add(tuple);
  321. }
  322. var innerProgress = new ActionableProgress<double>();
  323. // Whenever the progress updates, update the outer progress object and InstallationInfo
  324. innerProgress.RegisterAction(percent =>
  325. {
  326. progress.Report(percent);
  327. installationInfo.PercentComplete = percent;
  328. });
  329. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  330. var installationEventArgs = new InstallationEventArgs
  331. {
  332. InstallationInfo = installationInfo,
  333. PackageVersionInfo = package
  334. };
  335. EventHelper.QueueEventIfNotNull(PackageInstalling, this, installationEventArgs, _logger);
  336. try
  337. {
  338. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  339. lock (CurrentInstallations)
  340. {
  341. CurrentInstallations.Remove(tuple);
  342. }
  343. CompletedInstallations.Add(installationInfo);
  344. EventHelper.QueueEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
  345. }
  346. catch (OperationCanceledException)
  347. {
  348. lock (CurrentInstallations)
  349. {
  350. CurrentInstallations.Remove(tuple);
  351. }
  352. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  353. EventHelper.QueueEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
  354. throw;
  355. }
  356. catch (Exception ex)
  357. {
  358. _logger.ErrorException("Package installation failed", ex);
  359. lock (CurrentInstallations)
  360. {
  361. CurrentInstallations.Remove(tuple);
  362. }
  363. EventHelper.QueueEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
  364. {
  365. InstallationInfo = installationInfo,
  366. Exception = ex
  367. }, _logger);
  368. throw;
  369. }
  370. finally
  371. {
  372. // Dispose the progress object and remove the installation from the in-progress list
  373. innerProgress.Dispose();
  374. tuple.Item2.Dispose();
  375. }
  376. }
  377. /// <summary>
  378. /// Installs the package internal.
  379. /// </summary>
  380. /// <param name="package">The package.</param>
  381. /// <param name="progress">The progress.</param>
  382. /// <param name="cancellationToken">The cancellation token.</param>
  383. /// <returns>Task.</returns>
  384. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  385. {
  386. // Do the install
  387. await _packageManager.InstallPackage(progress, package, cancellationToken).ConfigureAwait(false);
  388. // Do plugin-specific processing
  389. if (!(Path.GetExtension(package.targetFilename) ?? "").Equals(".zip", StringComparison.OrdinalIgnoreCase))
  390. {
  391. // Set last update time if we were installed before
  392. var plugin = ApplicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  393. if (plugin != null)
  394. {
  395. OnPluginUpdated(plugin, package);
  396. }
  397. else
  398. {
  399. OnPluginInstalled(package);
  400. }
  401. }
  402. }
  403. /// <summary>
  404. /// Uninstalls a plugin
  405. /// </summary>
  406. /// <param name="plugin">The plugin.</param>
  407. /// <exception cref="System.ArgumentException"></exception>
  408. public void UninstallPlugin(IPlugin plugin)
  409. {
  410. plugin.OnUninstalling();
  411. // Remove it the quick way for now
  412. ApplicationHost.RemovePlugin(plugin);
  413. File.Delete(plugin.AssemblyFilePath);
  414. OnPluginUninstalled(plugin);
  415. ApplicationHost.NotifyPendingRestart();
  416. }
  417. /// <summary>
  418. /// Releases unmanaged and - optionally - managed resources.
  419. /// </summary>
  420. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  421. protected virtual void Dispose(bool dispose)
  422. {
  423. if (dispose)
  424. {
  425. lock (CurrentInstallations)
  426. {
  427. foreach (var tuple in CurrentInstallations)
  428. {
  429. tuple.Item2.Dispose();
  430. }
  431. CurrentInstallations.Clear();
  432. }
  433. }
  434. }
  435. public void Dispose()
  436. {
  437. Dispose(true);
  438. }
  439. }
  440. }