InstallationManager.cs 27 KB

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