InstallationManager.cs 27 KB

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