InstallationManager.cs 23 KB

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