PluginSecurityManager.cs 9.6 KB

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