InstallationManager.cs 27 KB

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