InstallationManager.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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 MediaBrowser.Common.IO;
  22. using MediaBrowser.Model.IO;
  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. /// <returns>Task{List{PackageInfo}}.</returns>
  133. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  134. bool withRegistration = true,
  135. string packageType = null,
  136. Version applicationVersion = null)
  137. {
  138. var data = new Dictionary<string, string>
  139. {
  140. { "key", _securityManager.SupporterKey },
  141. { "mac", _applicationHost.SystemId },
  142. { "systemid", _applicationHost.SystemId }
  143. };
  144. if (withRegistration)
  145. {
  146. using (var json = await _httpClient.Post(MbAdmin.HttpsUrl + "service/package/retrieveall", data, cancellationToken).ConfigureAwait(false))
  147. {
  148. cancellationToken.ThrowIfCancellationRequested();
  149. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  150. return FilterPackages(packages, packageType, applicationVersion);
  151. }
  152. }
  153. else
  154. {
  155. var packages = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  156. return FilterPackages(packages.ToList(), packageType, applicationVersion);
  157. }
  158. }
  159. private DateTime _lastPackageUpdateTime;
  160. /// <summary>
  161. /// Gets all available packages.
  162. /// </summary>
  163. /// <param name="cancellationToken">The cancellation token.</param>
  164. /// <returns>Task{List{PackageInfo}}.</returns>
  165. public async Task<IEnumerable<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken)
  166. {
  167. _logger.Info("Opening {0}", PackageCachePath);
  168. try
  169. {
  170. using (var stream = _fileSystem.OpenRead(PackageCachePath))
  171. {
  172. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(stream).ToList();
  173. if (DateTime.UtcNow - _lastPackageUpdateTime > GetCacheLength())
  174. {
  175. UpdateCachedPackages(CancellationToken.None, false);
  176. }
  177. return packages;
  178. }
  179. }
  180. catch (Exception)
  181. {
  182. }
  183. _lastPackageUpdateTime = DateTime.MinValue;
  184. await UpdateCachedPackages(cancellationToken, true).ConfigureAwait(false);
  185. using (var stream = _fileSystem.OpenRead(PackageCachePath))
  186. {
  187. return _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(stream).ToList();
  188. }
  189. }
  190. private string PackageCachePath
  191. {
  192. get { return Path.Combine(_appPaths.CachePath, "serverpackages.json"); }
  193. }
  194. private readonly SemaphoreSlim _updateSemaphore = new SemaphoreSlim(1, 1);
  195. private async Task UpdateCachedPackages(CancellationToken cancellationToken, bool throwErrors)
  196. {
  197. await _updateSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  198. try
  199. {
  200. if (DateTime.UtcNow - _lastPackageUpdateTime < GetCacheLength())
  201. {
  202. return;
  203. }
  204. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  205. {
  206. Url = MbAdmin.HttpUrl + "service/MB3Packages.json",
  207. CancellationToken = cancellationToken,
  208. Progress = new Progress<Double>()
  209. }).ConfigureAwait(false);
  210. _fileSystem.CreateDirectory(Path.GetDirectoryName(PackageCachePath));
  211. _fileSystem.CopyFile(tempFile, PackageCachePath, true);
  212. _lastPackageUpdateTime = DateTime.UtcNow;
  213. }
  214. catch (Exception ex)
  215. {
  216. _logger.ErrorException("Error updating package cache", ex);
  217. if (throwErrors)
  218. {
  219. throw;
  220. }
  221. }
  222. finally
  223. {
  224. _updateSemaphore.Release();
  225. }
  226. }
  227. private TimeSpan GetCacheLength()
  228. {
  229. switch (_config.CommonConfiguration.SystemUpdateLevel)
  230. {
  231. case PackageVersionClass.Beta:
  232. return TimeSpan.FromMinutes(30);
  233. case PackageVersionClass.Dev:
  234. return TimeSpan.FromMinutes(3);
  235. default:
  236. return TimeSpan.FromHours(24);
  237. }
  238. }
  239. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages)
  240. {
  241. foreach (var package in packages)
  242. {
  243. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  244. .OrderByDescending(GetPackageVersion).ToList();
  245. }
  246. // Remove packages with no versions
  247. packages = packages.Where(p => p.versions.Any()).ToList();
  248. return packages;
  249. }
  250. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages, string packageType, Version applicationVersion)
  251. {
  252. foreach (var package in packages)
  253. {
  254. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  255. .OrderByDescending(GetPackageVersion).ToList();
  256. }
  257. if (!string.IsNullOrWhiteSpace(packageType))
  258. {
  259. packages = packages.Where(p => string.Equals(p.type, packageType, StringComparison.OrdinalIgnoreCase)).ToList();
  260. }
  261. // If an app version was supplied, filter the versions for each package to only include supported versions
  262. if (applicationVersion != null)
  263. {
  264. foreach (var package in packages)
  265. {
  266. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  267. }
  268. }
  269. // Remove packages with no versions
  270. packages = packages.Where(p => p.versions.Any()).ToList();
  271. return packages;
  272. }
  273. /// <summary>
  274. /// Determines whether [is package version up to date] [the specified package version info].
  275. /// </summary>
  276. /// <param name="packageVersionInfo">The package version info.</param>
  277. /// <param name="currentServerVersion">The current server version.</param>
  278. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  279. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion)
  280. {
  281. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  282. {
  283. return true;
  284. }
  285. Version requiredVersion;
  286. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && currentServerVersion >= requiredVersion;
  287. }
  288. /// <summary>
  289. /// Gets the package.
  290. /// </summary>
  291. /// <param name="name">The name.</param>
  292. /// <param name="guid">The assembly guid</param>
  293. /// <param name="classification">The classification.</param>
  294. /// <param name="version">The version.</param>
  295. /// <returns>Task{PackageVersionInfo}.</returns>
  296. public async Task<PackageVersionInfo> GetPackage(string name, string guid, PackageVersionClass classification, Version version)
  297. {
  298. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  299. var package = packages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  300. ?? packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  301. if (package == null)
  302. {
  303. return null;
  304. }
  305. return package.versions.FirstOrDefault(v => GetPackageVersion(v).Equals(version) && v.classification == classification);
  306. }
  307. /// <summary>
  308. /// Gets the latest compatible version.
  309. /// </summary>
  310. /// <param name="name">The name.</param>
  311. /// <param name="guid">The assembly guid if this is a plug-in</param>
  312. /// <param name="currentServerVersion">The current server version.</param>
  313. /// <param name="classification">The classification.</param>
  314. /// <returns>Task{PackageVersionInfo}.</returns>
  315. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  316. {
  317. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  318. return GetLatestCompatibleVersion(packages, name, guid, currentServerVersion, classification);
  319. }
  320. /// <summary>
  321. /// Gets the latest compatible version.
  322. /// </summary>
  323. /// <param name="availablePackages">The available packages.</param>
  324. /// <param name="name">The name.</param>
  325. /// <param name="currentServerVersion">The current server version.</param>
  326. /// <param name="classification">The classification.</param>
  327. /// <returns>PackageVersionInfo.</returns>
  328. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  329. {
  330. var package = availablePackages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  331. ?? availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  332. if (package == null)
  333. {
  334. return null;
  335. }
  336. return package.versions
  337. .OrderByDescending(GetPackageVersion)
  338. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
  339. }
  340. /// <summary>
  341. /// Gets the available plugin updates.
  342. /// </summary>
  343. /// <param name="applicationVersion">The current server version.</param>
  344. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  345. /// <param name="cancellationToken">The cancellation token.</param>
  346. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  347. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  348. {
  349. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  350. var plugins = _applicationHost.Plugins.ToList();
  351. if (withAutoUpdateEnabled)
  352. {
  353. plugins = plugins
  354. .Where(p => _config.CommonConfiguration.EnableAutoUpdate)
  355. .ToList();
  356. }
  357. // Figure out what needs to be installed
  358. var packages = plugins.Select(p =>
  359. {
  360. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Id.ToString(), applicationVersion, _config.CommonConfiguration.SystemUpdateLevel);
  361. return latestPluginInfo != null && GetPackageVersion(latestPluginInfo) > p.Version ? latestPluginInfo : null;
  362. }).Where(i => i != null).ToList();
  363. return packages
  364. .Where(p => !string.IsNullOrWhiteSpace(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.AssemblyGuid, p.guid, StringComparison.OrdinalIgnoreCase)));
  365. }
  366. /// <summary>
  367. /// Installs the package.
  368. /// </summary>
  369. /// <param name="package">The package.</param>
  370. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  371. /// <param name="progress">The progress.</param>
  372. /// <param name="cancellationToken">The cancellation token.</param>
  373. /// <returns>Task.</returns>
  374. /// <exception cref="System.ArgumentNullException">package</exception>
  375. public async Task InstallPackage(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
  376. {
  377. if (package == null)
  378. {
  379. throw new ArgumentNullException("package");
  380. }
  381. if (progress == null)
  382. {
  383. throw new ArgumentNullException("progress");
  384. }
  385. var installationInfo = new InstallationInfo
  386. {
  387. Id = Guid.NewGuid().ToString("N"),
  388. Name = package.name,
  389. AssemblyGuid = package.guid,
  390. UpdateClass = package.classification,
  391. Version = package.versionStr
  392. };
  393. var innerCancellationTokenSource = new CancellationTokenSource();
  394. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  395. // Add it to the in-progress list
  396. lock (CurrentInstallations)
  397. {
  398. CurrentInstallations.Add(tuple);
  399. }
  400. var innerProgress = new ActionableProgress<double>();
  401. // Whenever the progress updates, update the outer progress object and InstallationInfo
  402. innerProgress.RegisterAction(percent =>
  403. {
  404. progress.Report(percent);
  405. installationInfo.PercentComplete = percent;
  406. });
  407. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  408. var installationEventArgs = new InstallationEventArgs
  409. {
  410. InstallationInfo = installationInfo,
  411. PackageVersionInfo = package
  412. };
  413. EventHelper.FireEventIfNotNull(PackageInstalling, this, installationEventArgs, _logger);
  414. try
  415. {
  416. await InstallPackageInternal(package, isPlugin, innerProgress, linkedToken).ConfigureAwait(false);
  417. lock (CurrentInstallations)
  418. {
  419. CurrentInstallations.Remove(tuple);
  420. }
  421. progress.Report(100);
  422. CompletedInstallations.Add(installationInfo);
  423. EventHelper.FireEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
  424. }
  425. catch (OperationCanceledException)
  426. {
  427. lock (CurrentInstallations)
  428. {
  429. CurrentInstallations.Remove(tuple);
  430. }
  431. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  432. EventHelper.FireEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
  433. throw;
  434. }
  435. catch (Exception ex)
  436. {
  437. _logger.ErrorException("Package installation failed", ex);
  438. lock (CurrentInstallations)
  439. {
  440. CurrentInstallations.Remove(tuple);
  441. }
  442. EventHelper.FireEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
  443. {
  444. InstallationInfo = installationInfo,
  445. Exception = ex
  446. }, _logger);
  447. throw;
  448. }
  449. finally
  450. {
  451. // Dispose the progress object and remove the installation from the in-progress list
  452. innerProgress.Dispose();
  453. tuple.Item2.Dispose();
  454. }
  455. }
  456. /// <summary>
  457. /// Installs the package internal.
  458. /// </summary>
  459. /// <param name="package">The package.</param>
  460. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  461. /// <param name="progress">The progress.</param>
  462. /// <param name="cancellationToken">The cancellation token.</param>
  463. /// <returns>Task.</returns>
  464. private async Task InstallPackageInternal(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
  465. {
  466. // Do the install
  467. await PerformPackageInstallation(progress, package, cancellationToken).ConfigureAwait(false);
  468. // Do plugin-specific processing
  469. if (isPlugin)
  470. {
  471. // Set last update time if we were installed before
  472. var plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
  473. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  474. if (plugin != null)
  475. {
  476. OnPluginUpdated(plugin, package);
  477. }
  478. else
  479. {
  480. OnPluginInstalled(package);
  481. }
  482. }
  483. }
  484. private async Task PerformPackageInstallation(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  485. {
  486. // Target based on if it is an archive or single assembly
  487. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  488. var extension = Path.GetExtension(package.targetFilename);
  489. var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
  490. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  491. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  492. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  493. {
  494. Url = package.sourceUrl,
  495. CancellationToken = cancellationToken,
  496. Progress = progress
  497. }).ConfigureAwait(false);
  498. cancellationToken.ThrowIfCancellationRequested();
  499. // Validate with a checksum
  500. var packageChecksum = string.IsNullOrWhiteSpace(package.checksum) ? Guid.Empty : new Guid(package.checksum);
  501. if (packageChecksum != Guid.Empty) // support for legacy uploads for now
  502. {
  503. using (var crypto = new MD5CryptoServiceProvider())
  504. using (var stream = new BufferedStream(_fileSystem.OpenRead(tempFile), 100000))
  505. {
  506. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  507. if (check != packageChecksum)
  508. {
  509. throw new ApplicationException(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. File.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. }