InstallationManager.cs 20 KB

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