InstallationManager.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. private ConcurrentBag<InstallationInfo> CompletedInstallationsInternal { get; set; }
  41. public IEnumerable<InstallationInfo> CompletedInstallations {
  42. get { return CompletedInstallationsInternal; }
  43. }
  44. #region PluginUninstalled Event
  45. /// <summary>
  46. /// Occurs when [plugin uninstalled].
  47. /// </summary>
  48. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  49. /// <summary>
  50. /// Called when [plugin uninstalled].
  51. /// </summary>
  52. /// <param name="plugin">The plugin.</param>
  53. private void OnPluginUninstalled(IPlugin plugin)
  54. {
  55. EventHelper.FireEventIfNotNull(PluginUninstalled, this, new GenericEventArgs<IPlugin> { Argument = plugin }, _logger);
  56. }
  57. #endregion
  58. #region PluginUpdated Event
  59. /// <summary>
  60. /// Occurs when [plugin updated].
  61. /// </summary>
  62. public event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
  63. /// <summary>
  64. /// Called when [plugin updated].
  65. /// </summary>
  66. /// <param name="plugin">The plugin.</param>
  67. /// <param name="newVersion">The new version.</param>
  68. private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
  69. {
  70. _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.versionStr ?? string.Empty, newVersion.classification);
  71. EventHelper.FireEventIfNotNull(PluginUpdated, this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) }, _logger);
  72. _applicationHost.NotifyPendingRestart();
  73. }
  74. #endregion
  75. #region PluginInstalled Event
  76. /// <summary>
  77. /// Occurs when [plugin updated].
  78. /// </summary>
  79. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  80. /// <summary>
  81. /// Called when [plugin installed].
  82. /// </summary>
  83. /// <param name="package">The package.</param>
  84. private void OnPluginInstalled(PackageVersionInfo package)
  85. {
  86. _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  87. EventHelper.FireEventIfNotNull(PluginInstalled, this, new GenericEventArgs<PackageVersionInfo> { Argument = package }, _logger);
  88. _applicationHost.NotifyPendingRestart();
  89. }
  90. #endregion
  91. /// <summary>
  92. /// The _logger
  93. /// </summary>
  94. private readonly ILogger _logger;
  95. private readonly IApplicationPaths _appPaths;
  96. private readonly IHttpClient _httpClient;
  97. private readonly IJsonSerializer _jsonSerializer;
  98. private readonly ISecurityManager _securityManager;
  99. private readonly IConfigurationManager _config;
  100. private readonly IFileSystem _fileSystem;
  101. /// <summary>
  102. /// Gets the application host.
  103. /// </summary>
  104. /// <value>The application host.</value>
  105. private readonly IApplicationHost _applicationHost;
  106. private readonly ICryptoProvider _cryptographyProvider;
  107. public InstallationManager(ILogger logger, IApplicationHost appHost, IApplicationPaths appPaths, IHttpClient httpClient, IJsonSerializer jsonSerializer, ISecurityManager securityManager, IConfigurationManager config, IFileSystem fileSystem, ICryptoProvider cryptographyProvider)
  108. {
  109. if (logger == null)
  110. {
  111. throw new ArgumentNullException("logger");
  112. }
  113. CurrentInstallations = new List<Tuple<InstallationInfo, CancellationTokenSource>>();
  114. CompletedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
  115. _applicationHost = appHost;
  116. _appPaths = appPaths;
  117. _httpClient = httpClient;
  118. _jsonSerializer = jsonSerializer;
  119. _securityManager = securityManager;
  120. _config = config;
  121. _fileSystem = fileSystem;
  122. _cryptographyProvider = cryptographyProvider;
  123. _logger = logger;
  124. }
  125. private Version GetPackageVersion(PackageVersionInfo version)
  126. {
  127. return new Version(ValueOrDefault(version.versionStr, "0.0.0.1"));
  128. }
  129. private static string ValueOrDefault(string str, string def)
  130. {
  131. return string.IsNullOrEmpty(str) ? def : str;
  132. }
  133. /// <summary>
  134. /// Gets all available packages.
  135. /// </summary>
  136. /// <returns>Task{List{PackageInfo}}.</returns>
  137. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  138. bool withRegistration = true,
  139. string 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("https://www.mb3admin.com/admin/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. _logger.Info("Opening {0}", PackageCachePath);
  172. try
  173. {
  174. using (var stream = _fileSystem.OpenRead(PackageCachePath))
  175. {
  176. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(stream).ToList();
  177. if (DateTime.UtcNow - _lastPackageUpdateTime > GetCacheLength())
  178. {
  179. UpdateCachedPackages(CancellationToken.None, false);
  180. }
  181. return packages;
  182. }
  183. }
  184. catch (Exception)
  185. {
  186. }
  187. _lastPackageUpdateTime = DateTime.MinValue;
  188. await UpdateCachedPackages(cancellationToken, true).ConfigureAwait(false);
  189. using (var stream = _fileSystem.OpenRead(PackageCachePath))
  190. {
  191. return _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(stream).ToList();
  192. }
  193. }
  194. private string PackageCachePath
  195. {
  196. get { return Path.Combine(_appPaths.CachePath, "serverpackages.json"); }
  197. }
  198. private readonly SemaphoreSlim _updateSemaphore = new SemaphoreSlim(1, 1);
  199. private async Task UpdateCachedPackages(CancellationToken cancellationToken, bool throwErrors)
  200. {
  201. await _updateSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  202. try
  203. {
  204. if (DateTime.UtcNow - _lastPackageUpdateTime < GetCacheLength())
  205. {
  206. return;
  207. }
  208. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  209. {
  210. Url = "https://www.mb3admin.com/admin/service/MB3Packages.json",
  211. CancellationToken = cancellationToken,
  212. Progress = new Progress<Double>()
  213. }).ConfigureAwait(false);
  214. _fileSystem.CreateDirectory(Path.GetDirectoryName(PackageCachePath));
  215. _fileSystem.CopyFile(tempFile, PackageCachePath, true);
  216. _lastPackageUpdateTime = DateTime.UtcNow;
  217. }
  218. catch (Exception ex)
  219. {
  220. _logger.ErrorException("Error updating package cache", ex);
  221. if (throwErrors)
  222. {
  223. throw;
  224. }
  225. }
  226. finally
  227. {
  228. _updateSemaphore.Release();
  229. }
  230. }
  231. private TimeSpan GetCacheLength()
  232. {
  233. switch (_config.CommonConfiguration.SystemUpdateLevel)
  234. {
  235. case PackageVersionClass.Beta:
  236. return TimeSpan.FromMinutes(30);
  237. case PackageVersionClass.Dev:
  238. return TimeSpan.FromMinutes(3);
  239. default:
  240. return TimeSpan.FromHours(24);
  241. }
  242. }
  243. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages)
  244. {
  245. foreach (var package in packages)
  246. {
  247. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  248. .OrderByDescending(GetPackageVersion).ToList();
  249. }
  250. // Remove packages with no versions
  251. packages = packages.Where(p => p.versions.Any()).ToList();
  252. return packages;
  253. }
  254. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages, string packageType, Version applicationVersion)
  255. {
  256. foreach (var package in packages)
  257. {
  258. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  259. .OrderByDescending(GetPackageVersion).ToList();
  260. }
  261. if (!string.IsNullOrWhiteSpace(packageType))
  262. {
  263. packages = packages.Where(p => string.Equals(p.type, packageType, StringComparison.OrdinalIgnoreCase)).ToList();
  264. }
  265. // If an app version was supplied, filter the versions for each package to only include supported versions
  266. if (applicationVersion != null)
  267. {
  268. foreach (var package in packages)
  269. {
  270. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  271. }
  272. }
  273. // Remove packages with no versions
  274. packages = packages.Where(p => p.versions.Any()).ToList();
  275. return packages;
  276. }
  277. /// <summary>
  278. /// Determines whether [is package version up to date] [the specified package version info].
  279. /// </summary>
  280. /// <param name="packageVersionInfo">The package version info.</param>
  281. /// <param name="currentServerVersion">The current server version.</param>
  282. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  283. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion)
  284. {
  285. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  286. {
  287. return true;
  288. }
  289. Version requiredVersion;
  290. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && currentServerVersion >= requiredVersion;
  291. }
  292. /// <summary>
  293. /// Gets the package.
  294. /// </summary>
  295. /// <param name="name">The name.</param>
  296. /// <param name="guid">The assembly guid</param>
  297. /// <param name="classification">The classification.</param>
  298. /// <param name="version">The version.</param>
  299. /// <returns>Task{PackageVersionInfo}.</returns>
  300. public async Task<PackageVersionInfo> GetPackage(string name, string guid, PackageVersionClass classification, Version version)
  301. {
  302. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  303. var package = packages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  304. ?? packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  305. if (package == null)
  306. {
  307. return null;
  308. }
  309. return package.versions.FirstOrDefault(v => GetPackageVersion(v).Equals(version) && v.classification == classification);
  310. }
  311. /// <summary>
  312. /// Gets the latest compatible version.
  313. /// </summary>
  314. /// <param name="name">The name.</param>
  315. /// <param name="guid">The assembly guid if this is a plug-in</param>
  316. /// <param name="currentServerVersion">The current server version.</param>
  317. /// <param name="classification">The classification.</param>
  318. /// <returns>Task{PackageVersionInfo}.</returns>
  319. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  320. {
  321. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  322. return GetLatestCompatibleVersion(packages, name, guid, currentServerVersion, classification);
  323. }
  324. /// <summary>
  325. /// Gets the latest compatible version.
  326. /// </summary>
  327. /// <param name="availablePackages">The available packages.</param>
  328. /// <param name="name">The name.</param>
  329. /// <param name="currentServerVersion">The current server version.</param>
  330. /// <param name="classification">The classification.</param>
  331. /// <returns>PackageVersionInfo.</returns>
  332. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  333. {
  334. var package = availablePackages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  335. ?? availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  336. if (package == null)
  337. {
  338. return null;
  339. }
  340. return package.versions
  341. .OrderByDescending(GetPackageVersion)
  342. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
  343. }
  344. /// <summary>
  345. /// Gets the available plugin updates.
  346. /// </summary>
  347. /// <param name="applicationVersion">The current server version.</param>
  348. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  349. /// <param name="cancellationToken">The cancellation token.</param>
  350. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  351. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  352. {
  353. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  354. var plugins = _applicationHost.Plugins.ToList();
  355. if (withAutoUpdateEnabled)
  356. {
  357. plugins = plugins
  358. .Where(p => _config.CommonConfiguration.EnableAutoUpdate)
  359. .ToList();
  360. }
  361. // Figure out what needs to be installed
  362. var packages = plugins.Select(p =>
  363. {
  364. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Id.ToString(), applicationVersion, _config.CommonConfiguration.SystemUpdateLevel);
  365. return latestPluginInfo != null && GetPackageVersion(latestPluginInfo) > p.Version ? latestPluginInfo : null;
  366. }).Where(i => i != null).ToList();
  367. return packages
  368. .Where(p => !string.IsNullOrWhiteSpace(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.AssemblyGuid, p.guid, StringComparison.OrdinalIgnoreCase)));
  369. }
  370. /// <summary>
  371. /// Installs the package.
  372. /// </summary>
  373. /// <param name="package">The package.</param>
  374. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  375. /// <param name="progress">The progress.</param>
  376. /// <param name="cancellationToken">The cancellation token.</param>
  377. /// <returns>Task.</returns>
  378. /// <exception cref="System.ArgumentNullException">package</exception>
  379. public async Task InstallPackage(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
  380. {
  381. if (package == null)
  382. {
  383. throw new ArgumentNullException("package");
  384. }
  385. if (progress == null)
  386. {
  387. throw new ArgumentNullException("progress");
  388. }
  389. var installationInfo = new InstallationInfo
  390. {
  391. Id = Guid.NewGuid().ToString("N"),
  392. Name = package.name,
  393. AssemblyGuid = package.guid,
  394. UpdateClass = package.classification,
  395. Version = package.versionStr
  396. };
  397. var innerCancellationTokenSource = new CancellationTokenSource();
  398. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  399. // Add it to the in-progress list
  400. lock (CurrentInstallations)
  401. {
  402. CurrentInstallations.Add(tuple);
  403. }
  404. var innerProgress = new ActionableProgress<double>();
  405. // Whenever the progress updates, update the outer progress object and InstallationInfo
  406. innerProgress.RegisterAction(percent =>
  407. {
  408. progress.Report(percent);
  409. installationInfo.PercentComplete = percent;
  410. });
  411. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  412. var installationEventArgs = new InstallationEventArgs
  413. {
  414. InstallationInfo = installationInfo,
  415. PackageVersionInfo = package
  416. };
  417. EventHelper.FireEventIfNotNull(PackageInstalling, this, installationEventArgs, _logger);
  418. try
  419. {
  420. await InstallPackageInternal(package, isPlugin, innerProgress, linkedToken).ConfigureAwait(false);
  421. lock (CurrentInstallations)
  422. {
  423. CurrentInstallations.Remove(tuple);
  424. }
  425. progress.Report(100);
  426. CompletedInstallationsInternal.Add(installationInfo);
  427. EventHelper.FireEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
  428. }
  429. catch (OperationCanceledException)
  430. {
  431. lock (CurrentInstallations)
  432. {
  433. CurrentInstallations.Remove(tuple);
  434. }
  435. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  436. EventHelper.FireEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
  437. throw;
  438. }
  439. catch (Exception ex)
  440. {
  441. _logger.ErrorException("Package installation failed", ex);
  442. lock (CurrentInstallations)
  443. {
  444. CurrentInstallations.Remove(tuple);
  445. }
  446. EventHelper.FireEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
  447. {
  448. InstallationInfo = installationInfo,
  449. Exception = ex
  450. }, _logger);
  451. throw;
  452. }
  453. finally
  454. {
  455. // Dispose the progress object and remove the installation from the in-progress list
  456. innerProgress.Dispose();
  457. tuple.Item2.Dispose();
  458. }
  459. }
  460. /// <summary>
  461. /// Installs the package internal.
  462. /// </summary>
  463. /// <param name="package">The package.</param>
  464. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  465. /// <param name="progress">The progress.</param>
  466. /// <param name="cancellationToken">The cancellation token.</param>
  467. /// <returns>Task.</returns>
  468. private async Task InstallPackageInternal(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
  469. {
  470. // Do the install
  471. await PerformPackageInstallation(progress, package, cancellationToken).ConfigureAwait(false);
  472. // Do plugin-specific processing
  473. if (isPlugin)
  474. {
  475. // Set last update time if we were installed before
  476. var plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
  477. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  478. if (plugin != null)
  479. {
  480. OnPluginUpdated(plugin, package);
  481. }
  482. else
  483. {
  484. OnPluginInstalled(package);
  485. }
  486. }
  487. }
  488. private async Task PerformPackageInstallation(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  489. {
  490. // Target based on if it is an archive or single assembly
  491. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  492. var extension = Path.GetExtension(package.targetFilename);
  493. var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
  494. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  495. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  496. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  497. {
  498. Url = package.sourceUrl,
  499. CancellationToken = cancellationToken,
  500. Progress = progress
  501. }).ConfigureAwait(false);
  502. cancellationToken.ThrowIfCancellationRequested();
  503. // Validate with a checksum
  504. var packageChecksum = string.IsNullOrWhiteSpace(package.checksum) ? Guid.Empty : new Guid(package.checksum);
  505. if (packageChecksum != Guid.Empty) // support for legacy uploads for now
  506. {
  507. using (var stream = _fileSystem.OpenRead(tempFile))
  508. {
  509. var check = Guid.Parse(BitConverter.ToString(_cryptographyProvider.ComputeMD5(stream)).Replace("-", String.Empty));
  510. if (check != packageChecksum)
  511. {
  512. throw new Exception(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. _fileSystem.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. }