2
0

InstallationManager.cs 21 KB

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