InstallationManager.cs 27 KB

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