2
0

PluginSecurityManager.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 MbAdminUrl = "https://www.mb3admin.com/admin/";
  20. private const string MBValidateUrl = MbAdminUrl + "service/registration/validate";
  21. /// <summary>
  22. /// The _is MB supporter
  23. /// </summary>
  24. private bool? _isMbSupporter;
  25. /// <summary>
  26. /// The _is MB supporter initialized
  27. /// </summary>
  28. private bool _isMbSupporterInitialized;
  29. /// <summary>
  30. /// The _is MB supporter sync lock
  31. /// </summary>
  32. private object _isMbSupporterSyncLock = new object();
  33. /// <summary>
  34. /// Gets a value indicating whether this instance is MB supporter.
  35. /// </summary>
  36. /// <value><c>true</c> if this instance is MB supporter; otherwise, <c>false</c>.</value>
  37. public bool IsMBSupporter
  38. {
  39. get
  40. {
  41. LazyInitializer.EnsureInitialized(ref _isMbSupporter, ref _isMbSupporterInitialized, ref _isMbSupporterSyncLock, () => GetSupporterRegistrationStatus().Result.IsRegistered);
  42. return _isMbSupporter.Value;
  43. }
  44. }
  45. private MBLicenseFile _licenseFile;
  46. private MBLicenseFile LicenseFile
  47. {
  48. get { return _licenseFile ?? (_licenseFile = new MBLicenseFile(_appPaths)); }
  49. }
  50. private readonly IHttpClient _httpClient;
  51. private readonly IJsonSerializer _jsonSerializer;
  52. private readonly IApplicationHost _appHost;
  53. private readonly ILogger _logger;
  54. private readonly INetworkManager _networkManager;
  55. private readonly IApplicationPaths _appPaths;
  56. private IEnumerable<IRequiresRegistration> _registeredEntities;
  57. protected IEnumerable<IRequiresRegistration> RegisteredEntities
  58. {
  59. get
  60. {
  61. return _registeredEntities ?? (_registeredEntities = _appHost.GetExports<IRequiresRegistration>());
  62. }
  63. }
  64. /// <summary>
  65. /// Initializes a new instance of the <see cref="PluginSecurityManager" /> class.
  66. /// </summary>
  67. public PluginSecurityManager(IApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer,
  68. IApplicationPaths appPaths, INetworkManager networkManager, ILogManager logManager)
  69. {
  70. if (httpClient == null)
  71. {
  72. throw new ArgumentNullException("httpClient");
  73. }
  74. _appHost = appHost;
  75. _httpClient = httpClient;
  76. _jsonSerializer = jsonSerializer;
  77. _networkManager = networkManager;
  78. _appPaths = appPaths;
  79. _logger = logManager.GetLogger("SecurityManager");
  80. }
  81. /// <summary>
  82. /// Load all registration info for all entities that require registration
  83. /// </summary>
  84. /// <returns></returns>
  85. public async Task LoadAllRegistrationInfo()
  86. {
  87. var tasks = new List<Task>();
  88. ResetSupporterInfo();
  89. tasks.AddRange(RegisteredEntities.Select(i => i.LoadRegistrationInfoAsync()));
  90. await Task.WhenAll(tasks);
  91. }
  92. /// <summary>
  93. /// Gets the registration status.
  94. /// This overload supports existing plug-ins.
  95. /// </summary>
  96. /// <param name="feature">The feature.</param>
  97. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  98. /// <returns>Task{MBRegistrationRecord}.</returns>
  99. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent = null)
  100. {
  101. return GetRegistrationStatusInternal(feature, mb2Equivalent);
  102. }
  103. /// <summary>
  104. /// Gets the registration status.
  105. /// </summary>
  106. /// <param name="feature">The feature.</param>
  107. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  108. /// <param name="version">The version of this feature</param>
  109. /// <returns>Task{MBRegistrationRecord}.</returns>
  110. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent, string version)
  111. {
  112. return GetRegistrationStatusInternal(feature, mb2Equivalent, version);
  113. }
  114. private Task<MBRegistrationRecord> GetSupporterRegistrationStatus()
  115. {
  116. return GetRegistrationStatusInternal("MBSupporter", null, _appHost.ApplicationVersion.ToString());
  117. }
  118. /// <summary>
  119. /// Gets or sets the supporter key.
  120. /// </summary>
  121. /// <value>The supporter key.</value>
  122. public string SupporterKey
  123. {
  124. get
  125. {
  126. return LicenseFile.RegKey;
  127. }
  128. set
  129. {
  130. if (value != LicenseFile.RegKey)
  131. {
  132. LicenseFile.RegKey = value;
  133. LicenseFile.Save();
  134. // re-load registration info
  135. Task.Run(() => LoadAllRegistrationInfo());
  136. }
  137. }
  138. }
  139. public async Task<SupporterInfo> GetSupporterInfo()
  140. {
  141. var key = SupporterKey;
  142. if (string.IsNullOrWhiteSpace(key))
  143. {
  144. return new SupporterInfo();
  145. }
  146. var url = MbAdminUrl + "/service/supporter/retrieve?key=" + key;
  147. using (var stream = await _httpClient.Get(url, CancellationToken.None).ConfigureAwait(false))
  148. {
  149. var response = _jsonSerializer.DeserializeFromStream<SuppporterInfoResponse>(stream);
  150. var info = new SupporterInfo
  151. {
  152. Email = response.email,
  153. PlanType = response.planType,
  154. SupporterKey = response.supporterKey,
  155. ExpirationDate = string.IsNullOrWhiteSpace(response.expDate) ? (DateTime?)null : DateTime.Parse(response.expDate),
  156. RegistrationDate = DateTime.Parse(response.regDate),
  157. IsActiveSupporter = IsMBSupporter
  158. };
  159. info.IsExpiredSupporter = info.ExpirationDate.HasValue && info.ExpirationDate < DateTime.UtcNow && !string.IsNullOrWhiteSpace(info.SupporterKey);
  160. return info;
  161. }
  162. }
  163. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  164. string mb2Equivalent = null,
  165. string version = null)
  166. {
  167. var lastChecked = LicenseFile.LastChecked(feature);
  168. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  169. var reg = new RegRecord
  170. {
  171. // Cache the result for up to a week
  172. registered = lastChecked > DateTime.UtcNow.AddDays(-7)
  173. };
  174. var success = reg.registered;
  175. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)))
  176. {
  177. var mac = _networkManager.GetMacAddress();
  178. var data = new Dictionary<string, string>
  179. {
  180. { "feature", feature },
  181. { "key", SupporterKey },
  182. { "mac", mac },
  183. { "systemid", _appHost.SystemId },
  184. { "mb2equiv", mb2Equivalent },
  185. { "ver", version },
  186. { "platform", _appHost.OperatingSystemDisplayName },
  187. { "isservice", _appHost.IsRunningAsService.ToString().ToLower() }
  188. };
  189. try
  190. {
  191. using (var json = await _httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
  192. {
  193. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  194. success = true;
  195. }
  196. if (reg.registered)
  197. {
  198. LicenseFile.AddRegCheck(feature);
  199. }
  200. else
  201. {
  202. LicenseFile.RemoveRegCheck(feature);
  203. }
  204. }
  205. catch (Exception e)
  206. {
  207. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  208. }
  209. }
  210. var record = new MBRegistrationRecord
  211. {
  212. IsRegistered = reg.registered,
  213. ExpirationDate = reg.expDate,
  214. RegChecked = true,
  215. RegError = !success
  216. };
  217. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  218. record.IsValid = !record.RegChecked || (record.IsRegistered || record.TrialVersion);
  219. return record;
  220. }
  221. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  222. {
  223. //don't set this until we've successfully obtained exp date
  224. if (!regChecked)
  225. {
  226. return false;
  227. }
  228. var isInTrial = expirationDate > DateTime.UtcNow;
  229. return (isInTrial && !isRegistered);
  230. }
  231. /// <summary>
  232. /// Resets the supporter info.
  233. /// </summary>
  234. private void ResetSupporterInfo()
  235. {
  236. _isMbSupporter = null;
  237. _isMbSupporterInitialized = false;
  238. }
  239. }
  240. }