InstallationManager.cs 27 KB

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