InstallationManager.cs 20 KB

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