InstallationManager.cs 19 KB

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