InstallationManager.cs 29 KB

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