InstallationManager.cs 28 KB

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