InstallationManager.cs 27 KB

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