InstallationManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Common.Plugins;
  13. using MediaBrowser.Common.Progress;
  14. using MediaBrowser.Common.Updates;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Model.Events;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Model.Updates;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.Updates
  22. {
  23. /// <summary>
  24. /// Manages all install, uninstall and update operations (both plugins and system)
  25. /// </summary>
  26. public class InstallationManager : IInstallationManager
  27. {
  28. public event EventHandler<InstallationEventArgs> PackageInstalling;
  29. public event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
  30. public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
  31. public event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
  32. /// <summary>
  33. /// The current installations
  34. /// </summary>
  35. private List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations { get; set; }
  36. /// <summary>
  37. /// The completed installations
  38. /// </summary>
  39. private ConcurrentBag<InstallationInfo> _completedInstallationsInternal;
  40. public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
  41. /// <summary>
  42. /// Occurs when [plugin uninstalled].
  43. /// </summary>
  44. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  45. /// <summary>
  46. /// Occurs when [plugin updated].
  47. /// </summary>
  48. public event EventHandler<GenericEventArgs<(IPlugin, PackageVersionInfo)>> PluginUpdated;
  49. /// <summary>
  50. /// Occurs when [plugin updated].
  51. /// </summary>
  52. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  53. /// <summary>
  54. /// The _logger
  55. /// </summary>
  56. private readonly ILogger _logger;
  57. private readonly IApplicationPaths _appPaths;
  58. private readonly IHttpClient _httpClient;
  59. private readonly IJsonSerializer _jsonSerializer;
  60. private readonly IServerConfigurationManager _config;
  61. private readonly IFileSystem _fileSystem;
  62. /// <summary>
  63. /// Gets the application host.
  64. /// </summary>
  65. /// <value>The application host.</value>
  66. private readonly IApplicationHost _applicationHost;
  67. private readonly IZipClient _zipClient;
  68. public InstallationManager(
  69. ILogger<InstallationManager> logger,
  70. IApplicationHost appHost,
  71. IApplicationPaths appPaths,
  72. IHttpClient httpClient,
  73. IJsonSerializer jsonSerializer,
  74. IServerConfigurationManager config,
  75. IFileSystem fileSystem,
  76. IZipClient zipClient)
  77. {
  78. if (logger == null)
  79. {
  80. throw new ArgumentNullException(nameof(logger));
  81. }
  82. _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>();
  83. _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
  84. _logger = logger;
  85. _applicationHost = appHost;
  86. _appPaths = appPaths;
  87. _httpClient = httpClient;
  88. _jsonSerializer = jsonSerializer;
  89. _config = config;
  90. _fileSystem = fileSystem;
  91. _zipClient = zipClient;
  92. }
  93. /// <summary>
  94. /// Gets all available packages.
  95. /// </summary>
  96. /// <returns>Task{List{PackageInfo}}.</returns>
  97. public async Task<List<PackageInfo>> GetAvailablePackages(
  98. CancellationToken cancellationToken,
  99. bool withRegistration = true,
  100. string packageType = null,
  101. Version applicationVersion = null)
  102. {
  103. var packages = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  104. return FilterPackages(packages, packageType, applicationVersion);
  105. }
  106. /// <summary>
  107. /// Gets all available packages.
  108. /// </summary>
  109. /// <param name="cancellationToken">The cancellation token.</param>
  110. /// <returns>Task{List{PackageInfo}}.</returns>
  111. public async Task<List<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken)
  112. {
  113. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  114. {
  115. Url = "https://repo.jellyfin.org/releases/plugin/manifest.json",
  116. CancellationToken = cancellationToken,
  117. CacheLength = GetCacheLength()
  118. }, HttpMethod.Get).ConfigureAwait(false))
  119. using (var stream = response.Content)
  120. {
  121. return FilterPackages(await _jsonSerializer.DeserializeFromStreamAsync<PackageInfo[]>(stream).ConfigureAwait(false));
  122. }
  123. }
  124. private static TimeSpan GetCacheLength()
  125. {
  126. return TimeSpan.FromMinutes(3);
  127. }
  128. protected List<PackageInfo> FilterPackages(IEnumerable<PackageInfo> packages)
  129. {
  130. var list = new List<PackageInfo>();
  131. foreach (var package in packages)
  132. {
  133. var versions = new List<PackageVersionInfo>();
  134. foreach (var version in package.versions)
  135. {
  136. if (string.IsNullOrEmpty(version.sourceUrl))
  137. {
  138. continue;
  139. }
  140. versions.Add(version);
  141. }
  142. package.versions = versions
  143. .OrderByDescending(x => x.Version)
  144. .ToArray();
  145. if (package.versions.Length == 0)
  146. {
  147. continue;
  148. }
  149. list.Add(package);
  150. }
  151. // Remove packages with no versions
  152. return list;
  153. }
  154. protected List<PackageInfo> FilterPackages(IEnumerable<PackageInfo> packages, string packageType, Version applicationVersion)
  155. {
  156. var packagesList = FilterPackages(packages);
  157. var returnList = new List<PackageInfo>();
  158. var filterOnPackageType = !string.IsNullOrEmpty(packageType);
  159. foreach (var p in packagesList)
  160. {
  161. if (filterOnPackageType && !string.Equals(p.type, packageType, StringComparison.OrdinalIgnoreCase))
  162. {
  163. continue;
  164. }
  165. // If an app version was supplied, filter the versions for each package to only include supported versions
  166. if (applicationVersion != null)
  167. {
  168. p.versions = p.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToArray();
  169. }
  170. if (p.versions.Length == 0)
  171. {
  172. continue;
  173. }
  174. returnList.Add(p);
  175. }
  176. return returnList;
  177. }
  178. /// <summary>
  179. /// Determines whether [is package version up to date] [the specified package version info].
  180. /// </summary>
  181. /// <param name="packageVersionInfo">The package version info.</param>
  182. /// <param name="currentServerVersion">The current server version.</param>
  183. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  184. private static bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion)
  185. {
  186. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  187. {
  188. return true;
  189. }
  190. return Version.TryParse(packageVersionInfo.requiredVersionStr, out var requiredVersion) && currentServerVersion >= requiredVersion;
  191. }
  192. /// <summary>
  193. /// Gets the package.
  194. /// </summary>
  195. /// <param name="name">The name.</param>
  196. /// <param name="guid">The assembly guid</param>
  197. /// <param name="classification">The classification.</param>
  198. /// <param name="version">The version.</param>
  199. /// <returns>Task{PackageVersionInfo}.</returns>
  200. public async Task<PackageVersionInfo> GetPackage(string name, string guid, PackageVersionClass classification, Version version)
  201. {
  202. var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
  203. var package = packages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  204. ?? packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  205. if (package == null)
  206. {
  207. return null;
  208. }
  209. return package.versions.FirstOrDefault(v => v.Version == version && v.classification == classification);
  210. }
  211. /// <summary>
  212. /// Gets the latest compatible version.
  213. /// </summary>
  214. /// <param name="name">The name.</param>
  215. /// <param name="guid">The assembly guid if this is a plug-in</param>
  216. /// <param name="currentServerVersion">The current server version.</param>
  217. /// <param name="classification">The classification.</param>
  218. /// <returns>Task{PackageVersionInfo}.</returns>
  219. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  220. {
  221. var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
  222. return GetLatestCompatibleVersion(packages, name, guid, currentServerVersion, classification);
  223. }
  224. /// <summary>
  225. /// Gets the latest compatible version.
  226. /// </summary>
  227. /// <param name="availablePackages">The available packages.</param>
  228. /// <param name="name">The name.</param>
  229. /// <param name="currentServerVersion">The current server version.</param>
  230. /// <param name="classification">The classification.</param>
  231. /// <returns>PackageVersionInfo.</returns>
  232. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  233. {
  234. var package = availablePackages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  235. ?? availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  236. if (package == null)
  237. {
  238. return null;
  239. }
  240. return package.versions
  241. .OrderByDescending(x => x.Version)
  242. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
  243. }
  244. /// <summary>
  245. /// Gets the available plugin updates.
  246. /// </summary>
  247. /// <param name="applicationVersion">The current server version.</param>
  248. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  249. /// <param name="cancellationToken">The cancellation token.</param>
  250. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  251. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  252. {
  253. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  254. var systemUpdateLevel = _applicationHost.SystemUpdateLevel;
  255. // Figure out what needs to be installed
  256. return _applicationHost.Plugins.Select(p =>
  257. {
  258. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Id.ToString(), applicationVersion, systemUpdateLevel);
  259. return latestPluginInfo != null && latestPluginInfo.Version > p.Version ? latestPluginInfo : null;
  260. }).Where(i => i != null)
  261. .Where(p => !string.IsNullOrEmpty(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.AssemblyGuid, p.guid, StringComparison.OrdinalIgnoreCase)));
  262. }
  263. /// <summary>
  264. /// Installs the package.
  265. /// </summary>
  266. /// <param name="package">The package.</param>
  267. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  268. /// <param name="progress">The progress.</param>
  269. /// <param name="cancellationToken">The cancellation token.</param>
  270. /// <returns>Task.</returns>
  271. /// <exception cref="ArgumentNullException">package</exception>
  272. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  273. {
  274. if (package == null)
  275. {
  276. throw new ArgumentNullException(nameof(package));
  277. }
  278. if (progress == null)
  279. {
  280. throw new ArgumentNullException(nameof(progress));
  281. }
  282. var installationInfo = new InstallationInfo
  283. {
  284. Id = Guid.NewGuid(),
  285. Name = package.name,
  286. AssemblyGuid = package.guid,
  287. UpdateClass = package.classification,
  288. Version = package.versionStr
  289. };
  290. var innerCancellationTokenSource = new CancellationTokenSource();
  291. var tuple = (installationInfo, innerCancellationTokenSource);
  292. // Add it to the in-progress list
  293. lock (_currentInstallations)
  294. {
  295. _currentInstallations.Add(tuple);
  296. }
  297. var innerProgress = new ActionableProgress<double>();
  298. // Whenever the progress updates, update the outer progress object and InstallationInfo
  299. innerProgress.RegisterAction(percent =>
  300. {
  301. progress.Report(percent);
  302. installationInfo.PercentComplete = percent;
  303. });
  304. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  305. var installationEventArgs = new InstallationEventArgs
  306. {
  307. InstallationInfo = installationInfo,
  308. PackageVersionInfo = package
  309. };
  310. PackageInstalling?.Invoke(this, installationEventArgs);
  311. try
  312. {
  313. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  314. lock (_currentInstallations)
  315. {
  316. _currentInstallations.Remove(tuple);
  317. }
  318. _completedInstallationsInternal.Add(installationInfo);
  319. PackageInstallationCompleted?.Invoke(this, installationEventArgs);
  320. }
  321. catch (OperationCanceledException)
  322. {
  323. lock (_currentInstallations)
  324. {
  325. _currentInstallations.Remove(tuple);
  326. }
  327. _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  328. PackageInstallationCancelled?.Invoke(this, installationEventArgs);
  329. throw;
  330. }
  331. catch (Exception ex)
  332. {
  333. _logger.LogError(ex, "Package installation failed");
  334. lock (_currentInstallations)
  335. {
  336. _currentInstallations.Remove(tuple);
  337. }
  338. PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs
  339. {
  340. InstallationInfo = installationInfo,
  341. Exception = ex
  342. });
  343. throw;
  344. }
  345. finally
  346. {
  347. // Dispose the progress object and remove the installation from the in-progress list
  348. tuple.Item2.Dispose();
  349. }
  350. }
  351. /// <summary>
  352. /// Installs the package internal.
  353. /// </summary>
  354. /// <param name="package">The package.</param>
  355. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  356. /// <param name="progress">The progress.</param>
  357. /// <param name="cancellationToken">The cancellation token.</param>
  358. /// <returns>Task.</returns>
  359. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  360. {
  361. // Set last update time if we were installed before
  362. IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
  363. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  364. string targetPath = plugin == null ? null : plugin.AssemblyFilePath;
  365. // Do the install
  366. await PerformPackageInstallation(progress, targetPath, package, cancellationToken).ConfigureAwait(false);
  367. // Do plugin-specific processing
  368. if (plugin == null)
  369. {
  370. _logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  371. PluginInstalled?.Invoke(this, new GenericEventArgs<PackageVersionInfo>(package));
  372. }
  373. else
  374. {
  375. _logger.LogInformation("Plugin updated: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  376. PluginUpdated?.Invoke(this, new GenericEventArgs<(IPlugin, PackageVersionInfo)>((plugin, package)));
  377. }
  378. _applicationHost.NotifyPendingRestart();
  379. }
  380. private async Task PerformPackageInstallation(IProgress<double> progress, string target, PackageVersionInfo package, CancellationToken cancellationToken)
  381. {
  382. // TODO: Remove the `string target` argument as it is not used any longer
  383. var extension = Path.GetExtension(package.targetFilename);
  384. var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase);
  385. if (!isArchive)
  386. {
  387. _logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.targetFilename);
  388. return;
  389. }
  390. // Always override the passed-in target (which is a file) and figure it out again
  391. target = Path.Combine(_appPaths.PluginsPath, package.name);
  392. _logger.LogDebug("Installing plugin to {Filename}.", target);
  393. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  394. _logger.LogDebug("Downloading ZIP.");
  395. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  396. {
  397. Url = package.sourceUrl,
  398. CancellationToken = cancellationToken,
  399. Progress = progress
  400. }).ConfigureAwait(false);
  401. cancellationToken.ThrowIfCancellationRequested();
  402. // TODO: Validate with a checksum, *properly*
  403. // Check if the target directory already exists, and remove it if so
  404. if (Directory.Exists(target))
  405. {
  406. _logger.LogDebug("Deleting existing plugin at {Filename}.", target);
  407. Directory.Delete(target, true);
  408. }
  409. // Success - move it to the real target
  410. try
  411. {
  412. _logger.LogDebug("Extracting ZIP {TempFile} to {Filename}.", tempFile, target);
  413. using (var stream = File.OpenRead(tempFile))
  414. {
  415. _zipClient.ExtractAllFromZip(stream, target, true);
  416. }
  417. }
  418. catch (IOException ex)
  419. {
  420. _logger.LogError(ex, "Error attempting to extract {TempFile} to {TargetFile}", tempFile, target);
  421. throw;
  422. }
  423. try
  424. {
  425. _logger.LogDebug("Deleting temporary file {Filename}.", tempFile);
  426. _fileSystem.DeleteFile(tempFile);
  427. }
  428. catch (IOException ex)
  429. {
  430. // Don't fail because of this
  431. _logger.LogError(ex, "Error deleting temp file {TempFile}", tempFile);
  432. }
  433. }
  434. /// <summary>
  435. /// Uninstalls a plugin
  436. /// </summary>
  437. /// <param name="plugin">The plugin.</param>
  438. /// <exception cref="ArgumentException"></exception>
  439. public void UninstallPlugin(IPlugin plugin)
  440. {
  441. plugin.OnUninstalling();
  442. // Remove it the quick way for now
  443. _applicationHost.RemovePlugin(plugin);
  444. var path = plugin.AssemblyFilePath;
  445. bool isDirectory = false;
  446. // Check if we have a plugin directory we should remove too
  447. if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath)
  448. {
  449. path = Path.GetDirectoryName(plugin.AssemblyFilePath);
  450. isDirectory = true;
  451. }
  452. // Make this case-insensitive to account for possible incorrect assembly naming
  453. var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
  454. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  455. if (!string.IsNullOrWhiteSpace(file))
  456. {
  457. path = file;
  458. }
  459. if (isDirectory)
  460. {
  461. _logger.LogInformation("Deleting plugin directory {0}", path);
  462. Directory.Delete(path, true);
  463. }
  464. else
  465. {
  466. _logger.LogInformation("Deleting plugin file {0}", path);
  467. _fileSystem.DeleteFile(path);
  468. }
  469. var list = _config.Configuration.UninstalledPlugins.ToList();
  470. var filename = Path.GetFileName(path);
  471. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  472. {
  473. list.Add(filename);
  474. _config.Configuration.UninstalledPlugins = list.ToArray();
  475. _config.SaveConfiguration();
  476. }
  477. PluginUninstalled?.Invoke(this, new GenericEventArgs<IPlugin> { Argument = plugin });
  478. _applicationHost.NotifyPendingRestart();
  479. }
  480. /// <inheritdoc/>
  481. public bool CancelInstallation(Guid id)
  482. {
  483. lock (_currentInstallations)
  484. {
  485. var install = _currentInstallations.Find(x => x.Item1.Id == id);
  486. if (install == default((InstallationInfo, CancellationTokenSource)))
  487. {
  488. return false;
  489. }
  490. install.Item2.Cancel();
  491. _currentInstallations.Remove(install);
  492. return true;
  493. }
  494. }
  495. public void Dispose()
  496. {
  497. Dispose(true);
  498. GC.SuppressFinalize(this);
  499. }
  500. /// <summary>
  501. /// Releases unmanaged and - optionally - managed resources.
  502. /// </summary>
  503. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  504. protected virtual void Dispose(bool dispose)
  505. {
  506. if (dispose)
  507. {
  508. lock (_currentInstallations)
  509. {
  510. foreach (var tuple in _currentInstallations)
  511. {
  512. tuple.Item2.Dispose();
  513. }
  514. _currentInstallations.Clear();
  515. }
  516. }
  517. }
  518. }
  519. }