2
0

InstallationManager.cs 17 KB

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