InstallationManager.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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<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<PackageInfo[]>(json);
  155. return FilterPackages(packages, packageType, applicationVersion);
  156. }
  157. }
  158. else
  159. {
  160. var packages = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  161. return FilterPackages(packages, 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<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<PackageInfo[]>(stream);
  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<PackageInfo[]>(stream);
  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 SimpleProgress<Double>()
  214. }).ConfigureAwait(false);
  215. _fileSystem.CreateDirectory(_fileSystem.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 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).ToArray();
  254. }
  255. // Remove packages with no versions
  256. return packages.Where(p => p.versions.Any()).ToArray();
  257. }
  258. protected PackageInfo[] FilterPackages(PackageInfo[] packages, string packageType, Version applicationVersion)
  259. {
  260. foreach (var package in packages)
  261. {
  262. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  263. .OrderByDescending(GetPackageVersion).ToArray();
  264. }
  265. if (!string.IsNullOrWhiteSpace(packageType))
  266. {
  267. packages = packages.Where(p => string.Equals(p.type, packageType, StringComparison.OrdinalIgnoreCase)).ToArray();
  268. }
  269. // If an app version was supplied, filter the versions for each package to only include supported versions
  270. if (applicationVersion != null)
  271. {
  272. foreach (var package in packages)
  273. {
  274. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToArray();
  275. }
  276. }
  277. // Remove packages with no versions
  278. return packages.Where(p => p.versions.Any()).ToArray();
  279. }
  280. /// <summary>
  281. /// Determines whether [is package version up to date] [the specified package version info].
  282. /// </summary>
  283. /// <param name="packageVersionInfo">The package version info.</param>
  284. /// <param name="currentServerVersion">The current server version.</param>
  285. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  286. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion)
  287. {
  288. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  289. {
  290. return true;
  291. }
  292. Version requiredVersion;
  293. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && currentServerVersion >= requiredVersion;
  294. }
  295. /// <summary>
  296. /// Gets the package.
  297. /// </summary>
  298. /// <param name="name">The name.</param>
  299. /// <param name="guid">The assembly guid</param>
  300. /// <param name="classification">The classification.</param>
  301. /// <param name="version">The version.</param>
  302. /// <returns>Task{PackageVersionInfo}.</returns>
  303. public async Task<PackageVersionInfo> GetPackage(string name, string guid, PackageVersionClass classification, Version version)
  304. {
  305. var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
  306. var package = packages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  307. ?? packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  308. if (package == null)
  309. {
  310. return null;
  311. }
  312. return package.versions.FirstOrDefault(v => GetPackageVersion(v).Equals(version) && v.classification == classification);
  313. }
  314. /// <summary>
  315. /// Gets the latest compatible version.
  316. /// </summary>
  317. /// <param name="name">The name.</param>
  318. /// <param name="guid">The assembly guid if this is a plug-in</param>
  319. /// <param name="currentServerVersion">The current server version.</param>
  320. /// <param name="classification">The classification.</param>
  321. /// <returns>Task{PackageVersionInfo}.</returns>
  322. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  323. {
  324. var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
  325. return GetLatestCompatibleVersion(packages, name, guid, currentServerVersion, classification);
  326. }
  327. /// <summary>
  328. /// Gets the latest compatible version.
  329. /// </summary>
  330. /// <param name="availablePackages">The available packages.</param>
  331. /// <param name="name">The name.</param>
  332. /// <param name="currentServerVersion">The current server version.</param>
  333. /// <param name="classification">The classification.</param>
  334. /// <returns>PackageVersionInfo.</returns>
  335. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  336. {
  337. var package = availablePackages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  338. ?? availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  339. if (package == null)
  340. {
  341. return null;
  342. }
  343. return package.versions
  344. .OrderByDescending(GetPackageVersion)
  345. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
  346. }
  347. /// <summary>
  348. /// Gets the available plugin updates.
  349. /// </summary>
  350. /// <param name="applicationVersion">The current server version.</param>
  351. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  352. /// <param name="cancellationToken">The cancellation token.</param>
  353. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  354. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  355. {
  356. if (!_config.CommonConfiguration.EnableAutoUpdate)
  357. {
  358. return new PackageVersionInfo[] { };
  359. }
  360. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  361. var systemUpdateLevel = GetSystemUpdateLevel();
  362. // Figure out what needs to be installed
  363. return _applicationHost.Plugins.Select(p =>
  364. {
  365. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Id.ToString(), applicationVersion, systemUpdateLevel);
  366. return latestPluginInfo != null && GetPackageVersion(latestPluginInfo) > p.Version ? latestPluginInfo : null;
  367. }).Where(i => i != null)
  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. CompletedInstallationsInternal.Add(installationInfo);
  426. EventHelper.FireEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
  427. }
  428. catch (OperationCanceledException)
  429. {
  430. lock (CurrentInstallations)
  431. {
  432. CurrentInstallations.Remove(tuple);
  433. }
  434. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  435. EventHelper.FireEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
  436. throw;
  437. }
  438. catch (Exception ex)
  439. {
  440. _logger.ErrorException("Package installation failed", ex);
  441. lock (CurrentInstallations)
  442. {
  443. CurrentInstallations.Remove(tuple);
  444. }
  445. EventHelper.FireEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
  446. {
  447. InstallationInfo = installationInfo,
  448. Exception = ex
  449. }, _logger);
  450. throw;
  451. }
  452. finally
  453. {
  454. // Dispose the progress object and remove the installation from the in-progress list
  455. innerProgress.Dispose();
  456. tuple.Item2.Dispose();
  457. }
  458. }
  459. /// <summary>
  460. /// Installs the package internal.
  461. /// </summary>
  462. /// <param name="package">The package.</param>
  463. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  464. /// <param name="progress">The progress.</param>
  465. /// <param name="cancellationToken">The cancellation token.</param>
  466. /// <returns>Task.</returns>
  467. private async Task InstallPackageInternal(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
  468. {
  469. // Do the install
  470. await PerformPackageInstallation(progress, package, cancellationToken).ConfigureAwait(false);
  471. // Do plugin-specific processing
  472. if (isPlugin)
  473. {
  474. // Set last update time if we were installed before
  475. var plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
  476. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  477. if (plugin != null)
  478. {
  479. OnPluginUpdated(plugin, package);
  480. }
  481. else
  482. {
  483. OnPluginInstalled(package);
  484. }
  485. }
  486. }
  487. private async Task PerformPackageInstallation(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  488. {
  489. // Target based on if it is an archive or single assembly
  490. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  491. var extension = Path.GetExtension(package.targetFilename);
  492. var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
  493. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  494. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  495. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  496. {
  497. Url = package.sourceUrl,
  498. CancellationToken = cancellationToken,
  499. Progress = progress
  500. }).ConfigureAwait(false);
  501. cancellationToken.ThrowIfCancellationRequested();
  502. // Validate with a checksum
  503. var packageChecksum = string.IsNullOrWhiteSpace(package.checksum) ? Guid.Empty : new Guid(package.checksum);
  504. if (packageChecksum != Guid.Empty) // support for legacy uploads for now
  505. {
  506. using (var stream = _fileSystem.OpenRead(tempFile))
  507. {
  508. var check = Guid.Parse(BitConverter.ToString(_cryptographyProvider.ComputeMD5(stream)).Replace("-", String.Empty));
  509. if (check != packageChecksum)
  510. {
  511. throw new Exception(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  512. }
  513. }
  514. }
  515. cancellationToken.ThrowIfCancellationRequested();
  516. // Success - move it to the real target
  517. try
  518. {
  519. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(target));
  520. _fileSystem.CopyFile(tempFile, target, true);
  521. //If it is an archive - write out a version file so we know what it is
  522. if (isArchive)
  523. {
  524. _fileSystem.WriteAllText(target + ".ver", package.versionStr);
  525. }
  526. }
  527. catch (IOException e)
  528. {
  529. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  530. throw;
  531. }
  532. try
  533. {
  534. _fileSystem.DeleteFile(tempFile);
  535. }
  536. catch (IOException e)
  537. {
  538. // Don't fail because of this
  539. _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
  540. }
  541. }
  542. /// <summary>
  543. /// Uninstalls a plugin
  544. /// </summary>
  545. /// <param name="plugin">The plugin.</param>
  546. /// <exception cref="System.ArgumentException"></exception>
  547. public void UninstallPlugin(IPlugin plugin)
  548. {
  549. plugin.OnUninstalling();
  550. // Remove it the quick way for now
  551. _applicationHost.RemovePlugin(plugin);
  552. var path = plugin.AssemblyFilePath;
  553. _logger.Info("Deleting plugin file {0}", path);
  554. // Make this case-insensitive to account for possible incorrect assembly naming
  555. var file = _fileSystem.GetFilePaths(_fileSystem.GetDirectoryName(path))
  556. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  557. if (!string.IsNullOrWhiteSpace(file))
  558. {
  559. path = file;
  560. }
  561. _fileSystem.DeleteFile(path);
  562. OnPluginUninstalled(plugin);
  563. _applicationHost.NotifyPendingRestart();
  564. }
  565. /// <summary>
  566. /// Releases unmanaged and - optionally - managed resources.
  567. /// </summary>
  568. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  569. protected virtual void Dispose(bool dispose)
  570. {
  571. if (dispose)
  572. {
  573. lock (CurrentInstallations)
  574. {
  575. foreach (var tuple in CurrentInstallations)
  576. {
  577. tuple.Item2.Dispose();
  578. }
  579. CurrentInstallations.Clear();
  580. }
  581. }
  582. }
  583. public void Dispose()
  584. {
  585. Dispose(true);
  586. }
  587. }
  588. }