PackageManager.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. /// <summary>
  44. /// Get all available packages including registration information.
  45. /// Use this for the plug-in catalog to provide all information for this installation.
  46. /// </summary>
  47. /// <param name="cancellationToken"></param>
  48. /// <returns></returns>
  49. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken)
  50. {
  51. var data = new Dictionary<string, string> { { "key", _securityManager.SupporterKey }, { "mac", _networkManager.GetMacAddress() } };
  52. using (var json = await _httpClient.Post(Constants.Constants.MbAdminUrl + "service/package/retrieveall", data, cancellationToken).ConfigureAwait(false))
  53. {
  54. cancellationToken.ThrowIfCancellationRequested();
  55. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  56. return FilterVersions(packages);
  57. }
  58. }
  59. /// <summary>
  60. /// Get all available packages using the static file resource.
  61. /// Use this for update checks as it will be much less taxing on the server and can be cached.
  62. /// </summary>
  63. /// <param name="cancellationToken"></param>
  64. /// <returns></returns>
  65. public async Task<IEnumerable<PackageInfo>> GetAvailablePackagesStatic(CancellationToken cancellationToken)
  66. {
  67. using (var json = await _httpClient.Get(Constants.Constants.MbAdminUrl + "service/MB3Packages.json", cancellationToken).ConfigureAwait(false))
  68. {
  69. cancellationToken.ThrowIfCancellationRequested();
  70. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  71. return FilterVersions(packages);
  72. }
  73. }
  74. private IEnumerable<PackageInfo> FilterVersions(List<PackageInfo> original)
  75. {
  76. foreach (var package in original)
  77. {
  78. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  79. .OrderByDescending(v => v.version).ToList();
  80. }
  81. return original;
  82. }
  83. public async Task InstallPackage(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  84. {
  85. // Target based on if it is an archive or single assembly
  86. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  87. var isArchive = string.Equals(Path.GetExtension(package.targetFilename), ".zip", StringComparison.OrdinalIgnoreCase);
  88. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  89. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  90. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  91. {
  92. Url = package.sourceUrl,
  93. CancellationToken = cancellationToken,
  94. Progress = progress
  95. }).ConfigureAwait(false);
  96. cancellationToken.ThrowIfCancellationRequested();
  97. // Validate with a checksum
  98. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  99. {
  100. using (var crypto = new MD5CryptoServiceProvider())
  101. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  102. {
  103. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  104. if (check != package.checksum)
  105. {
  106. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  107. }
  108. }
  109. }
  110. cancellationToken.ThrowIfCancellationRequested();
  111. // Success - move it to the real target
  112. try
  113. {
  114. File.Copy(tempFile, target, true);
  115. //If it is an archive - write out a version file so we know what it is
  116. if (isArchive)
  117. {
  118. File.WriteAllText(target+".ver", package.versionStr);
  119. }
  120. }
  121. catch (IOException e)
  122. {
  123. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  124. throw;
  125. }
  126. try
  127. {
  128. File.Delete(tempFile);
  129. }
  130. catch (IOException e)
  131. {
  132. // Don't fail because of this
  133. _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
  134. }
  135. }
  136. }
  137. }