InstallationManager.cs 19 KB

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