InstallationManager.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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.Model.Cryptography;
  16. using MediaBrowser.Model.Events;
  17. using MediaBrowser.Model.IO;
  18. using Microsoft.Extensions.Logging;
  19. using MediaBrowser.Model.Serialization;
  20. using MediaBrowser.Model.Updates;
  21. using MediaBrowser.Controller.Configuration;
  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. Version requiredVersion;
  270. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && currentServerVersion >= requiredVersion;
  271. }
  272. /// <summary>
  273. /// Gets the package.
  274. /// </summary>
  275. /// <param name="name">The name.</param>
  276. /// <param name="guid">The assembly guid</param>
  277. /// <param name="classification">The classification.</param>
  278. /// <param name="version">The version.</param>
  279. /// <returns>Task{PackageVersionInfo}.</returns>
  280. public async Task<PackageVersionInfo> GetPackage(string name, string guid, PackageVersionClass classification, Version version)
  281. {
  282. var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
  283. var package = packages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  284. ?? packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  285. if (package == null)
  286. {
  287. return null;
  288. }
  289. return package.versions.FirstOrDefault(v => GetPackageVersion(v).Equals(version) && v.classification == classification);
  290. }
  291. /// <summary>
  292. /// Gets the latest compatible version.
  293. /// </summary>
  294. /// <param name="name">The name.</param>
  295. /// <param name="guid">The assembly guid if this is a plug-in</param>
  296. /// <param name="currentServerVersion">The current server version.</param>
  297. /// <param name="classification">The classification.</param>
  298. /// <returns>Task{PackageVersionInfo}.</returns>
  299. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  300. {
  301. var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
  302. return GetLatestCompatibleVersion(packages, name, guid, currentServerVersion, classification);
  303. }
  304. /// <summary>
  305. /// Gets the latest compatible version.
  306. /// </summary>
  307. /// <param name="availablePackages">The available packages.</param>
  308. /// <param name="name">The name.</param>
  309. /// <param name="currentServerVersion">The current server version.</param>
  310. /// <param name="classification">The classification.</param>
  311. /// <returns>PackageVersionInfo.</returns>
  312. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  313. {
  314. var package = availablePackages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  315. ?? availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  316. if (package == null)
  317. {
  318. return null;
  319. }
  320. return package.versions
  321. .OrderByDescending(GetPackageVersion)
  322. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
  323. }
  324. /// <summary>
  325. /// Gets the available plugin updates.
  326. /// </summary>
  327. /// <param name="applicationVersion">The current server version.</param>
  328. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  329. /// <param name="cancellationToken">The cancellation token.</param>
  330. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  331. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  332. {
  333. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  334. var systemUpdateLevel = GetSystemUpdateLevel();
  335. // Figure out what needs to be installed
  336. return _applicationHost.Plugins.Select(p =>
  337. {
  338. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Id.ToString(), applicationVersion, systemUpdateLevel);
  339. return latestPluginInfo != null && GetPackageVersion(latestPluginInfo) > p.Version ? latestPluginInfo : null;
  340. }).Where(i => i != null)
  341. .Where(p => !string.IsNullOrEmpty(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.AssemblyGuid, p.guid, StringComparison.OrdinalIgnoreCase)));
  342. }
  343. /// <summary>
  344. /// Installs the package.
  345. /// </summary>
  346. /// <param name="package">The package.</param>
  347. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  348. /// <param name="progress">The progress.</param>
  349. /// <param name="cancellationToken">The cancellation token.</param>
  350. /// <returns>Task.</returns>
  351. /// <exception cref="System.ArgumentNullException">package</exception>
  352. public async Task InstallPackage(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
  353. {
  354. if (package == null)
  355. {
  356. throw new ArgumentNullException(nameof(package));
  357. }
  358. if (progress == null)
  359. {
  360. throw new ArgumentNullException(nameof(progress));
  361. }
  362. var installationInfo = new InstallationInfo
  363. {
  364. Id = Guid.NewGuid(),
  365. Name = package.name,
  366. AssemblyGuid = package.guid,
  367. UpdateClass = package.classification,
  368. Version = package.versionStr
  369. };
  370. var innerCancellationTokenSource = new CancellationTokenSource();
  371. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  372. // Add it to the in-progress list
  373. lock (CurrentInstallations)
  374. {
  375. CurrentInstallations.Add(tuple);
  376. }
  377. var innerProgress = new ActionableProgress<double>();
  378. // Whenever the progress updates, update the outer progress object and InstallationInfo
  379. innerProgress.RegisterAction(percent =>
  380. {
  381. progress.Report(percent);
  382. installationInfo.PercentComplete = percent;
  383. });
  384. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  385. var installationEventArgs = new InstallationEventArgs
  386. {
  387. InstallationInfo = installationInfo,
  388. PackageVersionInfo = package
  389. };
  390. PackageInstalling?.Invoke(this, installationEventArgs);
  391. try
  392. {
  393. await InstallPackageInternal(package, isPlugin, innerProgress, linkedToken).ConfigureAwait(false);
  394. lock (CurrentInstallations)
  395. {
  396. CurrentInstallations.Remove(tuple);
  397. }
  398. CompletedInstallationsInternal.Add(installationInfo);
  399. PackageInstallationCompleted?.Invoke(this, installationEventArgs);
  400. }
  401. catch (OperationCanceledException)
  402. {
  403. lock (CurrentInstallations)
  404. {
  405. CurrentInstallations.Remove(tuple);
  406. }
  407. _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  408. PackageInstallationCancelled?.Invoke(this, installationEventArgs);
  409. throw;
  410. }
  411. catch (Exception ex)
  412. {
  413. _logger.LogError(ex, "Package installation failed");
  414. lock (CurrentInstallations)
  415. {
  416. CurrentInstallations.Remove(tuple);
  417. }
  418. PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs
  419. {
  420. InstallationInfo = installationInfo,
  421. Exception = ex
  422. });
  423. throw;
  424. }
  425. finally
  426. {
  427. // Dispose the progress object and remove the installation from the in-progress list
  428. tuple.Item2.Dispose();
  429. }
  430. }
  431. /// <summary>
  432. /// Installs the package internal.
  433. /// </summary>
  434. /// <param name="package">The package.</param>
  435. /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
  436. /// <param name="progress">The progress.</param>
  437. /// <param name="cancellationToken">The cancellation token.</param>
  438. /// <returns>Task.</returns>
  439. private async Task InstallPackageInternal(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
  440. {
  441. IPlugin plugin = null;
  442. if (isPlugin)
  443. {
  444. // Set last update time if we were installed before
  445. plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
  446. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  447. }
  448. string targetPath = plugin == null ? null : plugin.AssemblyFilePath;
  449. // Do the install
  450. await PerformPackageInstallation(progress, targetPath, package, cancellationToken).ConfigureAwait(false);
  451. // Do plugin-specific processing
  452. if (isPlugin)
  453. {
  454. if (plugin == null)
  455. {
  456. OnPluginInstalled(package);
  457. }
  458. else
  459. {
  460. OnPluginUpdated(plugin, package);
  461. }
  462. }
  463. }
  464. private async Task PerformPackageInstallation(IProgress<double> progress, string target, PackageVersionInfo package, CancellationToken cancellationToken)
  465. {
  466. // Target based on if it is an archive or single assembly
  467. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  468. var extension = Path.GetExtension(package.targetFilename);
  469. var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
  470. if (target == null)
  471. {
  472. target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  473. }
  474. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  475. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  476. {
  477. Url = package.sourceUrl,
  478. CancellationToken = cancellationToken,
  479. Progress = progress
  480. }).ConfigureAwait(false);
  481. cancellationToken.ThrowIfCancellationRequested();
  482. // Validate with a checksum
  483. var packageChecksum = string.IsNullOrWhiteSpace(package.checksum) ? Guid.Empty : new Guid(package.checksum);
  484. if (!packageChecksum.Equals(Guid.Empty)) // support for legacy uploads for now
  485. {
  486. using (var stream = _fileSystem.OpenRead(tempFile))
  487. {
  488. var check = Guid.Parse(BitConverter.ToString(_cryptographyProvider.ComputeMD5(stream)).Replace("-", string.Empty));
  489. if (check != packageChecksum)
  490. {
  491. throw new Exception(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  492. }
  493. }
  494. }
  495. cancellationToken.ThrowIfCancellationRequested();
  496. // Success - move it to the real target
  497. try
  498. {
  499. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(target));
  500. _fileSystem.CopyFile(tempFile, target, true);
  501. //If it is an archive - write out a version file so we know what it is
  502. if (isArchive)
  503. {
  504. _fileSystem.WriteAllText(target + ".ver", package.versionStr);
  505. }
  506. }
  507. catch (IOException ex)
  508. {
  509. _logger.LogError(ex, "Error attempting to move file from {TempFile} to {TargetFile}", tempFile, target);
  510. throw;
  511. }
  512. try
  513. {
  514. _fileSystem.DeleteFile(tempFile);
  515. }
  516. catch (IOException ex)
  517. {
  518. // Don't fail because of this
  519. _logger.LogError(ex, "Error deleting temp file {TempFile}", tempFile);
  520. }
  521. }
  522. /// <summary>
  523. /// Uninstalls a plugin
  524. /// </summary>
  525. /// <param name="plugin">The plugin.</param>
  526. /// <exception cref="System.ArgumentException"></exception>
  527. public void UninstallPlugin(IPlugin plugin)
  528. {
  529. plugin.OnUninstalling();
  530. // Remove it the quick way for now
  531. _applicationHost.RemovePlugin(plugin);
  532. var path = plugin.AssemblyFilePath;
  533. _logger.LogInformation("Deleting plugin file {0}", path);
  534. // Make this case-insensitive to account for possible incorrect assembly naming
  535. var file = _fileSystem.GetFilePaths(_fileSystem.GetDirectoryName(path))
  536. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  537. if (!string.IsNullOrWhiteSpace(file))
  538. {
  539. path = file;
  540. }
  541. _fileSystem.DeleteFile(path);
  542. var list = _config.Configuration.UninstalledPlugins.ToList();
  543. var filename = Path.GetFileName(path);
  544. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  545. {
  546. list.Add(filename);
  547. _config.Configuration.UninstalledPlugins = list.ToArray();
  548. _config.SaveConfiguration();
  549. }
  550. OnPluginUninstalled(plugin);
  551. _applicationHost.NotifyPendingRestart();
  552. }
  553. /// <summary>
  554. /// Releases unmanaged and - optionally - managed resources.
  555. /// </summary>
  556. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  557. protected virtual void Dispose(bool dispose)
  558. {
  559. if (dispose)
  560. {
  561. lock (CurrentInstallations)
  562. {
  563. foreach (var tuple in CurrentInstallations)
  564. {
  565. tuple.Item2.Dispose();
  566. }
  567. CurrentInstallations.Clear();
  568. }
  569. }
  570. }
  571. public void Dispose()
  572. {
  573. Dispose(true);
  574. }
  575. }
  576. }