InstallationManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. using System.Security.Cryptography;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Events;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Common.Plugins;
  6. using MediaBrowser.Common.Progress;
  7. using MediaBrowser.Common.Security;
  8. using MediaBrowser.Common.Updates;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Serialization;
  11. using MediaBrowser.Model.Updates;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Common.Implementations.Updates
  20. {
  21. /// <summary>
  22. /// Manages all install, uninstall and update operations (both plugins and system)
  23. /// </summary>
  24. public class InstallationManager : IInstallationManager
  25. {
  26. public event EventHandler<InstallationEventArgs> PackageInstalling;
  27. public event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
  28. public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
  29. public event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
  30. /// <summary>
  31. /// The current installations
  32. /// </summary>
  33. public List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations { get; set; }
  34. /// <summary>
  35. /// The completed installations
  36. /// </summary>
  37. public ConcurrentBag<InstallationInfo> CompletedInstallations { get; set; }
  38. #region PluginUninstalled Event
  39. /// <summary>
  40. /// Occurs when [plugin uninstalled].
  41. /// </summary>
  42. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  43. /// <summary>
  44. /// Called when [plugin uninstalled].
  45. /// </summary>
  46. /// <param name="plugin">The plugin.</param>
  47. private void OnPluginUninstalled(IPlugin plugin)
  48. {
  49. EventHelper.QueueEventIfNotNull(PluginUninstalled, this, new GenericEventArgs<IPlugin> { Argument = plugin }, _logger);
  50. }
  51. #endregion
  52. #region PluginUpdated Event
  53. /// <summary>
  54. /// Occurs when [plugin updated].
  55. /// </summary>
  56. public event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
  57. /// <summary>
  58. /// Called when [plugin updated].
  59. /// </summary>
  60. /// <param name="plugin">The plugin.</param>
  61. /// <param name="newVersion">The new version.</param>
  62. private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
  63. {
  64. _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.version, newVersion.classification);
  65. EventHelper.QueueEventIfNotNull(PluginUpdated, this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) }, _logger);
  66. _applicationHost.NotifyPendingRestart();
  67. }
  68. #endregion
  69. #region PluginInstalled Event
  70. /// <summary>
  71. /// Occurs when [plugin updated].
  72. /// </summary>
  73. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  74. /// <summary>
  75. /// Called when [plugin installed].
  76. /// </summary>
  77. /// <param name="package">The package.</param>
  78. private void OnPluginInstalled(PackageVersionInfo package)
  79. {
  80. _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.version, package.classification);
  81. EventHelper.QueueEventIfNotNull(PluginInstalled, this, new GenericEventArgs<PackageVersionInfo> { Argument = package }, _logger);
  82. _applicationHost.NotifyPendingRestart();
  83. }
  84. #endregion
  85. /// <summary>
  86. /// The _logger
  87. /// </summary>
  88. private readonly ILogger _logger;
  89. private readonly IApplicationPaths _appPaths;
  90. private readonly IHttpClient _httpClient;
  91. private readonly IJsonSerializer _jsonSerializer;
  92. private readonly ISecurityManager _securityManager;
  93. private readonly INetworkManager _networkManager;
  94. /// <summary>
  95. /// Gets the application host.
  96. /// </summary>
  97. /// <value>The application host.</value>
  98. private readonly IApplicationHost _applicationHost;
  99. public InstallationManager(ILogger logger, IApplicationHost appHost, IApplicationPaths appPaths, IHttpClient httpClient, IJsonSerializer jsonSerializer, ISecurityManager securityManager, INetworkManager networkManager)
  100. {
  101. if (logger == null)
  102. {
  103. throw new ArgumentNullException("logger");
  104. }
  105. CurrentInstallations = new List<Tuple<InstallationInfo, CancellationTokenSource>>();
  106. CompletedInstallations = new ConcurrentBag<InstallationInfo>();
  107. _applicationHost = appHost;
  108. _appPaths = appPaths;
  109. _httpClient = httpClient;
  110. _jsonSerializer = jsonSerializer;
  111. _securityManager = securityManager;
  112. _networkManager = networkManager;
  113. _logger = logger;
  114. }
  115. /// <summary>
  116. /// Gets all available packages.
  117. /// </summary>
  118. /// <param name="cancellationToken">The cancellation token.</param>
  119. /// <param name="packageType">Type of the package.</param>
  120. /// <param name="applicationVersion">The application version.</param>
  121. /// <returns>Task{List{PackageInfo}}.</returns>
  122. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  123. PackageType? packageType = null,
  124. Version applicationVersion = null)
  125. {
  126. var data = new Dictionary<string, string> { { "key", _securityManager.SupporterKey }, { "mac", _networkManager.GetMacAddress() } };
  127. using (var json = await _httpClient.Post(Constants.Constants.MbAdminUrl + "service/package/retrieveall", data, cancellationToken).ConfigureAwait(false))
  128. {
  129. cancellationToken.ThrowIfCancellationRequested();
  130. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  131. return FilterPackages(packages, packageType, applicationVersion);
  132. }
  133. }
  134. /// <summary>
  135. /// Gets all available packages.
  136. /// </summary>
  137. /// <param name="cancellationToken">The cancellation token.</param>
  138. /// <param name="packageType">Type of the package.</param>
  139. /// <param name="applicationVersion">The application version.</param>
  140. /// <returns>Task{List{PackageInfo}}.</returns>
  141. public async Task<IEnumerable<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken,
  142. PackageType? packageType = null,
  143. Version applicationVersion = null)
  144. {
  145. using (var json = await _httpClient.Get(Constants.Constants.MbAdminUrl + "service/MB3Packages.json", cancellationToken).ConfigureAwait(false))
  146. {
  147. cancellationToken.ThrowIfCancellationRequested();
  148. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  149. return FilterPackages(packages, packageType, applicationVersion);
  150. }
  151. }
  152. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages, PackageType? packageType, Version applicationVersion)
  153. {
  154. foreach (var package in packages)
  155. {
  156. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  157. .OrderByDescending(v => v.version).ToList();
  158. }
  159. if (packageType.HasValue)
  160. {
  161. packages = packages.Where(p => p.type == packageType.Value).ToList();
  162. }
  163. // If an app version was supplied, filter the versions for each package to only include supported versions
  164. if (applicationVersion != null)
  165. {
  166. foreach (var package in packages)
  167. {
  168. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  169. }
  170. }
  171. // Remove packages with no versions
  172. packages = packages.Where(p => p.versions.Any()).ToList();
  173. return packages;
  174. }
  175. /// <summary>
  176. /// Determines whether [is package version up to date] [the specified package version info].
  177. /// </summary>
  178. /// <param name="packageVersionInfo">The package version info.</param>
  179. /// <param name="applicationVersion">The application version.</param>
  180. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  181. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version applicationVersion)
  182. {
  183. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  184. {
  185. return true;
  186. }
  187. Version requiredVersion;
  188. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && applicationVersion >= requiredVersion;
  189. }
  190. /// <summary>
  191. /// Gets the package.
  192. /// </summary>
  193. /// <param name="name">The name.</param>
  194. /// <param name="classification">The classification.</param>
  195. /// <param name="version">The version.</param>
  196. /// <returns>Task{PackageVersionInfo}.</returns>
  197. public async Task<PackageVersionInfo> GetPackage(string name, PackageVersionClass classification, Version version)
  198. {
  199. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  200. var package = packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  201. if (package == null)
  202. {
  203. return null;
  204. }
  205. return package.versions.FirstOrDefault(v => v.version.Equals(version) && v.classification == classification);
  206. }
  207. /// <summary>
  208. /// Gets the latest compatible version.
  209. /// </summary>
  210. /// <param name="name">The name.</param>
  211. /// <param name="classification">The classification.</param>
  212. /// <returns>Task{PackageVersionInfo}.</returns>
  213. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, PackageVersionClass classification = PackageVersionClass.Release)
  214. {
  215. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  216. return GetLatestCompatibleVersion(packages, name, classification);
  217. }
  218. /// <summary>
  219. /// Gets the latest compatible version.
  220. /// </summary>
  221. /// <param name="availablePackages">The available packages.</param>
  222. /// <param name="name">The name.</param>
  223. /// <param name="classification">The classification.</param>
  224. /// <returns>PackageVersionInfo.</returns>
  225. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, PackageVersionClass classification = PackageVersionClass.Release)
  226. {
  227. var package = availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  228. if (package == null)
  229. {
  230. return null;
  231. }
  232. return package.versions
  233. .OrderByDescending(v => v.version)
  234. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, _applicationHost.ApplicationVersion));
  235. }
  236. /// <summary>
  237. /// Gets the available plugin updates including registration information for each one.
  238. /// Used with API and catalog.
  239. /// </summary>
  240. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  241. /// <param name="cancellationToken">The cancellation token.</param>
  242. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  243. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  244. {
  245. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  246. return FilterCatalog(catalog, withAutoUpdateEnabled);
  247. }
  248. /// <summary>
  249. /// Gets the available plugin updates from a static resource - no registration information.
  250. /// Used for update checks.
  251. /// </summary>
  252. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  253. /// <param name="cancellationToken">The cancellation token.</param>
  254. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  255. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdatesWithoutRegistrationInfo(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  256. {
  257. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  258. return FilterCatalog(catalog, withAutoUpdateEnabled);
  259. }
  260. protected IEnumerable<PackageVersionInfo> FilterCatalog(IEnumerable<PackageInfo> catalog, bool withAutoUpdateEnabled)
  261. {
  262. var plugins = _applicationHost.Plugins;
  263. if (withAutoUpdateEnabled)
  264. {
  265. plugins = plugins.Where(p => p.Configuration.EnableAutoUpdate);
  266. }
  267. // Figure out what needs to be installed
  268. return plugins.Select(p =>
  269. {
  270. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Configuration.UpdateClass);
  271. return latestPluginInfo != null && latestPluginInfo.version > p.Version ? latestPluginInfo : null;
  272. }).Where(p => !CompletedInstallations.Any(i => string.Equals(i.Name, p.name, StringComparison.OrdinalIgnoreCase)))
  273. .Where(p => p != null && !string.IsNullOrWhiteSpace(p.sourceUrl));
  274. }
  275. /// <summary>
  276. /// Installs the package.
  277. /// </summary>
  278. /// <param name="package">The package.</param>
  279. /// <param name="progress">The progress.</param>
  280. /// <param name="cancellationToken">The cancellation token.</param>
  281. /// <returns>Task.</returns>
  282. /// <exception cref="System.ArgumentNullException">package</exception>
  283. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  284. {
  285. if (package == null)
  286. {
  287. throw new ArgumentNullException("package");
  288. }
  289. if (progress == null)
  290. {
  291. throw new ArgumentNullException("progress");
  292. }
  293. if (cancellationToken == null)
  294. {
  295. throw new ArgumentNullException("cancellationToken");
  296. }
  297. var installationInfo = new InstallationInfo
  298. {
  299. Id = Guid.NewGuid(),
  300. Name = package.name,
  301. UpdateClass = package.classification,
  302. Version = package.versionStr
  303. };
  304. var innerCancellationTokenSource = new CancellationTokenSource();
  305. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  306. // Add it to the in-progress list
  307. lock (CurrentInstallations)
  308. {
  309. CurrentInstallations.Add(tuple);
  310. }
  311. var innerProgress = new ActionableProgress<double>();
  312. // Whenever the progress updates, update the outer progress object and InstallationInfo
  313. innerProgress.RegisterAction(percent =>
  314. {
  315. progress.Report(percent);
  316. installationInfo.PercentComplete = percent;
  317. });
  318. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  319. var installationEventArgs = new InstallationEventArgs
  320. {
  321. InstallationInfo = installationInfo,
  322. PackageVersionInfo = package
  323. };
  324. EventHelper.QueueEventIfNotNull(PackageInstalling, this, installationEventArgs, _logger);
  325. try
  326. {
  327. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  328. lock (CurrentInstallations)
  329. {
  330. CurrentInstallations.Remove(tuple);
  331. }
  332. CompletedInstallations.Add(installationInfo);
  333. EventHelper.QueueEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
  334. }
  335. catch (OperationCanceledException)
  336. {
  337. lock (CurrentInstallations)
  338. {
  339. CurrentInstallations.Remove(tuple);
  340. }
  341. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  342. EventHelper.QueueEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
  343. throw;
  344. }
  345. catch (Exception ex)
  346. {
  347. _logger.ErrorException("Package installation failed", ex);
  348. lock (CurrentInstallations)
  349. {
  350. CurrentInstallations.Remove(tuple);
  351. }
  352. EventHelper.QueueEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
  353. {
  354. InstallationInfo = installationInfo,
  355. Exception = ex
  356. }, _logger);
  357. throw;
  358. }
  359. finally
  360. {
  361. // Dispose the progress object and remove the installation from the in-progress list
  362. innerProgress.Dispose();
  363. tuple.Item2.Dispose();
  364. }
  365. }
  366. /// <summary>
  367. /// Installs the package internal.
  368. /// </summary>
  369. /// <param name="package">The package.</param>
  370. /// <param name="progress">The progress.</param>
  371. /// <param name="cancellationToken">The cancellation token.</param>
  372. /// <returns>Task.</returns>
  373. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  374. {
  375. // Do the install
  376. await PerformPackageInstallation(progress, package, cancellationToken).ConfigureAwait(false);
  377. // Do plugin-specific processing
  378. if (!(Path.GetExtension(package.targetFilename) ?? "").Equals(".zip", StringComparison.OrdinalIgnoreCase))
  379. {
  380. // Set last update time if we were installed before
  381. var plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  382. if (plugin != null)
  383. {
  384. OnPluginUpdated(plugin, package);
  385. }
  386. else
  387. {
  388. OnPluginInstalled(package);
  389. }
  390. }
  391. }
  392. private async Task PerformPackageInstallation(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  393. {
  394. // Target based on if it is an archive or single assembly
  395. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  396. var isArchive = string.Equals(Path.GetExtension(package.targetFilename), ".zip", StringComparison.OrdinalIgnoreCase);
  397. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  398. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  399. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  400. {
  401. Url = package.sourceUrl,
  402. CancellationToken = cancellationToken,
  403. Progress = progress
  404. }).ConfigureAwait(false);
  405. cancellationToken.ThrowIfCancellationRequested();
  406. // Validate with a checksum
  407. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  408. {
  409. using (var crypto = new MD5CryptoServiceProvider())
  410. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  411. {
  412. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  413. if (check != package.checksum)
  414. {
  415. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  416. }
  417. }
  418. }
  419. cancellationToken.ThrowIfCancellationRequested();
  420. // Success - move it to the real target
  421. try
  422. {
  423. File.Copy(tempFile, target, true);
  424. //If it is an archive - write out a version file so we know what it is
  425. if (isArchive)
  426. {
  427. File.WriteAllText(target + ".ver", package.versionStr);
  428. }
  429. }
  430. catch (IOException e)
  431. {
  432. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  433. throw;
  434. }
  435. try
  436. {
  437. File.Delete(tempFile);
  438. }
  439. catch (IOException e)
  440. {
  441. // Don't fail because of this
  442. _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
  443. }
  444. }
  445. /// <summary>
  446. /// Uninstalls a plugin
  447. /// </summary>
  448. /// <param name="plugin">The plugin.</param>
  449. /// <exception cref="System.ArgumentException"></exception>
  450. public void UninstallPlugin(IPlugin plugin)
  451. {
  452. plugin.OnUninstalling();
  453. // Remove it the quick way for now
  454. _applicationHost.RemovePlugin(plugin);
  455. File.Delete(plugin.AssemblyFilePath);
  456. OnPluginUninstalled(plugin);
  457. _applicationHost.NotifyPendingRestart();
  458. }
  459. /// <summary>
  460. /// Releases unmanaged and - optionally - managed resources.
  461. /// </summary>
  462. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  463. protected virtual void Dispose(bool dispose)
  464. {
  465. if (dispose)
  466. {
  467. lock (CurrentInstallations)
  468. {
  469. foreach (var tuple in CurrentInstallations)
  470. {
  471. tuple.Item2.Dispose();
  472. }
  473. CurrentInstallations.Clear();
  474. }
  475. }
  476. }
  477. public void Dispose()
  478. {
  479. Dispose(true);
  480. }
  481. }
  482. }