InstallationManager.cs 28 KB

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