PluginSecurityManager.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Common.Security;
  4. using MediaBrowser.Model.Entities;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Common.Implementations.Security
  13. {
  14. /// <summary>
  15. /// Class PluginSecurityManager
  16. /// </summary>
  17. public class PluginSecurityManager : ISecurityManager
  18. {
  19. private const string MBValidateUrl = Constants.Constants.MbAdminUrl + "service/registration/validate";
  20. /// <summary>
  21. /// The _is MB supporter
  22. /// </summary>
  23. private bool? _isMbSupporter;
  24. /// <summary>
  25. /// The _is MB supporter initialized
  26. /// </summary>
  27. private bool _isMbSupporterInitialized;
  28. /// <summary>
  29. /// The _is MB supporter sync lock
  30. /// </summary>
  31. private object _isMbSupporterSyncLock = new object();
  32. /// <summary>
  33. /// Gets a value indicating whether this instance is MB supporter.
  34. /// </summary>
  35. /// <value><c>true</c> if this instance is MB supporter; otherwise, <c>false</c>.</value>
  36. public bool IsMBSupporter
  37. {
  38. get
  39. {
  40. LazyInitializer.EnsureInitialized(ref _isMbSupporter, ref _isMbSupporterInitialized, ref _isMbSupporterSyncLock, () => GetSupporterRegistrationStatus().Result.IsRegistered);
  41. return _isMbSupporter.Value;
  42. }
  43. }
  44. private MBLicenseFile _licenseFile;
  45. private MBLicenseFile LicenseFile
  46. {
  47. get { return _licenseFile ?? (_licenseFile = new MBLicenseFile(_appPaths)); }
  48. }
  49. private readonly IHttpClient _httpClient;
  50. private readonly IJsonSerializer _jsonSerializer;
  51. private readonly IApplicationHost _appHost;
  52. private readonly ILogger _logger;
  53. private readonly INetworkManager _networkManager;
  54. private readonly IApplicationPaths _appPaths;
  55. private IEnumerable<IRequiresRegistration> _registeredEntities;
  56. protected IEnumerable<IRequiresRegistration> RegisteredEntities
  57. {
  58. get
  59. {
  60. return _registeredEntities ?? (_registeredEntities = _appHost.GetExports<IRequiresRegistration>());
  61. }
  62. }
  63. /// <summary>
  64. /// Initializes a new instance of the <see cref="PluginSecurityManager" /> class.
  65. /// </summary>
  66. public PluginSecurityManager(IApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer,
  67. IApplicationPaths appPaths, INetworkManager networkManager, ILogManager logManager)
  68. {
  69. if (httpClient == null)
  70. {
  71. throw new ArgumentNullException("httpClient");
  72. }
  73. _appHost = appHost;
  74. _httpClient = httpClient;
  75. _jsonSerializer = jsonSerializer;
  76. _networkManager = networkManager;
  77. _appPaths = appPaths;
  78. _logger = logManager.GetLogger("SecurityManager");
  79. }
  80. /// <summary>
  81. /// Load all registration info for all entities that require registration
  82. /// </summary>
  83. /// <returns></returns>
  84. public async Task LoadAllRegistrationInfo()
  85. {
  86. var tasks = new List<Task>();
  87. ResetSupporterInfo();
  88. tasks.AddRange(RegisteredEntities.Select(i => i.LoadRegistrationInfoAsync()));
  89. await Task.WhenAll(tasks);
  90. }
  91. /// <summary>
  92. /// Gets the registration status.
  93. /// This overload supports existing plug-ins.
  94. /// </summary>
  95. /// <param name="feature">The feature.</param>
  96. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  97. /// <returns>Task{MBRegistrationRecord}.</returns>
  98. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent = null)
  99. {
  100. return GetRegistrationStatusInternal(feature, mb2Equivalent);
  101. }
  102. /// <summary>
  103. /// Gets the registration status.
  104. /// </summary>
  105. /// <param name="feature">The feature.</param>
  106. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  107. /// <param name="version">The version of this feature</param>
  108. /// <returns>Task{MBRegistrationRecord}.</returns>
  109. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent, string version)
  110. {
  111. return GetRegistrationStatusInternal(feature, mb2Equivalent, version);
  112. }
  113. public Task<MBRegistrationRecord> GetSupporterRegistrationStatus()
  114. {
  115. return GetRegistrationStatusInternal("MBSupporter", null, _appHost.ApplicationVersion.ToString());
  116. }
  117. /// <summary>
  118. /// Gets or sets the supporter key.
  119. /// </summary>
  120. /// <value>The supporter key.</value>
  121. public string SupporterKey
  122. {
  123. get
  124. {
  125. return LicenseFile.RegKey;
  126. }
  127. set
  128. {
  129. if (value != LicenseFile.RegKey)
  130. {
  131. LicenseFile.RegKey = value;
  132. LicenseFile.Save();
  133. // re-load registration info
  134. Task.Run(() => LoadAllRegistrationInfo());
  135. }
  136. }
  137. }
  138. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  139. string mb2Equivalent = null,
  140. string version = null)
  141. {
  142. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  143. var reg = new RegRecord
  144. {
  145. registered = LicenseFile.LastChecked(feature) > DateTime.UtcNow.AddDays(-15)
  146. };
  147. var success = reg.registered;
  148. if (!reg.registered)
  149. {
  150. var mac = _networkManager.GetMacAddress();
  151. var data = new Dictionary<string, string>
  152. {
  153. { "feature", feature },
  154. { "key", SupporterKey },
  155. { "mac", mac },
  156. { "mb2equiv", mb2Equivalent },
  157. { "ver", version },
  158. { "platform", Environment.OSVersion.VersionString },
  159. { "isservice", _appHost.IsRunningAsService.ToString().ToLower() }
  160. };
  161. try
  162. {
  163. using (var json = await _httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
  164. {
  165. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  166. success = true;
  167. }
  168. if (reg.registered)
  169. {
  170. LicenseFile.AddRegCheck(feature);
  171. }
  172. else
  173. {
  174. LicenseFile.RemoveRegCheck(feature);
  175. }
  176. }
  177. catch (Exception e)
  178. {
  179. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  180. }
  181. }
  182. return new MBRegistrationRecord
  183. {
  184. IsRegistered = reg.registered,
  185. ExpirationDate = reg.expDate,
  186. RegChecked = true,
  187. RegError = !success
  188. };
  189. }
  190. /// <summary>
  191. /// Resets the supporter info.
  192. /// </summary>
  193. private void ResetSupporterInfo()
  194. {
  195. _isMbSupporter = null;
  196. _isMbSupporterInitialized = false;
  197. }
  198. }
  199. }