InstallationManager.cs 22 KB

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