PackageManager.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Common.Security;
  4. using MediaBrowser.Common.Updates;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using MediaBrowser.Model.Updates;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Security.Cryptography;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Common.Implementations.Updates
  16. {
  17. public class PackageManager : IPackageManager
  18. {
  19. private readonly ISecurityManager _securityManager;
  20. private readonly INetworkManager _networkManager;
  21. private readonly IHttpClient _httpClient;
  22. private readonly IApplicationPaths _appPaths;
  23. private readonly IJsonSerializer _jsonSerializer;
  24. private readonly ILogger _logger;
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="PackageManager" /> class.
  27. /// </summary>
  28. /// <param name="securityManager">The security manager.</param>
  29. /// <param name="networkManager">The network manager.</param>
  30. /// <param name="httpClient">The HTTP client.</param>
  31. /// <param name="applicationPaths">The application paths.</param>
  32. /// <param name="jsonSerializer">The json serializer.</param>
  33. /// <param name="logger">The logger.</param>
  34. public PackageManager(ISecurityManager securityManager, INetworkManager networkManager, IHttpClient httpClient, IApplicationPaths applicationPaths, IJsonSerializer jsonSerializer, ILogger logger)
  35. {
  36. _securityManager = securityManager;
  37. _networkManager = networkManager;
  38. _httpClient = httpClient;
  39. _appPaths = applicationPaths;
  40. _jsonSerializer = jsonSerializer;
  41. _logger = logger;
  42. }
  43. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken)
  44. {
  45. var data = new Dictionary<string, string> { { "key", _securityManager.SupporterKey }, { "mac", _networkManager.GetMacAddress() } };
  46. using (var json = await _httpClient.Post(Constants.Constants.MBAdminUrl + "service/package/retrieveall", data, cancellationToken).ConfigureAwait(false))
  47. {
  48. cancellationToken.ThrowIfCancellationRequested();
  49. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  50. foreach (var package in packages)
  51. {
  52. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  53. .OrderByDescending(v => v.version).ToList();
  54. }
  55. return packages;
  56. }
  57. }
  58. public async Task InstallPackage(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  59. {
  60. // Target based on if it is an archive or single assembly
  61. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  62. var isArchive = string.Equals(Path.GetExtension(package.targetFilename), ".zip", StringComparison.OrdinalIgnoreCase);
  63. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  64. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  65. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  66. {
  67. Url = package.sourceUrl,
  68. CancellationToken = cancellationToken,
  69. Progress = progress
  70. }).ConfigureAwait(false);
  71. cancellationToken.ThrowIfCancellationRequested();
  72. // Validate with a checksum
  73. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  74. {
  75. using (var crypto = new MD5CryptoServiceProvider())
  76. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  77. {
  78. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  79. if (check != package.checksum)
  80. {
  81. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  82. }
  83. }
  84. }
  85. cancellationToken.ThrowIfCancellationRequested();
  86. // Success - move it to the real target
  87. try
  88. {
  89. File.Copy(tempFile, target, true);
  90. }
  91. catch (IOException e)
  92. {
  93. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  94. throw;
  95. }
  96. try
  97. {
  98. File.Delete(tempFile);
  99. }
  100. catch (IOException e)
  101. {
  102. // Don't fail because of this
  103. _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
  104. }
  105. }
  106. }
  107. }