InstallationManager.cs 22 KB

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