PluginSecurityManager.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. private 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. public async Task<SupporterInfo> GetSupporterInfo()
  139. {
  140. var key = SupporterKey;
  141. if (string.IsNullOrWhiteSpace(key))
  142. {
  143. return new SupporterInfo();
  144. }
  145. var url = Constants.Constants.MbAdminUrl + "/service/supporter/retrieve?key=" + key;
  146. using (var stream = await _httpClient.Get(url, CancellationToken.None).ConfigureAwait(false))
  147. {
  148. var response = _jsonSerializer.DeserializeFromStream<SuppporterInfoResponse>(stream);
  149. var info = new SupporterInfo
  150. {
  151. Email = response.email,
  152. PlanType = response.planType,
  153. SupporterKey = response.supporterKey,
  154. ExpirationDate = string.IsNullOrWhiteSpace(response.expDate) ? (DateTime?)null : DateTime.Parse(response.expDate),
  155. RegistrationDate = DateTime.Parse(response.regDate),
  156. IsActiveSupporter = IsMBSupporter
  157. };
  158. info.IsExpiredSupporter = info.ExpirationDate.HasValue && info.ExpirationDate < DateTime.UtcNow && !string.IsNullOrWhiteSpace(info.SupporterKey);
  159. return info;
  160. }
  161. }
  162. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  163. string mb2Equivalent = null,
  164. string version = null)
  165. {
  166. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  167. var reg = new RegRecord
  168. {
  169. registered = LicenseFile.LastChecked(feature) > DateTime.UtcNow.AddDays(-7)
  170. };
  171. var success = reg.registered;
  172. if (!reg.registered)
  173. {
  174. var mac = _networkManager.GetMacAddress();
  175. var data = new Dictionary<string, string>
  176. {
  177. { "feature", feature },
  178. { "key", SupporterKey },
  179. { "mac", mac },
  180. { "systemid", _appHost.SystemId },
  181. { "mb2equiv", mb2Equivalent },
  182. { "ver", version },
  183. { "platform", Environment.OSVersion.VersionString },
  184. { "isservice", _appHost.IsRunningAsService.ToString().ToLower() }
  185. };
  186. try
  187. {
  188. using (var json = await _httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
  189. {
  190. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  191. success = true;
  192. }
  193. if (reg.registered)
  194. {
  195. LicenseFile.AddRegCheck(feature);
  196. }
  197. else
  198. {
  199. LicenseFile.RemoveRegCheck(feature);
  200. }
  201. }
  202. catch (Exception e)
  203. {
  204. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  205. }
  206. }
  207. var record = new MBRegistrationRecord
  208. {
  209. IsRegistered = reg.registered,
  210. ExpirationDate = reg.expDate,
  211. RegChecked = true,
  212. RegError = !success
  213. };
  214. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  215. record.IsValid = !record.RegChecked || (record.IsRegistered || record.TrialVersion);
  216. return record;
  217. }
  218. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  219. {
  220. //don't set this until we've successfully obtained exp date
  221. if (!regChecked)
  222. {
  223. return false;
  224. }
  225. var isInTrial = expirationDate > DateTime.UtcNow;
  226. return (isInTrial && !isRegistered);
  227. }
  228. /// <summary>
  229. /// Resets the supporter info.
  230. /// </summary>
  231. private void ResetSupporterInfo()
  232. {
  233. _isMbSupporter = null;
  234. _isMbSupporterInitialized = false;
  235. }
  236. }
  237. }