InstallationManager.cs 22 KB

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