InstallationManager.cs 23 KB

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