InstallationManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. using System.Security.Cryptography;
  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.Serialization;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Logging;
  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. /// <summary>
  26. /// The current installations
  27. /// </summary>
  28. public readonly List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations =
  29. new List<Tuple<InstallationInfo, CancellationTokenSource>>();
  30. /// <summary>
  31. /// The completed installations
  32. /// </summary>
  33. public readonly ConcurrentBag<InstallationInfo> CompletedInstallations = new ConcurrentBag<InstallationInfo>();
  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.TcpManager.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. /// Initializes a new instance of the <see cref="InstallationManager" /> class.
  94. /// </summary>
  95. /// <param name="kernel">The kernel.</param>
  96. /// <param name="zipClient">The zip client.</param>
  97. /// <param name="logger">The logger.</param>
  98. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  99. public InstallationManager(Kernel kernel, IZipClient zipClient, ILogger logger)
  100. : base(kernel)
  101. {
  102. if (zipClient == null)
  103. {
  104. throw new ArgumentNullException("zipClient");
  105. }
  106. _logger = logger;
  107. ZipClient = zipClient;
  108. }
  109. /// <summary>
  110. /// Gets all available packages.
  111. /// </summary>
  112. /// <param name="cancellationToken">The cancellation token.</param>
  113. /// <param name="packageType">Type of the package.</param>
  114. /// <param name="applicationVersion">The application version.</param>
  115. /// <returns>Task{List{PackageInfo}}.</returns>
  116. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  117. PackageType? packageType = null,
  118. Version applicationVersion = null)
  119. {
  120. var data = new Dictionary<string, string> { { "key", Kernel.PluginSecurityManager.SupporterKey }, { "mac", NetUtils.GetMacAddress() } };
  121. using (var json = await Kernel.HttpManager.Post(Controller.Kernel.MBAdminUrl + "service/package/retrieveall", data, Kernel.ResourcePools.Mb, cancellationToken).ConfigureAwait(false))
  122. {
  123. cancellationToken.ThrowIfCancellationRequested();
  124. var packages = JsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  125. foreach (var package in packages)
  126. {
  127. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  128. .OrderByDescending(v => v.version).ToList();
  129. }
  130. if (packageType.HasValue)
  131. {
  132. packages = packages.Where(p => p.type == packageType.Value).ToList();
  133. }
  134. // If an app version was supplied, filter the versions for each package to only include supported versions
  135. if (applicationVersion != null)
  136. {
  137. foreach (var package in packages)
  138. {
  139. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  140. }
  141. }
  142. // Remove packages with no versions
  143. packages = packages.Where(p => p.versions.Any()).ToList();
  144. return packages;
  145. }
  146. }
  147. /// <summary>
  148. /// Determines whether [is package version up to date] [the specified package version info].
  149. /// </summary>
  150. /// <param name="packageVersionInfo">The package version info.</param>
  151. /// <param name="applicationVersion">The application version.</param>
  152. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  153. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version applicationVersion)
  154. {
  155. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  156. {
  157. return true;
  158. }
  159. Version requiredVersion;
  160. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && applicationVersion >= requiredVersion;
  161. }
  162. /// <summary>
  163. /// Gets the package.
  164. /// </summary>
  165. /// <param name="name">The name.</param>
  166. /// <param name="classification">The classification.</param>
  167. /// <param name="version">The version.</param>
  168. /// <returns>Task{PackageVersionInfo}.</returns>
  169. public async Task<PackageVersionInfo> GetPackage(string name, PackageVersionClass classification, Version version)
  170. {
  171. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  172. var package = packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  173. if (package == null)
  174. {
  175. return null;
  176. }
  177. return package.versions.FirstOrDefault(v => v.version.Equals(version) && v.classification == classification);
  178. }
  179. /// <summary>
  180. /// Gets the latest compatible version.
  181. /// </summary>
  182. /// <param name="name">The name.</param>
  183. /// <param name="classification">The classification.</param>
  184. /// <returns>Task{PackageVersionInfo}.</returns>
  185. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, PackageVersionClass classification = PackageVersionClass.Release)
  186. {
  187. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  188. return GetLatestCompatibleVersion(packages, name, classification);
  189. }
  190. /// <summary>
  191. /// Gets the latest compatible version.
  192. /// </summary>
  193. /// <param name="availablePackages">The available packages.</param>
  194. /// <param name="name">The name.</param>
  195. /// <param name="classification">The classification.</param>
  196. /// <returns>PackageVersionInfo.</returns>
  197. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, PackageVersionClass classification = PackageVersionClass.Release)
  198. {
  199. var package = availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  200. if (package == null)
  201. {
  202. return null;
  203. }
  204. return package.versions
  205. .OrderByDescending(v => v.version)
  206. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, Kernel.ApplicationVersion));
  207. }
  208. /// <summary>
  209. /// Gets the available plugin updates.
  210. /// </summary>
  211. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  212. /// <param name="cancellationToken">The cancellation token.</param>
  213. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  214. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  215. {
  216. var catalog = await Kernel.InstallationManager.GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  217. var plugins = Kernel.Plugins;
  218. if (withAutoUpdateEnabled)
  219. {
  220. plugins = plugins.Where(p => p.Configuration.EnableAutoUpdate);
  221. }
  222. // Figure out what needs to be installed
  223. return plugins.Select(p =>
  224. {
  225. var latestPluginInfo = Kernel.InstallationManager.GetLatestCompatibleVersion(catalog, p.Name, p.Configuration.UpdateClass);
  226. return latestPluginInfo != null && latestPluginInfo.version > p.Version ? latestPluginInfo : null;
  227. }).Where(p => !CompletedInstallations.Any(i => i.Name.Equals(p.name, StringComparison.OrdinalIgnoreCase)))
  228. .Where(p => p != null && !string.IsNullOrWhiteSpace(p.sourceUrl));
  229. }
  230. /// <summary>
  231. /// Installs the package.
  232. /// </summary>
  233. /// <param name="package">The package.</param>
  234. /// <param name="progress">The progress.</param>
  235. /// <param name="cancellationToken">The cancellation token.</param>
  236. /// <returns>Task.</returns>
  237. /// <exception cref="System.ArgumentNullException">package</exception>
  238. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  239. {
  240. if (package == null)
  241. {
  242. throw new ArgumentNullException("package");
  243. }
  244. if (progress == null)
  245. {
  246. throw new ArgumentNullException("progress");
  247. }
  248. if (cancellationToken == null)
  249. {
  250. throw new ArgumentNullException("cancellationToken");
  251. }
  252. var installationInfo = new InstallationInfo
  253. {
  254. Id = Guid.NewGuid(),
  255. Name = package.name,
  256. UpdateClass = package.classification,
  257. Version = package.versionStr
  258. };
  259. var innerCancellationTokenSource = new CancellationTokenSource();
  260. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  261. // Add it to the in-progress list
  262. lock (CurrentInstallations)
  263. {
  264. CurrentInstallations.Add(tuple);
  265. }
  266. var innerProgress = new ActionableProgress<double> { };
  267. // Whenever the progress updates, update the outer progress object and InstallationInfo
  268. innerProgress.RegisterAction(percent =>
  269. {
  270. progress.Report(percent);
  271. installationInfo.PercentComplete = percent;
  272. });
  273. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  274. Kernel.TcpManager.SendWebSocketMessage("PackageInstalling", installationInfo);
  275. try
  276. {
  277. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  278. lock (CurrentInstallations)
  279. {
  280. CurrentInstallations.Remove(tuple);
  281. }
  282. CompletedInstallations.Add(installationInfo);
  283. Kernel.TcpManager.SendWebSocketMessage("PackageInstallationCompleted", installationInfo);
  284. }
  285. catch (OperationCanceledException)
  286. {
  287. lock (CurrentInstallations)
  288. {
  289. CurrentInstallations.Remove(tuple);
  290. }
  291. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  292. Kernel.TcpManager.SendWebSocketMessage("PackageInstallationCancelled", installationInfo);
  293. throw;
  294. }
  295. catch
  296. {
  297. lock (CurrentInstallations)
  298. {
  299. CurrentInstallations.Remove(tuple);
  300. }
  301. Kernel.TcpManager.SendWebSocketMessage("PackageInstallationFailed", installationInfo);
  302. throw;
  303. }
  304. finally
  305. {
  306. // Dispose the progress object and remove the installation from the in-progress list
  307. innerProgress.Dispose();
  308. tuple.Item2.Dispose();
  309. }
  310. }
  311. /// <summary>
  312. /// Installs the package internal.
  313. /// </summary>
  314. /// <param name="package">The package.</param>
  315. /// <param name="progress">The progress.</param>
  316. /// <param name="cancellationToken">The cancellation token.</param>
  317. /// <returns>Task.</returns>
  318. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  319. {
  320. // Target based on if it is an archive or single assembly
  321. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  322. var isArchive = string.Equals(Path.GetExtension(package.sourceUrl), ".zip", StringComparison.OrdinalIgnoreCase);
  323. var target = isArchive ? Kernel.ApplicationPaths.ProgramDataPath : Path.Combine(Kernel.ApplicationPaths.PluginsPath, package.targetFilename);
  324. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  325. var tempFile = await Kernel.HttpManager.FetchToTempFile(package.sourceUrl, Kernel.ResourcePools.Mb, cancellationToken, progress).ConfigureAwait(false);
  326. cancellationToken.ThrowIfCancellationRequested();
  327. // Validate with a checksum
  328. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  329. {
  330. using (var crypto = new MD5CryptoServiceProvider())
  331. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  332. {
  333. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  334. if (check != package.checksum)
  335. {
  336. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  337. }
  338. }
  339. }
  340. cancellationToken.ThrowIfCancellationRequested();
  341. // Success - move it to the real target based on type
  342. if (isArchive)
  343. {
  344. try
  345. {
  346. ZipClient.ExtractAll(tempFile, target, true);
  347. }
  348. catch (IOException e)
  349. {
  350. _logger.ErrorException("Error attempting to extract archive from {0} to {1}", e, tempFile, target);
  351. throw;
  352. }
  353. }
  354. else
  355. {
  356. try
  357. {
  358. File.Copy(tempFile, target, true);
  359. File.Delete(tempFile);
  360. }
  361. catch (IOException e)
  362. {
  363. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  364. throw;
  365. }
  366. }
  367. // Set last update time if we were installed before
  368. var plugin = Kernel.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  369. if (plugin != null)
  370. {
  371. // Synchronize the UpdateClass value
  372. if (plugin.Configuration.UpdateClass != package.classification)
  373. {
  374. plugin.Configuration.UpdateClass = package.classification;
  375. plugin.SaveConfiguration();
  376. }
  377. OnPluginUpdated(plugin, package);
  378. }
  379. else
  380. {
  381. OnPluginInstalled(package);
  382. }
  383. }
  384. /// <summary>
  385. /// Uninstalls a plugin
  386. /// </summary>
  387. /// <param name="plugin">The plugin.</param>
  388. /// <exception cref="System.ArgumentException"></exception>
  389. public void UninstallPlugin(IPlugin plugin)
  390. {
  391. if (plugin.IsCorePlugin)
  392. {
  393. throw new ArgumentException(string.Format("{0} cannot be uninstalled because it is a core plugin.", plugin.Name));
  394. }
  395. plugin.OnUninstalling();
  396. // Remove it the quick way for now
  397. Kernel.RemovePlugin(plugin);
  398. File.Delete(plugin.AssemblyFilePath);
  399. OnPluginUninstalled(plugin);
  400. Kernel.NotifyPendingRestart();
  401. }
  402. /// <summary>
  403. /// Releases unmanaged and - optionally - managed resources.
  404. /// </summary>
  405. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  406. protected override void Dispose(bool dispose)
  407. {
  408. if (dispose)
  409. {
  410. lock (CurrentInstallations)
  411. {
  412. foreach (var tuple in CurrentInstallations)
  413. {
  414. tuple.Item2.Dispose();
  415. }
  416. CurrentInstallations.Clear();
  417. }
  418. }
  419. base.Dispose(dispose);
  420. }
  421. }
  422. }