InstallationManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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<IList<PackageInfo>> GetPackages(string manifestName, string manifest, bool filterIncompatible, CancellationToken cancellationToken = default)
  97. {
  98. try
  99. {
  100. List<PackageInfo>? packages = await _httpClientFactory.CreateClient(NamedClient.Default)
  101. .GetFromJsonAsync<List<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. if (!Guid.TryParse(package.Id, out var packageGuid))
  167. {
  168. // Package doesn't have a valid GUID, skip.
  169. continue;
  170. }
  171. var existing = FilterPackages(result, package.Name, packageGuid).FirstOrDefault();
  172. // Remove invalid versions from the valid package.
  173. for (var i = package.Versions.Count - 1; i >= 0; i--)
  174. {
  175. var version = package.Versions[i];
  176. var plugin = _pluginManager.GetPlugin(packageGuid, version.VersionNumber);
  177. if (plugin != null)
  178. {
  179. await _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path, plugin.Manifest.Status).ConfigureAwait(false);
  180. }
  181. // Remove versions with a target ABI greater then the current application version.
  182. if (Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi)
  183. {
  184. package.Versions.RemoveAt(i);
  185. }
  186. }
  187. // Don't add a package that doesn't have any compatible versions.
  188. if (package.Versions.Count == 0)
  189. {
  190. continue;
  191. }
  192. if (existing != null)
  193. {
  194. // Assumption is both lists are ordered, so slot these into the correct place.
  195. MergeSortedList(existing.Versions, package.Versions);
  196. }
  197. else
  198. {
  199. result.Add(package);
  200. }
  201. }
  202. }
  203. }
  204. return result;
  205. }
  206. /// <inheritdoc />
  207. public IEnumerable<PackageInfo> FilterPackages(
  208. IEnumerable<PackageInfo> availablePackages,
  209. string? name = null,
  210. Guid? id = default,
  211. Version? specificVersion = null)
  212. {
  213. if (name != null)
  214. {
  215. availablePackages = availablePackages.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
  216. }
  217. if (id != Guid.Empty)
  218. {
  219. availablePackages = availablePackages.Where(x => Guid.Parse(x.Id) == id);
  220. }
  221. if (specificVersion != null)
  222. {
  223. availablePackages = availablePackages.Where(x => x.Versions.Any(y => y.VersionNumber.Equals(specificVersion)));
  224. }
  225. return availablePackages;
  226. }
  227. /// <inheritdoc />
  228. public IEnumerable<InstallationInfo> GetCompatibleVersions(
  229. IEnumerable<PackageInfo> availablePackages,
  230. string? name = null,
  231. Guid? id = default,
  232. Version? minVersion = null,
  233. Version? specificVersion = null)
  234. {
  235. var package = FilterPackages(availablePackages, name, id, specificVersion).FirstOrDefault();
  236. // Package not found in repository
  237. if (package == null)
  238. {
  239. yield break;
  240. }
  241. var appVer = _applicationHost.ApplicationVersion;
  242. var availableVersions = package.Versions
  243. .Where(x => string.IsNullOrEmpty(x.TargetAbi) || Version.Parse(x.TargetAbi) <= appVer);
  244. if (specificVersion != null)
  245. {
  246. availableVersions = availableVersions.Where(x => x.VersionNumber.Equals(specificVersion));
  247. }
  248. else if (minVersion != null)
  249. {
  250. availableVersions = availableVersions.Where(x => x.VersionNumber >= minVersion);
  251. }
  252. foreach (var v in availableVersions.OrderByDescending(x => x.VersionNumber))
  253. {
  254. yield return new InstallationInfo
  255. {
  256. Changelog = v.Changelog,
  257. Id = new Guid(package.Id),
  258. Name = package.Name,
  259. Version = v.VersionNumber,
  260. SourceUrl = v.SourceUrl,
  261. Checksum = v.Checksum,
  262. PackageInfo = package
  263. };
  264. }
  265. }
  266. /// <inheritdoc />
  267. public async Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  268. {
  269. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  270. return GetAvailablePluginUpdates(catalog);
  271. }
  272. /// <inheritdoc />
  273. public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken)
  274. {
  275. if (package == null)
  276. {
  277. throw new ArgumentNullException(nameof(package));
  278. }
  279. var innerCancellationTokenSource = new CancellationTokenSource();
  280. var tuple = (package, innerCancellationTokenSource);
  281. // Add it to the in-progress list
  282. lock (_currentInstallationsLock)
  283. {
  284. _currentInstallations.Add(tuple);
  285. }
  286. using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token);
  287. var linkedToken = linkedTokenSource.Token;
  288. await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false);
  289. try
  290. {
  291. var isUpdate = await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  292. lock (_currentInstallationsLock)
  293. {
  294. _currentInstallations.Remove(tuple);
  295. }
  296. _completedInstallationsInternal.Add(package);
  297. await _eventManager.PublishAsync(isUpdate
  298. ? (GenericEventArgs<InstallationInfo>)new PluginUpdatedEventArgs(package)
  299. : new PluginInstalledEventArgs(package)).ConfigureAwait(false);
  300. _applicationHost.NotifyPendingRestart();
  301. }
  302. catch (OperationCanceledException)
  303. {
  304. lock (_currentInstallationsLock)
  305. {
  306. _currentInstallations.Remove(tuple);
  307. }
  308. _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version);
  309. await _eventManager.PublishAsync(new PluginInstallationCancelledEventArgs(package)).ConfigureAwait(false);
  310. throw;
  311. }
  312. catch (Exception ex)
  313. {
  314. _logger.LogError(ex, "Package installation failed");
  315. lock (_currentInstallationsLock)
  316. {
  317. _currentInstallations.Remove(tuple);
  318. }
  319. await _eventManager.PublishAsync(new InstallationFailedEventArgs
  320. {
  321. InstallationInfo = package,
  322. Exception = ex
  323. }).ConfigureAwait(false);
  324. throw;
  325. }
  326. finally
  327. {
  328. // Dispose the progress object and remove the installation from the in-progress list
  329. tuple.innerCancellationTokenSource.Dispose();
  330. }
  331. }
  332. /// <summary>
  333. /// Uninstalls a plugin.
  334. /// </summary>
  335. /// <param name="plugin">The <see cref="LocalPlugin"/> to uninstall.</param>
  336. public void UninstallPlugin(LocalPlugin plugin)
  337. {
  338. if (plugin == null)
  339. {
  340. return;
  341. }
  342. if (plugin.Instance?.CanUninstall == false)
  343. {
  344. _logger.LogWarning("Attempt to delete non removable plugin {PluginName}, ignoring request", plugin.Name);
  345. return;
  346. }
  347. plugin.Instance?.OnUninstalling();
  348. // Remove it the quick way for now
  349. _pluginManager.RemovePlugin(plugin);
  350. _eventManager.Publish(new PluginUninstalledEventArgs(plugin.GetPluginInfo()));
  351. _applicationHost.NotifyPendingRestart();
  352. }
  353. /// <inheritdoc/>
  354. public bool CancelInstallation(Guid id)
  355. {
  356. lock (_currentInstallationsLock)
  357. {
  358. var install = _currentInstallations.Find(x => x.info.Id == id);
  359. if (install == default((InstallationInfo, CancellationTokenSource)))
  360. {
  361. return false;
  362. }
  363. install.token.Cancel();
  364. _currentInstallations.Remove(install);
  365. return true;
  366. }
  367. }
  368. /// <inheritdoc />
  369. public void Dispose()
  370. {
  371. Dispose(true);
  372. GC.SuppressFinalize(this);
  373. }
  374. /// <summary>
  375. /// Releases unmanaged and optionally managed resources.
  376. /// </summary>
  377. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
  378. protected virtual void Dispose(bool dispose)
  379. {
  380. if (dispose)
  381. {
  382. lock (_currentInstallationsLock)
  383. {
  384. foreach (var (info, token) in _currentInstallations)
  385. {
  386. token.Dispose();
  387. }
  388. _currentInstallations.Clear();
  389. }
  390. }
  391. }
  392. /// <summary>
  393. /// Merges two sorted lists.
  394. /// </summary>
  395. /// <param name="source">The source <see cref="IList{VersionInfo}"/> instance to merge.</param>
  396. /// <param name="dest">The destination <see cref="IList{VersionInfo}"/> instance to merge with.</param>
  397. private static void MergeSortedList(IList<VersionInfo> source, IList<VersionInfo> dest)
  398. {
  399. int sLength = source.Count - 1;
  400. int dLength = dest.Count;
  401. int s = 0, d = 0;
  402. var sourceVersion = source[0].VersionNumber;
  403. var destVersion = dest[0].VersionNumber;
  404. while (d < dLength)
  405. {
  406. if (sourceVersion.CompareTo(destVersion) >= 0)
  407. {
  408. if (s < sLength)
  409. {
  410. sourceVersion = source[++s].VersionNumber;
  411. }
  412. else
  413. {
  414. // Append all of destination to the end of source.
  415. while (d < dLength)
  416. {
  417. source.Add(dest[d++]);
  418. }
  419. break;
  420. }
  421. }
  422. else
  423. {
  424. source.Insert(s++, dest[d++]);
  425. if (d >= dLength)
  426. {
  427. break;
  428. }
  429. sLength++;
  430. destVersion = dest[d].VersionNumber;
  431. }
  432. }
  433. }
  434. private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
  435. {
  436. var plugins = _pluginManager.Plugins;
  437. foreach (var plugin in plugins)
  438. {
  439. // Don't auto update when plugin marked not to, or when it's disabled.
  440. if (plugin.Manifest?.AutoUpdate == false || plugin.Manifest?.Status == PluginStatus.Disabled)
  441. {
  442. continue;
  443. }
  444. var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version);
  445. var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version);
  446. if (version != null && CompletedInstallations.All(x => x.Id != version.Id))
  447. {
  448. yield return version;
  449. }
  450. }
  451. }
  452. private async Task PerformPackageInstallation(InstallationInfo package, PluginStatus status, CancellationToken cancellationToken)
  453. {
  454. var extension = Path.GetExtension(package.SourceUrl);
  455. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  456. {
  457. _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl);
  458. return;
  459. }
  460. // Always override the passed-in target (which is a file) and figure it out again
  461. string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name);
  462. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  463. .GetAsync(new Uri(package.SourceUrl), cancellationToken).ConfigureAwait(false);
  464. response.EnsureSuccessStatusCode();
  465. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  466. // CA5351: Do Not Use Broken Cryptographic Algorithms
  467. #pragma warning disable CA5351
  468. using var md5 = MD5.Create();
  469. cancellationToken.ThrowIfCancellationRequested();
  470. var hash = Convert.ToHexString(md5.ComputeHash(stream));
  471. if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase))
  472. {
  473. _logger.LogError(
  474. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  475. package.Name,
  476. package.Checksum,
  477. hash);
  478. throw new InvalidDataException("The checksum of the received data doesn't match.");
  479. }
  480. // Version folder as they cannot be overwritten in Windows.
  481. targetDir += "_" + package.Version;
  482. if (Directory.Exists(targetDir))
  483. {
  484. try
  485. {
  486. Directory.Delete(targetDir, true);
  487. }
  488. #pragma warning disable CA1031 // Do not catch general exception types
  489. catch
  490. #pragma warning restore CA1031 // Do not catch general exception types
  491. {
  492. // Ignore any exceptions.
  493. }
  494. }
  495. stream.Position = 0;
  496. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  497. await _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir, status).ConfigureAwait(false);
  498. _pluginManager.ImportPluginFrom(targetDir);
  499. }
  500. private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken)
  501. {
  502. LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Id) && p.Version.Equals(package.Version))
  503. ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version));
  504. await PerformPackageInstallation(package, plugin?.Manifest.Status ?? PluginStatus.Active, cancellationToken).ConfigureAwait(false);
  505. _logger.LogInformation(plugin == null ? "New plugin installed: {PluginName} {PluginVersion}" : "Plugin updated: {PluginName} {PluginVersion}", package.Name, package.Version);
  506. return plugin != null;
  507. }
  508. }
  509. }