InstallationManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #nullable disable
  2. #nullable enable
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net.Http;
  9. using System.Net.Http.Json;
  10. using System.Security.Cryptography;
  11. using System.Text.Json;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using Jellyfin.Data.Events;
  15. using MediaBrowser.Common.Configuration;
  16. using MediaBrowser.Common.Json;
  17. using MediaBrowser.Common.Net;
  18. using MediaBrowser.Common.Plugins;
  19. using MediaBrowser.Common.Updates;
  20. using MediaBrowser.Controller;
  21. using MediaBrowser.Controller.Configuration;
  22. using MediaBrowser.Controller.Events;
  23. using MediaBrowser.Controller.Events.Updates;
  24. using MediaBrowser.Model.IO;
  25. using MediaBrowser.Model.Plugins;
  26. using MediaBrowser.Model.Updates;
  27. using Microsoft.Extensions.Logging;
  28. namespace Emby.Server.Implementations.Updates
  29. {
  30. /// <summary>
  31. /// Manages all install, uninstall, and update operations for the system and individual plugins.
  32. /// </summary>
  33. public class InstallationManager : IInstallationManager
  34. {
  35. /// <summary>
  36. /// The logger.
  37. /// </summary>
  38. private readonly ILogger<InstallationManager> _logger;
  39. private readonly IApplicationPaths _appPaths;
  40. private readonly IEventManager _eventManager;
  41. private readonly IHttpClientFactory _httpClientFactory;
  42. private readonly IServerConfigurationManager _config;
  43. private readonly JsonSerializerOptions _jsonSerializerOptions;
  44. private readonly IPluginManager _pluginManager;
  45. /// <summary>
  46. /// Gets the application host.
  47. /// </summary>
  48. /// <value>The application host.</value>
  49. private readonly IServerApplicationHost _applicationHost;
  50. private readonly IZipClient _zipClient;
  51. private readonly object _currentInstallationsLock = new object();
  52. /// <summary>
  53. /// The current installations.
  54. /// </summary>
  55. private readonly List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations;
  56. /// <summary>
  57. /// The completed installations.
  58. /// </summary>
  59. private readonly ConcurrentBag<InstallationInfo> _completedInstallationsInternal;
  60. /// <summary>
  61. /// Initializes a new instance of the <see cref="InstallationManager"/> class.
  62. /// </summary>
  63. /// <param name="logger">The <see cref="ILogger{InstallationManager}"/>.</param>
  64. /// <param name="appHost">The <see cref="IServerApplicationHost"/>.</param>
  65. /// <param name="appPaths">The <see cref="IApplicationPaths"/>.</param>
  66. /// <param name="eventManager">The <see cref="IEventManager"/>.</param>
  67. /// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/>.</param>
  68. /// <param name="config">The <see cref="IServerConfigurationManager"/>.</param>
  69. /// <param name="zipClient">The <see cref="IZipClient"/>.</param>
  70. /// <param name="pluginManager">The <see cref="IPluginManager"/>.</param>
  71. public InstallationManager(
  72. ILogger<InstallationManager> logger,
  73. IServerApplicationHost appHost,
  74. IApplicationPaths appPaths,
  75. IEventManager eventManager,
  76. IHttpClientFactory httpClientFactory,
  77. IServerConfigurationManager config,
  78. IZipClient zipClient,
  79. IPluginManager pluginManager)
  80. {
  81. _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>();
  82. _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
  83. _logger = logger;
  84. _applicationHost = appHost;
  85. _appPaths = appPaths;
  86. _eventManager = eventManager;
  87. _httpClientFactory = httpClientFactory;
  88. _config = config;
  89. _zipClient = zipClient;
  90. _jsonSerializerOptions = JsonDefaults.Options;
  91. _pluginManager = pluginManager;
  92. }
  93. /// <inheritdoc />
  94. public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
  95. /// <inheritdoc />
  96. public async Task<PackageInfo[]> GetPackages(string manifestName, string manifest, bool filterIncompatible, CancellationToken cancellationToken = default)
  97. {
  98. try
  99. {
  100. PackageInfo[]? packages = await _httpClientFactory.CreateClient(NamedClient.Default)
  101. .GetFromJsonAsync<PackageInfo[]>(new Uri(manifest), _jsonSerializerOptions, cancellationToken).ConfigureAwait(false);
  102. if (packages == null)
  103. {
  104. return Array.Empty<PackageInfo>();
  105. }
  106. var minimumVersion = new Version(0, 0, 0, 1);
  107. // Store the repository and repository url with each version, as they may be spread apart.
  108. foreach (var entry in packages)
  109. {
  110. for (int a = entry.Versions.Count - 1; a >= 0; a--)
  111. {
  112. var ver = entry.Versions[a];
  113. ver.RepositoryName = manifestName;
  114. ver.RepositoryUrl = manifest;
  115. if (!filterIncompatible)
  116. {
  117. continue;
  118. }
  119. if (!Version.TryParse(ver.TargetAbi, out var targetAbi))
  120. {
  121. targetAbi = minimumVersion;
  122. }
  123. // Only show plugins that are greater than or equal to targetAbi.
  124. if (_applicationHost.ApplicationVersion >= targetAbi)
  125. {
  126. continue;
  127. }
  128. // Not compatible with this version so remove it.
  129. entry.Versions.Remove(ver);
  130. }
  131. }
  132. return packages;
  133. }
  134. catch (IOException ex)
  135. {
  136. _logger.LogError(ex, "Cannot locate the plugin manifest {Manifest}", manifest);
  137. return Array.Empty<PackageInfo>();
  138. }
  139. catch (JsonException ex)
  140. {
  141. _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
  142. return Array.Empty<PackageInfo>();
  143. }
  144. catch (UriFormatException ex)
  145. {
  146. _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
  147. return Array.Empty<PackageInfo>();
  148. }
  149. catch (HttpRequestException ex)
  150. {
  151. _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
  152. return Array.Empty<PackageInfo>();
  153. }
  154. }
  155. /// <inheritdoc />
  156. public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
  157. {
  158. var result = new List<PackageInfo>();
  159. foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories)
  160. {
  161. if (repository.Enabled && repository.Url != null)
  162. {
  163. // Where repositories have the same content, the details from the first is taken.
  164. foreach (var package in await GetPackages(repository.Name ?? "Unnamed Repo", repository.Url, true, cancellationToken).ConfigureAwait(true))
  165. {
  166. var existing = FilterPackages(result, package.Name, package.Id).FirstOrDefault();
  167. // Remove invalid versions from the valid package.
  168. for (var i = package.Versions.Count - 1; i >= 0; i--)
  169. {
  170. var version = package.Versions[i];
  171. var plugin = _pluginManager.GetPlugin(package.Id, version.VersionNumber);
  172. if (plugin != null)
  173. {
  174. await _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path, plugin.Manifest.Status).ConfigureAwait(false);
  175. }
  176. // Remove versions with a target ABI greater then the current application version.
  177. if (Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi)
  178. {
  179. package.Versions.RemoveAt(i);
  180. }
  181. }
  182. // Don't add a package that doesn't have any compatible versions.
  183. if (package.Versions.Count == 0)
  184. {
  185. continue;
  186. }
  187. if (existing != null)
  188. {
  189. // Assumption is both lists are ordered, so slot these into the correct place.
  190. MergeSortedList(existing.Versions, package.Versions);
  191. }
  192. else
  193. {
  194. result.Add(package);
  195. }
  196. }
  197. }
  198. }
  199. return result;
  200. }
  201. /// <inheritdoc />
  202. public IEnumerable<PackageInfo> FilterPackages(
  203. IEnumerable<PackageInfo> availablePackages,
  204. string? name = null,
  205. Guid id = default,
  206. Version? specificVersion = null)
  207. {
  208. if (name != null)
  209. {
  210. availablePackages = availablePackages.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
  211. }
  212. if (id != default)
  213. {
  214. availablePackages = availablePackages.Where(x => x.Id == id);
  215. }
  216. if (specificVersion != null)
  217. {
  218. availablePackages = availablePackages.Where(x => x.Versions.Any(y => y.VersionNumber.Equals(specificVersion)));
  219. }
  220. return availablePackages;
  221. }
  222. /// <inheritdoc />
  223. public IEnumerable<InstallationInfo> GetCompatibleVersions(
  224. IEnumerable<PackageInfo> availablePackages,
  225. string? name = null,
  226. Guid id = default,
  227. Version? minVersion = null,
  228. Version? specificVersion = null)
  229. {
  230. var package = FilterPackages(availablePackages, name, id, specificVersion).FirstOrDefault();
  231. // Package not found in repository
  232. if (package == null)
  233. {
  234. yield break;
  235. }
  236. var appVer = _applicationHost.ApplicationVersion;
  237. var availableVersions = package.Versions
  238. .Where(x => string.IsNullOrEmpty(x.TargetAbi) || Version.Parse(x.TargetAbi) <= appVer);
  239. if (specificVersion != null)
  240. {
  241. availableVersions = availableVersions.Where(x => x.VersionNumber.Equals(specificVersion));
  242. }
  243. else if (minVersion != null)
  244. {
  245. availableVersions = availableVersions.Where(x => x.VersionNumber >= minVersion);
  246. }
  247. foreach (var v in availableVersions.OrderByDescending(x => x.VersionNumber))
  248. {
  249. yield return new InstallationInfo
  250. {
  251. Changelog = v.Changelog,
  252. Id = package.Id,
  253. Name = package.Name,
  254. Version = v.VersionNumber,
  255. SourceUrl = v.SourceUrl,
  256. Checksum = v.Checksum,
  257. PackageInfo = package
  258. };
  259. }
  260. }
  261. /// <inheritdoc />
  262. public async Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  263. {
  264. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  265. return GetAvailablePluginUpdates(catalog);
  266. }
  267. /// <inheritdoc />
  268. public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken)
  269. {
  270. if (package == null)
  271. {
  272. throw new ArgumentNullException(nameof(package));
  273. }
  274. var innerCancellationTokenSource = new CancellationTokenSource();
  275. var tuple = (package, innerCancellationTokenSource);
  276. // Add it to the in-progress list
  277. lock (_currentInstallationsLock)
  278. {
  279. _currentInstallations.Add(tuple);
  280. }
  281. using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token);
  282. var linkedToken = linkedTokenSource.Token;
  283. await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false);
  284. try
  285. {
  286. var isUpdate = await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  287. lock (_currentInstallationsLock)
  288. {
  289. _currentInstallations.Remove(tuple);
  290. }
  291. _completedInstallationsInternal.Add(package);
  292. await _eventManager.PublishAsync(isUpdate
  293. ? (GenericEventArgs<InstallationInfo>)new PluginUpdatedEventArgs(package)
  294. : new PluginInstalledEventArgs(package)).ConfigureAwait(false);
  295. _applicationHost.NotifyPendingRestart();
  296. }
  297. catch (OperationCanceledException)
  298. {
  299. lock (_currentInstallationsLock)
  300. {
  301. _currentInstallations.Remove(tuple);
  302. }
  303. _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version);
  304. await _eventManager.PublishAsync(new PluginInstallationCancelledEventArgs(package)).ConfigureAwait(false);
  305. throw;
  306. }
  307. catch (Exception ex)
  308. {
  309. _logger.LogError(ex, "Package installation failed");
  310. lock (_currentInstallationsLock)
  311. {
  312. _currentInstallations.Remove(tuple);
  313. }
  314. await _eventManager.PublishAsync(new InstallationFailedEventArgs
  315. {
  316. InstallationInfo = package,
  317. Exception = ex
  318. }).ConfigureAwait(false);
  319. throw;
  320. }
  321. finally
  322. {
  323. // Dispose the progress object and remove the installation from the in-progress list
  324. tuple.innerCancellationTokenSource.Dispose();
  325. }
  326. }
  327. /// <summary>
  328. /// Uninstalls a plugin.
  329. /// </summary>
  330. /// <param name="plugin">The <see cref="LocalPlugin"/> to uninstall.</param>
  331. public void UninstallPlugin(LocalPlugin plugin)
  332. {
  333. if (plugin == null)
  334. {
  335. return;
  336. }
  337. if (plugin.Instance?.CanUninstall == false)
  338. {
  339. _logger.LogWarning("Attempt to delete non removable plugin {PluginName}, ignoring request", plugin.Name);
  340. return;
  341. }
  342. plugin.Instance?.OnUninstalling();
  343. // Remove it the quick way for now
  344. _pluginManager.RemovePlugin(plugin);
  345. _eventManager.Publish(new PluginUninstalledEventArgs(plugin.GetPluginInfo()));
  346. _applicationHost.NotifyPendingRestart();
  347. }
  348. /// <inheritdoc/>
  349. public bool CancelInstallation(Guid id)
  350. {
  351. lock (_currentInstallationsLock)
  352. {
  353. var install = _currentInstallations.Find(x => x.info.Id == id);
  354. if (install == default((InstallationInfo, CancellationTokenSource)))
  355. {
  356. return false;
  357. }
  358. install.token.Cancel();
  359. _currentInstallations.Remove(install);
  360. return true;
  361. }
  362. }
  363. /// <inheritdoc />
  364. public void Dispose()
  365. {
  366. Dispose(true);
  367. GC.SuppressFinalize(this);
  368. }
  369. /// <summary>
  370. /// Releases unmanaged and optionally managed resources.
  371. /// </summary>
  372. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
  373. protected virtual void Dispose(bool dispose)
  374. {
  375. if (dispose)
  376. {
  377. lock (_currentInstallationsLock)
  378. {
  379. foreach (var (info, token) in _currentInstallations)
  380. {
  381. token.Dispose();
  382. }
  383. _currentInstallations.Clear();
  384. }
  385. }
  386. }
  387. /// <summary>
  388. /// Merges two sorted lists.
  389. /// </summary>
  390. /// <param name="source">The source <see cref="IList{VersionInfo}"/> instance to merge.</param>
  391. /// <param name="dest">The destination <see cref="IList{VersionInfo}"/> instance to merge with.</param>
  392. private static void MergeSortedList(IList<VersionInfo> source, IList<VersionInfo> dest)
  393. {
  394. int sLength = source.Count - 1;
  395. int dLength = dest.Count;
  396. int s = 0, d = 0;
  397. var sourceVersion = source[0].VersionNumber;
  398. var destVersion = dest[0].VersionNumber;
  399. while (d < dLength)
  400. {
  401. if (sourceVersion.CompareTo(destVersion) >= 0)
  402. {
  403. if (s < sLength)
  404. {
  405. sourceVersion = source[++s].VersionNumber;
  406. }
  407. else
  408. {
  409. // Append all of destination to the end of source.
  410. while (d < dLength)
  411. {
  412. source.Add(dest[d++]);
  413. }
  414. break;
  415. }
  416. }
  417. else
  418. {
  419. source.Insert(s++, dest[d++]);
  420. if (d >= dLength)
  421. {
  422. break;
  423. }
  424. sLength++;
  425. destVersion = dest[d].VersionNumber;
  426. }
  427. }
  428. }
  429. private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
  430. {
  431. var plugins = _pluginManager.Plugins;
  432. foreach (var plugin in plugins)
  433. {
  434. // Don't auto update when plugin marked not to, or when it's disabled.
  435. if (plugin.Manifest?.AutoUpdate == false || plugin.Manifest?.Status == PluginStatus.Disabled)
  436. {
  437. continue;
  438. }
  439. var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version);
  440. var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version);
  441. if (version != null && CompletedInstallations.All(x => x.Id != version.Id))
  442. {
  443. yield return version;
  444. }
  445. }
  446. }
  447. private async Task PerformPackageInstallation(InstallationInfo package, PluginStatus status, CancellationToken cancellationToken)
  448. {
  449. var extension = Path.GetExtension(package.SourceUrl);
  450. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  451. {
  452. _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl);
  453. return;
  454. }
  455. // Always override the passed-in target (which is a file) and figure it out again
  456. string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name);
  457. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  458. .GetAsync(new Uri(package.SourceUrl), cancellationToken).ConfigureAwait(false);
  459. response.EnsureSuccessStatusCode();
  460. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  461. // CA5351: Do Not Use Broken Cryptographic Algorithms
  462. #pragma warning disable CA5351
  463. using var md5 = MD5.Create();
  464. cancellationToken.ThrowIfCancellationRequested();
  465. var hash = Convert.ToHexString(md5.ComputeHash(stream));
  466. if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase))
  467. {
  468. _logger.LogError(
  469. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  470. package.Name,
  471. package.Checksum,
  472. hash);
  473. throw new InvalidDataException("The checksum of the received data doesn't match.");
  474. }
  475. // Version folder as they cannot be overwritten in Windows.
  476. targetDir += "_" + package.Version;
  477. if (Directory.Exists(targetDir))
  478. {
  479. try
  480. {
  481. Directory.Delete(targetDir, true);
  482. }
  483. #pragma warning disable CA1031 // Do not catch general exception types
  484. catch
  485. #pragma warning restore CA1031 // Do not catch general exception types
  486. {
  487. // Ignore any exceptions.
  488. }
  489. }
  490. stream.Position = 0;
  491. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  492. await _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir, status).ConfigureAwait(false);
  493. _pluginManager.ImportPluginFrom(targetDir);
  494. }
  495. private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken)
  496. {
  497. LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Id) && p.Version.Equals(package.Version))
  498. ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version));
  499. await PerformPackageInstallation(package, plugin?.Manifest.Status ?? PluginStatus.Active, cancellationToken).ConfigureAwait(false);
  500. _logger.LogInformation(plugin == null ? "New plugin installed: {PluginName} {PluginVersion}" : "Plugin updated: {PluginName} {PluginVersion}", package.Name, package.Version);
  501. return plugin != null;
  502. }
  503. }
  504. }