PluginSecurityManager.cs 9.7 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 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 data = new Dictionary<string, string>
  144. {
  145. { "key", key },
  146. };
  147. var url = MbAdmin.HttpsUrl + "/service/supporter/retrieve";
  148. using (var stream = await _httpClient.Post(url, data, CancellationToken.None).ConfigureAwait(false))
  149. {
  150. var response = _jsonSerializer.DeserializeFromStream<SuppporterInfoResponse>(stream);
  151. var info = new SupporterInfo
  152. {
  153. Email = response.email,
  154. PlanType = response.planType,
  155. SupporterKey = response.supporterKey,
  156. ExpirationDate = string.IsNullOrWhiteSpace(response.expDate) ? (DateTime?)null : DateTime.Parse(response.expDate),
  157. RegistrationDate = DateTime.Parse(response.regDate),
  158. IsActiveSupporter = IsMBSupporter
  159. };
  160. info.IsExpiredSupporter = info.ExpirationDate.HasValue && info.ExpirationDate < DateTime.UtcNow && !string.IsNullOrWhiteSpace(info.SupporterKey);
  161. return info;
  162. }
  163. }
  164. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  165. string mb2Equivalent = null,
  166. string version = null)
  167. {
  168. var lastChecked = LicenseFile.LastChecked(feature);
  169. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  170. var reg = new RegRecord
  171. {
  172. // Cache the result for up to a week
  173. registered = lastChecked > DateTime.UtcNow.AddDays(-7)
  174. };
  175. var success = reg.registered;
  176. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)))
  177. {
  178. var data = new Dictionary<string, string>
  179. {
  180. { "feature", feature },
  181. { "key", SupporterKey },
  182. { "mac", _appHost.SystemId },
  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. }