InstallationManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. /// <inheritdoc />
  96. public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
  97. {
  98. using (var response = await _httpClient.SendAsync(
  99. new HttpRequestOptions
  100. {
  101. Url = "https://repo.jellyfin.org/releases/plugin/manifest.json",
  102. CancellationToken = cancellationToken,
  103. CacheMode = CacheMode.Unconditional,
  104. CacheLength = TimeSpan.FromMinutes(3)
  105. },
  106. HttpMethod.Get).ConfigureAwait(false))
  107. using (Stream stream = response.Content)
  108. {
  109. return await _jsonSerializer.DeserializeFromStreamAsync<IReadOnlyList<PackageInfo>>(
  110. stream).ConfigureAwait(false);
  111. }
  112. }
  113. /// <inheritdoc />
  114. public IEnumerable<PackageInfo> FilterPackages(
  115. IEnumerable<PackageInfo> availablePackages,
  116. string name = null,
  117. Guid guid = default)
  118. {
  119. if (name != null)
  120. {
  121. availablePackages = availablePackages.Where(x => x.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  122. }
  123. if (guid != Guid.Empty)
  124. {
  125. var strGuid = guid.ToString("N", CultureInfo.InvariantCulture);
  126. availablePackages = availablePackages.Where(x => x.guid.Equals(strGuid, StringComparison.OrdinalIgnoreCase));
  127. }
  128. return availablePackages;
  129. }
  130. /// <inheritdoc />
  131. public IEnumerable<PackageVersionInfo> GetCompatibleVersions(
  132. IEnumerable<PackageVersionInfo> availableVersions,
  133. Version minVersion = null,
  134. PackageVersionClass classification = PackageVersionClass.Release)
  135. {
  136. var appVer = _applicationHost.ApplicationVersion;
  137. availableVersions = availableVersions
  138. .Where(x => x.classification == classification
  139. && Version.Parse(x.requiredVersionStr) <= appVer);
  140. if (minVersion != null)
  141. {
  142. availableVersions = availableVersions.Where(x => x.Version >= minVersion);
  143. }
  144. return availableVersions.OrderByDescending(x => x.Version);
  145. }
  146. /// <inheritdoc />
  147. public IEnumerable<PackageVersionInfo> GetCompatibleVersions(
  148. IEnumerable<PackageInfo> availablePackages,
  149. string name = null,
  150. Guid guid = default,
  151. Version minVersion = null,
  152. PackageVersionClass classification = PackageVersionClass.Release)
  153. {
  154. var package = FilterPackages(availablePackages, name, guid).FirstOrDefault();
  155. // Package not found.
  156. if (package == null)
  157. {
  158. return null;
  159. }
  160. return GetCompatibleVersions(
  161. package.versions,
  162. minVersion,
  163. classification);
  164. }
  165. /// <inheritdoc />
  166. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  167. {
  168. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  169. var systemUpdateLevel = _applicationHost.SystemUpdateLevel;
  170. // Figure out what needs to be installed
  171. return _applicationHost.Plugins.Select(x =>
  172. {
  173. var compatibleversions = GetCompatibleVersions(catalog, x.Name, x.Id, x.Version, systemUpdateLevel);
  174. return compatibleversions.FirstOrDefault(y => y.Version > x.Version);
  175. }).Where(x => x != null)
  176. .Where(x => !CompletedInstallations.Any(y => string.Equals(y.AssemblyGuid, x.guid, StringComparison.OrdinalIgnoreCase)));
  177. }
  178. /// <inheritdoc />
  179. public async Task InstallPackage(PackageVersionInfo package, CancellationToken cancellationToken)
  180. {
  181. if (package == null)
  182. {
  183. throw new ArgumentNullException(nameof(package));
  184. }
  185. var installationInfo = new InstallationInfo
  186. {
  187. Id = Guid.NewGuid(),
  188. Name = package.name,
  189. AssemblyGuid = package.guid,
  190. UpdateClass = package.classification,
  191. Version = package.versionStr
  192. };
  193. var innerCancellationTokenSource = new CancellationTokenSource();
  194. var tuple = (installationInfo, innerCancellationTokenSource);
  195. // Add it to the in-progress list
  196. lock (_currentInstallations)
  197. {
  198. _currentInstallations.Add(tuple);
  199. }
  200. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  201. var installationEventArgs = new InstallationEventArgs
  202. {
  203. InstallationInfo = installationInfo,
  204. PackageVersionInfo = package
  205. };
  206. PackageInstalling?.Invoke(this, installationEventArgs);
  207. try
  208. {
  209. await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  210. lock (_currentInstallations)
  211. {
  212. _currentInstallations.Remove(tuple);
  213. }
  214. _completedInstallationsInternal.Add(installationInfo);
  215. PackageInstallationCompleted?.Invoke(this, installationEventArgs);
  216. }
  217. catch (OperationCanceledException)
  218. {
  219. lock (_currentInstallations)
  220. {
  221. _currentInstallations.Remove(tuple);
  222. }
  223. _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  224. PackageInstallationCancelled?.Invoke(this, installationEventArgs);
  225. throw;
  226. }
  227. catch (Exception ex)
  228. {
  229. _logger.LogError(ex, "Package installation failed");
  230. lock (_currentInstallations)
  231. {
  232. _currentInstallations.Remove(tuple);
  233. }
  234. PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs
  235. {
  236. InstallationInfo = installationInfo,
  237. Exception = ex
  238. });
  239. throw;
  240. }
  241. finally
  242. {
  243. // Dispose the progress object and remove the installation from the in-progress list
  244. tuple.innerCancellationTokenSource.Dispose();
  245. }
  246. }
  247. /// <summary>
  248. /// Installs the package internal.
  249. /// </summary>
  250. /// <param name="package">The package.</param>
  251. /// <param name="cancellationToken">The cancellation token.</param>
  252. /// <returns><see cref="Task" />.</returns>
  253. private async Task InstallPackageInternal(PackageVersionInfo package, CancellationToken cancellationToken)
  254. {
  255. // Set last update time if we were installed before
  256. IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
  257. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  258. // Do the install
  259. await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false);
  260. // Do plugin-specific processing
  261. if (plugin == null)
  262. {
  263. _logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  264. PluginInstalled?.Invoke(this, new GenericEventArgs<PackageVersionInfo>(package));
  265. }
  266. else
  267. {
  268. _logger.LogInformation("Plugin updated: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  269. PluginUpdated?.Invoke(this, new GenericEventArgs<(IPlugin, PackageVersionInfo)>((plugin, package)));
  270. }
  271. _applicationHost.NotifyPendingRestart();
  272. }
  273. private async Task PerformPackageInstallation(PackageVersionInfo package, CancellationToken cancellationToken)
  274. {
  275. var extension = Path.GetExtension(package.targetFilename);
  276. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  277. {
  278. _logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.targetFilename);
  279. return;
  280. }
  281. // Always override the passed-in target (which is a file) and figure it out again
  282. string targetDir = Path.Combine(_appPaths.PluginsPath, package.name);
  283. // CA5351: Do Not Use Broken Cryptographic Algorithms
  284. #pragma warning disable CA5351
  285. using (var res = await _httpClient.SendAsync(
  286. new HttpRequestOptions
  287. {
  288. Url = package.sourceUrl,
  289. CancellationToken = cancellationToken,
  290. // We need it to be buffered for setting the position
  291. BufferContent = true
  292. },
  293. HttpMethod.Get).ConfigureAwait(false))
  294. using (var stream = res.Content)
  295. using (var md5 = MD5.Create())
  296. {
  297. cancellationToken.ThrowIfCancellationRequested();
  298. var hash = ToHexString(md5.ComputeHash(stream));
  299. if (!string.Equals(package.checksum, hash, StringComparison.OrdinalIgnoreCase))
  300. {
  301. _logger.LogError(
  302. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  303. package.name,
  304. package.checksum,
  305. hash);
  306. throw new InvalidDataException("The checksum of the received data doesn't match.");
  307. }
  308. if (Directory.Exists(targetDir))
  309. {
  310. Directory.Delete(targetDir, true);
  311. }
  312. stream.Position = 0;
  313. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  314. }
  315. #pragma warning restore CA5351
  316. }
  317. /// <summary>
  318. /// Uninstalls a plugin
  319. /// </summary>
  320. /// <param name="plugin">The plugin.</param>
  321. public void UninstallPlugin(IPlugin plugin)
  322. {
  323. plugin.OnUninstalling();
  324. // Remove it the quick way for now
  325. _applicationHost.RemovePlugin(plugin);
  326. var path = plugin.AssemblyFilePath;
  327. bool isDirectory = false;
  328. // Check if we have a plugin directory we should remove too
  329. if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath)
  330. {
  331. path = Path.GetDirectoryName(plugin.AssemblyFilePath);
  332. isDirectory = true;
  333. }
  334. // Make this case-insensitive to account for possible incorrect assembly naming
  335. var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
  336. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  337. if (!string.IsNullOrWhiteSpace(file))
  338. {
  339. path = file;
  340. }
  341. if (isDirectory)
  342. {
  343. _logger.LogInformation("Deleting plugin directory {0}", path);
  344. Directory.Delete(path, true);
  345. }
  346. else
  347. {
  348. _logger.LogInformation("Deleting plugin file {0}", path);
  349. _fileSystem.DeleteFile(path);
  350. }
  351. var list = _config.Configuration.UninstalledPlugins.ToList();
  352. var filename = Path.GetFileName(path);
  353. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  354. {
  355. list.Add(filename);
  356. _config.Configuration.UninstalledPlugins = list.ToArray();
  357. _config.SaveConfiguration();
  358. }
  359. PluginUninstalled?.Invoke(this, new GenericEventArgs<IPlugin> { Argument = plugin });
  360. _applicationHost.NotifyPendingRestart();
  361. }
  362. /// <inheritdoc/>
  363. public bool CancelInstallation(Guid id)
  364. {
  365. lock (_currentInstallations)
  366. {
  367. var install = _currentInstallations.Find(x => x.info.Id == id);
  368. if (install == default((InstallationInfo, CancellationTokenSource)))
  369. {
  370. return false;
  371. }
  372. install.token.Cancel();
  373. _currentInstallations.Remove(install);
  374. return true;
  375. }
  376. }
  377. /// <inheritdoc />
  378. public void Dispose()
  379. {
  380. Dispose(true);
  381. GC.SuppressFinalize(this);
  382. }
  383. /// <summary>
  384. /// Releases unmanaged and - optionally - managed resources.
  385. /// </summary>
  386. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  387. protected virtual void Dispose(bool dispose)
  388. {
  389. if (dispose)
  390. {
  391. lock (_currentInstallations)
  392. {
  393. foreach (var tuple in _currentInstallations)
  394. {
  395. tuple.token.Dispose();
  396. }
  397. _currentInstallations.Clear();
  398. }
  399. }
  400. }
  401. }
  402. }