InstallationManager.cs 23 KB

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