InstallationManager.cs 27 KB

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