InstallationManager.cs 19 KB

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