InstallationManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Common.Plugins;
  4. using MediaBrowser.Common.Progress;
  5. using MediaBrowser.Model.IO;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using MediaBrowser.Model.Updates;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Security.Cryptography;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Controller.Updates
  18. {
  19. /// <summary>
  20. /// Manages all install, uninstall and update operations (both plugins and system)
  21. /// </summary>
  22. public class InstallationManager : BaseManager<Kernel>
  23. {
  24. /// <summary>
  25. /// The current installations
  26. /// </summary>
  27. public readonly List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations =
  28. new List<Tuple<InstallationInfo, CancellationTokenSource>>();
  29. /// <summary>
  30. /// The completed installations
  31. /// </summary>
  32. public readonly ConcurrentBag<InstallationInfo> CompletedInstallations = new ConcurrentBag<InstallationInfo>();
  33. #region PluginUninstalled Event
  34. /// <summary>
  35. /// Occurs when [plugin uninstalled].
  36. /// </summary>
  37. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  38. /// <summary>
  39. /// Called when [plugin uninstalled].
  40. /// </summary>
  41. /// <param name="plugin">The plugin.</param>
  42. private void OnPluginUninstalled(IPlugin plugin)
  43. {
  44. EventHelper.QueueEventIfNotNull(PluginUninstalled, this, new GenericEventArgs<IPlugin> { Argument = plugin }, _logger);
  45. // Notify connected ui's
  46. Kernel.TcpManager.SendWebSocketMessage("PluginUninstalled", plugin.GetPluginInfo());
  47. }
  48. #endregion
  49. #region PluginUpdated Event
  50. /// <summary>
  51. /// Occurs when [plugin updated].
  52. /// </summary>
  53. public event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
  54. /// <summary>
  55. /// Called when [plugin updated].
  56. /// </summary>
  57. /// <param name="plugin">The plugin.</param>
  58. /// <param name="newVersion">The new version.</param>
  59. public void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
  60. {
  61. _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.version, newVersion.classification);
  62. EventHelper.QueueEventIfNotNull(PluginUpdated, this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) }, _logger);
  63. Kernel.NotifyPendingRestart();
  64. }
  65. #endregion
  66. #region PluginInstalled Event
  67. /// <summary>
  68. /// Occurs when [plugin updated].
  69. /// </summary>
  70. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  71. /// <summary>
  72. /// Called when [plugin installed].
  73. /// </summary>
  74. /// <param name="package">The package.</param>
  75. public void OnPluginInstalled(PackageVersionInfo package)
  76. {
  77. _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.version, package.classification);
  78. EventHelper.QueueEventIfNotNull(PluginInstalled, this, new GenericEventArgs<PackageVersionInfo> { Argument = package }, _logger);
  79. Kernel.NotifyPendingRestart();
  80. }
  81. #endregion
  82. /// <summary>
  83. /// Gets or sets the zip client.
  84. /// </summary>
  85. /// <value>The zip client.</value>
  86. private IZipClient ZipClient { get; set; }
  87. /// <summary>
  88. /// The _logger
  89. /// </summary>
  90. private readonly ILogger _logger;
  91. /// <summary>
  92. /// The _network manager
  93. /// </summary>
  94. private readonly INetworkManager _networkManager;
  95. /// <summary>
  96. /// Gets the json serializer.
  97. /// </summary>
  98. /// <value>The json serializer.</value>
  99. protected IJsonSerializer JsonSerializer { get; private set; }
  100. /// <summary>
  101. /// Gets the HTTP client.
  102. /// </summary>
  103. /// <value>The HTTP client.</value>
  104. protected IHttpClient HttpClient { get; private set; }
  105. /// <summary>
  106. /// Initializes a new instance of the <see cref="InstallationManager" /> class.
  107. /// </summary>
  108. /// <param name="kernel">The kernel.</param>
  109. /// <param name="httpClient">The HTTP client.</param>
  110. /// <param name="zipClient">The zip client.</param>
  111. /// <param name="networkManager">The network manager.</param>
  112. /// <param name="jsonSerializer">The json serializer.</param>
  113. /// <param name="logger">The logger.</param>
  114. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  115. public InstallationManager(Kernel kernel, IHttpClient httpClient, IZipClient zipClient, INetworkManager networkManager, IJsonSerializer jsonSerializer, ILogger logger)
  116. : base(kernel)
  117. {
  118. if (zipClient == null)
  119. {
  120. throw new ArgumentNullException("zipClient");
  121. }
  122. if (networkManager == null)
  123. {
  124. throw new ArgumentNullException("networkManager");
  125. }
  126. if (logger == null)
  127. {
  128. throw new ArgumentNullException("logger");
  129. }
  130. if (jsonSerializer == null)
  131. {
  132. throw new ArgumentNullException("jsonSerializer");
  133. }
  134. if (httpClient == null)
  135. {
  136. throw new ArgumentNullException("httpClient");
  137. }
  138. JsonSerializer = jsonSerializer;
  139. HttpClient = httpClient;
  140. _networkManager = networkManager;
  141. _logger = logger;
  142. ZipClient = zipClient;
  143. }
  144. /// <summary>
  145. /// Gets all available packages.
  146. /// </summary>
  147. /// <param name="cancellationToken">The cancellation token.</param>
  148. /// <param name="packageType">Type of the package.</param>
  149. /// <param name="applicationVersion">The application version.</param>
  150. /// <returns>Task{List{PackageInfo}}.</returns>
  151. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  152. PackageType? packageType = null,
  153. Version applicationVersion = null)
  154. {
  155. var data = new Dictionary<string, string> { { "key", Kernel.PluginSecurityManager.SupporterKey }, { "mac", _networkManager.GetMacAddress() } };
  156. using (var json = await HttpClient.Post(Controller.Kernel.MBAdminUrl + "service/package/retrieveall", data, Kernel.ResourcePools.Mb, cancellationToken).ConfigureAwait(false))
  157. {
  158. cancellationToken.ThrowIfCancellationRequested();
  159. var packages = JsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  160. foreach (var package in packages)
  161. {
  162. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  163. .OrderByDescending(v => v.version).ToList();
  164. }
  165. if (packageType.HasValue)
  166. {
  167. packages = packages.Where(p => p.type == packageType.Value).ToList();
  168. }
  169. // If an app version was supplied, filter the versions for each package to only include supported versions
  170. if (applicationVersion != null)
  171. {
  172. foreach (var package in packages)
  173. {
  174. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  175. }
  176. }
  177. // Remove packages with no versions
  178. packages = packages.Where(p => p.versions.Any()).ToList();
  179. return packages;
  180. }
  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, Kernel.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. Kernel.TcpManager.SendWebSocketMessage("PackageInstalling", installationInfo);
  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. Kernel.TcpManager.SendWebSocketMessage("PackageInstallationCompleted", installationInfo);
  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. Kernel.TcpManager.SendWebSocketMessage("PackageInstallationCancelled", installationInfo);
  328. throw;
  329. }
  330. catch
  331. {
  332. lock (CurrentInstallations)
  333. {
  334. CurrentInstallations.Remove(tuple);
  335. }
  336. Kernel.TcpManager.SendWebSocketMessage("PackageInstallationFailed", installationInfo);
  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. // Target based on if it is an archive or single assembly
  356. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  357. var isArchive = string.Equals(Path.GetExtension(package.sourceUrl), ".zip", StringComparison.OrdinalIgnoreCase);
  358. var target = isArchive ? Kernel.ApplicationPaths.ProgramDataPath : Path.Combine(Kernel.ApplicationPaths.PluginsPath, package.targetFilename);
  359. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  360. var tempFile = await HttpClient.GetTempFile(package.sourceUrl, Kernel.ResourcePools.Mb, cancellationToken, progress).ConfigureAwait(false);
  361. cancellationToken.ThrowIfCancellationRequested();
  362. // Validate with a checksum
  363. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  364. {
  365. using (var crypto = new MD5CryptoServiceProvider())
  366. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  367. {
  368. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  369. if (check != package.checksum)
  370. {
  371. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  372. }
  373. }
  374. }
  375. cancellationToken.ThrowIfCancellationRequested();
  376. // Success - move it to the real target based on type
  377. if (isArchive)
  378. {
  379. try
  380. {
  381. ZipClient.ExtractAll(tempFile, target, true);
  382. }
  383. catch (IOException e)
  384. {
  385. _logger.ErrorException("Error attempting to extract archive from {0} to {1}", e, tempFile, target);
  386. throw;
  387. }
  388. }
  389. else
  390. {
  391. try
  392. {
  393. File.Copy(tempFile, target, true);
  394. File.Delete(tempFile);
  395. }
  396. catch (IOException e)
  397. {
  398. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  399. throw;
  400. }
  401. }
  402. // Set last update time if we were installed before
  403. var plugin = Kernel.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  404. if (plugin != null)
  405. {
  406. // Synchronize the UpdateClass value
  407. if (plugin.Configuration.UpdateClass != package.classification)
  408. {
  409. plugin.Configuration.UpdateClass = package.classification;
  410. plugin.SaveConfiguration();
  411. }
  412. OnPluginUpdated(plugin, package);
  413. }
  414. else
  415. {
  416. OnPluginInstalled(package);
  417. }
  418. }
  419. /// <summary>
  420. /// Uninstalls a plugin
  421. /// </summary>
  422. /// <param name="plugin">The plugin.</param>
  423. /// <exception cref="System.ArgumentException"></exception>
  424. public void UninstallPlugin(IPlugin plugin)
  425. {
  426. if (plugin.IsCorePlugin)
  427. {
  428. throw new ArgumentException(string.Format("{0} cannot be uninstalled because it is a core plugin.", plugin.Name));
  429. }
  430. plugin.OnUninstalling();
  431. // Remove it the quick way for now
  432. Kernel.RemovePlugin(plugin);
  433. File.Delete(plugin.AssemblyFilePath);
  434. OnPluginUninstalled(plugin);
  435. Kernel.NotifyPendingRestart();
  436. }
  437. /// <summary>
  438. /// Releases unmanaged and - optionally - managed resources.
  439. /// </summary>
  440. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  441. protected override void Dispose(bool dispose)
  442. {
  443. if (dispose)
  444. {
  445. lock (CurrentInstallations)
  446. {
  447. foreach (var tuple in CurrentInstallations)
  448. {
  449. tuple.Item2.Dispose();
  450. }
  451. CurrentInstallations.Clear();
  452. }
  453. }
  454. base.Dispose(dispose);
  455. }
  456. }
  457. }