InstallationManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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.Security.Cryptography;
  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. /// <summary>
  27. /// The current installations
  28. /// </summary>
  29. public List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations { get; set; }
  30. /// <summary>
  31. /// The completed installations
  32. /// </summary>
  33. public ConcurrentBag<InstallationInfo> CompletedInstallations { get; set; }
  34. #region PluginUninstalled Event
  35. /// <summary>
  36. /// Occurs when [plugin uninstalled].
  37. /// </summary>
  38. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  39. /// <summary>
  40. /// Called when [plugin uninstalled].
  41. /// </summary>
  42. /// <param name="plugin">The plugin.</param>
  43. private void OnPluginUninstalled(IPlugin plugin)
  44. {
  45. EventHelper.QueueEventIfNotNull(PluginUninstalled, this, new GenericEventArgs<IPlugin> { Argument = plugin }, _logger);
  46. // Notify connected ui's
  47. Kernel.ServerManager.SendWebSocketMessage("PluginUninstalled", plugin.GetPluginInfo());
  48. }
  49. #endregion
  50. #region PluginUpdated Event
  51. /// <summary>
  52. /// Occurs when [plugin updated].
  53. /// </summary>
  54. public event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
  55. /// <summary>
  56. /// Called when [plugin updated].
  57. /// </summary>
  58. /// <param name="plugin">The plugin.</param>
  59. /// <param name="newVersion">The new version.</param>
  60. public void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
  61. {
  62. _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.version, newVersion.classification);
  63. EventHelper.QueueEventIfNotNull(PluginUpdated, this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) }, _logger);
  64. Kernel.NotifyPendingRestart();
  65. }
  66. #endregion
  67. #region PluginInstalled Event
  68. /// <summary>
  69. /// Occurs when [plugin updated].
  70. /// </summary>
  71. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  72. /// <summary>
  73. /// Called when [plugin installed].
  74. /// </summary>
  75. /// <param name="package">The package.</param>
  76. public void OnPluginInstalled(PackageVersionInfo package)
  77. {
  78. _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.version, package.classification);
  79. EventHelper.QueueEventIfNotNull(PluginInstalled, this, new GenericEventArgs<PackageVersionInfo> { Argument = package }, _logger);
  80. Kernel.NotifyPendingRestart();
  81. }
  82. #endregion
  83. /// <summary>
  84. /// Gets or sets the zip client.
  85. /// </summary>
  86. /// <value>The zip client.</value>
  87. private IZipClient ZipClient { get; set; }
  88. /// <summary>
  89. /// The _logger
  90. /// </summary>
  91. private readonly ILogger _logger;
  92. /// <summary>
  93. /// The _network manager
  94. /// </summary>
  95. private readonly INetworkManager _networkManager;
  96. /// <summary>
  97. /// The package manager
  98. /// </summary>
  99. private readonly IPackageManager _packageManager;
  100. /// <summary>
  101. /// Gets the json serializer.
  102. /// </summary>
  103. /// <value>The json serializer.</value>
  104. protected IJsonSerializer JsonSerializer { get; private set; }
  105. /// <summary>
  106. /// Gets the HTTP client.
  107. /// </summary>
  108. /// <value>The HTTP client.</value>
  109. protected IHttpClient HttpClient { get; private set; }
  110. /// <summary>
  111. /// Gets the application host.
  112. /// </summary>
  113. /// <value>The application host.</value>
  114. protected IApplicationHost ApplicationHost { get; private set; }
  115. /// <summary>
  116. /// Initializes a new instance of the <see cref="InstallationManager" /> class.
  117. /// </summary>
  118. /// <param name="kernel">The kernel.</param>
  119. /// <param name="httpClient">The HTTP client.</param>
  120. /// <param name="zipClient">The zip client.</param>
  121. /// <param name="networkManager">The network manager.</param>
  122. /// <param name="packageManager">The package manager.</param>
  123. /// <param name="jsonSerializer">The json serializer.</param>
  124. /// <param name="logger">The logger.</param>
  125. /// <param name="appHost">The app host.</param>
  126. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  127. public InstallationManager(Kernel kernel, IHttpClient httpClient, IZipClient zipClient, INetworkManager networkManager, IPackageManager packageManager, IJsonSerializer jsonSerializer, ILogger logger, IApplicationHost appHost)
  128. : base(kernel)
  129. {
  130. if (zipClient == null)
  131. {
  132. throw new ArgumentNullException("zipClient");
  133. }
  134. if (networkManager == null)
  135. {
  136. throw new ArgumentNullException("networkManager");
  137. }
  138. if (packageManager == null)
  139. {
  140. throw new ArgumentNullException("packageManager");
  141. }
  142. if (logger == null)
  143. {
  144. throw new ArgumentNullException("logger");
  145. }
  146. if (jsonSerializer == null)
  147. {
  148. throw new ArgumentNullException("jsonSerializer");
  149. }
  150. if (httpClient == null)
  151. {
  152. throw new ArgumentNullException("httpClient");
  153. }
  154. CurrentInstallations = new List<Tuple<InstallationInfo, CancellationTokenSource>>();
  155. CompletedInstallations = new ConcurrentBag<InstallationInfo>();
  156. JsonSerializer = jsonSerializer;
  157. HttpClient = httpClient;
  158. ApplicationHost = appHost;
  159. _networkManager = networkManager;
  160. _packageManager = packageManager;
  161. _logger = logger;
  162. ZipClient = zipClient;
  163. }
  164. /// <summary>
  165. /// Gets all available packages.
  166. /// </summary>
  167. /// <param name="cancellationToken">The cancellation token.</param>
  168. /// <param name="packageType">Type of the package.</param>
  169. /// <param name="applicationVersion">The application version.</param>
  170. /// <returns>Task{List{PackageInfo}}.</returns>
  171. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  172. PackageType? packageType = null,
  173. Version applicationVersion = null)
  174. {
  175. var packages = (await _packageManager.GetAvailablePackages(HttpClient, _networkManager, Kernel.SecurityManager, Kernel.ResourcePools, JsonSerializer, cancellationToken).ConfigureAwait(false)).ToList();
  176. if (packageType.HasValue)
  177. {
  178. packages = packages.Where(p => p.type == packageType.Value).ToList();
  179. }
  180. // If an app version was supplied, filter the versions for each package to only include supported versions
  181. if (applicationVersion != null)
  182. {
  183. foreach (var package in packages)
  184. {
  185. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  186. }
  187. }
  188. // Remove packages with no versions
  189. packages = packages.Where(p => p.versions.Any()).ToList();
  190. return packages;
  191. }
  192. /// <summary>
  193. /// Determines whether [is package version up to date] [the specified package version info].
  194. /// </summary>
  195. /// <param name="packageVersionInfo">The package version info.</param>
  196. /// <param name="applicationVersion">The application version.</param>
  197. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  198. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version applicationVersion)
  199. {
  200. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  201. {
  202. return true;
  203. }
  204. Version requiredVersion;
  205. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && applicationVersion >= requiredVersion;
  206. }
  207. /// <summary>
  208. /// Gets the package.
  209. /// </summary>
  210. /// <param name="name">The name.</param>
  211. /// <param name="classification">The classification.</param>
  212. /// <param name="version">The version.</param>
  213. /// <returns>Task{PackageVersionInfo}.</returns>
  214. public async Task<PackageVersionInfo> GetPackage(string name, PackageVersionClass classification, Version version)
  215. {
  216. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  217. var package = packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  218. if (package == null)
  219. {
  220. return null;
  221. }
  222. return package.versions.FirstOrDefault(v => v.version.Equals(version) && v.classification == classification);
  223. }
  224. /// <summary>
  225. /// Gets the latest compatible version.
  226. /// </summary>
  227. /// <param name="name">The name.</param>
  228. /// <param name="classification">The classification.</param>
  229. /// <returns>Task{PackageVersionInfo}.</returns>
  230. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, PackageVersionClass classification = PackageVersionClass.Release)
  231. {
  232. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  233. return GetLatestCompatibleVersion(packages, name, classification);
  234. }
  235. /// <summary>
  236. /// Gets the latest compatible version.
  237. /// </summary>
  238. /// <param name="availablePackages">The available packages.</param>
  239. /// <param name="name">The name.</param>
  240. /// <param name="classification">The classification.</param>
  241. /// <returns>PackageVersionInfo.</returns>
  242. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, PackageVersionClass classification = PackageVersionClass.Release)
  243. {
  244. var package = availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  245. if (package == null)
  246. {
  247. return null;
  248. }
  249. return package.versions
  250. .OrderByDescending(v => v.version)
  251. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, ApplicationHost.ApplicationVersion));
  252. }
  253. /// <summary>
  254. /// Gets the available plugin updates.
  255. /// </summary>
  256. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  257. /// <param name="cancellationToken">The cancellation token.</param>
  258. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  259. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  260. {
  261. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  262. var plugins = Kernel.Plugins;
  263. if (withAutoUpdateEnabled)
  264. {
  265. plugins = plugins.Where(p => p.Configuration.EnableAutoUpdate);
  266. }
  267. // Figure out what needs to be installed
  268. return plugins.Select(p =>
  269. {
  270. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Configuration.UpdateClass);
  271. return latestPluginInfo != null && latestPluginInfo.version > p.Version ? latestPluginInfo : null;
  272. }).Where(p => !CompletedInstallations.Any(i => i.Name.Equals(p.name, StringComparison.OrdinalIgnoreCase)))
  273. .Where(p => p != null && !string.IsNullOrWhiteSpace(p.sourceUrl));
  274. }
  275. /// <summary>
  276. /// Installs the package.
  277. /// </summary>
  278. /// <param name="package">The package.</param>
  279. /// <param name="progress">The progress.</param>
  280. /// <param name="cancellationToken">The cancellation token.</param>
  281. /// <returns>Task.</returns>
  282. /// <exception cref="System.ArgumentNullException">package</exception>
  283. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  284. {
  285. if (package == null)
  286. {
  287. throw new ArgumentNullException("package");
  288. }
  289. if (progress == null)
  290. {
  291. throw new ArgumentNullException("progress");
  292. }
  293. if (cancellationToken == null)
  294. {
  295. throw new ArgumentNullException("cancellationToken");
  296. }
  297. var installationInfo = new InstallationInfo
  298. {
  299. Id = Guid.NewGuid(),
  300. Name = package.name,
  301. UpdateClass = package.classification,
  302. Version = package.versionStr
  303. };
  304. var innerCancellationTokenSource = new CancellationTokenSource();
  305. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  306. // Add it to the in-progress list
  307. lock (CurrentInstallations)
  308. {
  309. CurrentInstallations.Add(tuple);
  310. }
  311. var innerProgress = new ActionableProgress<double> { };
  312. // Whenever the progress updates, update the outer progress object and InstallationInfo
  313. innerProgress.RegisterAction(percent =>
  314. {
  315. progress.Report(percent);
  316. installationInfo.PercentComplete = percent;
  317. });
  318. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  319. Kernel.ServerManager.SendWebSocketMessage("PackageInstalling", installationInfo);
  320. try
  321. {
  322. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  323. lock (CurrentInstallations)
  324. {
  325. CurrentInstallations.Remove(tuple);
  326. }
  327. CompletedInstallations.Add(installationInfo);
  328. Kernel.ServerManager.SendWebSocketMessage("PackageInstallationCompleted", installationInfo);
  329. }
  330. catch (OperationCanceledException)
  331. {
  332. lock (CurrentInstallations)
  333. {
  334. CurrentInstallations.Remove(tuple);
  335. }
  336. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  337. Kernel.ServerManager.SendWebSocketMessage("PackageInstallationCancelled", installationInfo);
  338. throw;
  339. }
  340. catch
  341. {
  342. lock (CurrentInstallations)
  343. {
  344. CurrentInstallations.Remove(tuple);
  345. }
  346. Kernel.ServerManager.SendWebSocketMessage("PackageInstallationFailed", installationInfo);
  347. throw;
  348. }
  349. finally
  350. {
  351. // Dispose the progress object and remove the installation from the in-progress list
  352. innerProgress.Dispose();
  353. tuple.Item2.Dispose();
  354. }
  355. }
  356. /// <summary>
  357. /// Installs the package internal.
  358. /// </summary>
  359. /// <param name="package">The package.</param>
  360. /// <param name="progress">The progress.</param>
  361. /// <param name="cancellationToken">The cancellation token.</param>
  362. /// <returns>Task.</returns>
  363. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  364. {
  365. // Target based on if it is an archive or single assembly
  366. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  367. var isArchive = string.Equals(Path.GetExtension(package.sourceUrl), ".zip", StringComparison.OrdinalIgnoreCase);
  368. var target = isArchive ? Kernel.ApplicationPaths.ProgramDataPath : Path.Combine(Kernel.ApplicationPaths.PluginsPath, package.targetFilename);
  369. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  370. var tempFile = await HttpClient.GetTempFile(package.sourceUrl, Kernel.ResourcePools.Mb, cancellationToken, progress).ConfigureAwait(false);
  371. cancellationToken.ThrowIfCancellationRequested();
  372. // Validate with a checksum
  373. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  374. {
  375. using (var crypto = new MD5CryptoServiceProvider())
  376. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  377. {
  378. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  379. if (check != package.checksum)
  380. {
  381. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  382. }
  383. }
  384. }
  385. cancellationToken.ThrowIfCancellationRequested();
  386. // Success - move it to the real target based on type
  387. if (isArchive)
  388. {
  389. try
  390. {
  391. ZipClient.ExtractAll(tempFile, target, true);
  392. }
  393. catch (IOException e)
  394. {
  395. _logger.ErrorException("Error attempting to extract archive from {0} to {1}", e, tempFile, target);
  396. throw;
  397. }
  398. }
  399. else
  400. {
  401. try
  402. {
  403. File.Copy(tempFile, target, true);
  404. File.Delete(tempFile);
  405. }
  406. catch (IOException e)
  407. {
  408. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  409. throw;
  410. }
  411. }
  412. // Set last update time if we were installed before
  413. var plugin = Kernel.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  414. if (plugin != null)
  415. {
  416. // Synchronize the UpdateClass value
  417. if (plugin.Configuration.UpdateClass != package.classification)
  418. {
  419. plugin.Configuration.UpdateClass = package.classification;
  420. plugin.SaveConfiguration();
  421. }
  422. OnPluginUpdated(plugin, package);
  423. }
  424. else
  425. {
  426. OnPluginInstalled(package);
  427. }
  428. }
  429. /// <summary>
  430. /// Uninstalls a plugin
  431. /// </summary>
  432. /// <param name="plugin">The plugin.</param>
  433. /// <exception cref="System.ArgumentException"></exception>
  434. public void UninstallPlugin(IPlugin plugin)
  435. {
  436. if (plugin.IsCorePlugin)
  437. {
  438. throw new ArgumentException(string.Format("{0} cannot be uninstalled because it is a core plugin.", plugin.Name));
  439. }
  440. plugin.OnUninstalling();
  441. // Remove it the quick way for now
  442. Kernel.RemovePlugin(plugin);
  443. File.Delete(plugin.AssemblyFilePath);
  444. OnPluginUninstalled(plugin);
  445. Kernel.NotifyPendingRestart();
  446. }
  447. /// <summary>
  448. /// Releases unmanaged and - optionally - managed resources.
  449. /// </summary>
  450. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  451. protected override void Dispose(bool dispose)
  452. {
  453. if (dispose)
  454. {
  455. lock (CurrentInstallations)
  456. {
  457. foreach (var tuple in CurrentInstallations)
  458. {
  459. tuple.Item2.Dispose();
  460. }
  461. CurrentInstallations.Clear();
  462. }
  463. }
  464. base.Dispose(dispose);
  465. }
  466. }
  467. }