PluginSecurityManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "http://mb3admin.com/test/admin/" + "service/appstore/register";
  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 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, ILogManager logManager)
  68. {
  69. if (httpClient == null)
  70. {
  71. throw new ArgumentNullException("httpClient");
  72. }
  73. _appHost = appHost;
  74. _httpClient = httpClient;
  75. _jsonSerializer = jsonSerializer;
  76. _appPaths = appPaths;
  77. _logger = logManager.GetLogger("SecurityManager");
  78. }
  79. /// <summary>
  80. /// Load all registration info for all entities that require registration
  81. /// </summary>
  82. /// <returns></returns>
  83. public async Task LoadAllRegistrationInfo()
  84. {
  85. var tasks = new List<Task>();
  86. ResetSupporterInfo();
  87. tasks.AddRange(RegisteredEntities.Select(i => i.LoadRegistrationInfoAsync()));
  88. await Task.WhenAll(tasks);
  89. }
  90. /// <summary>
  91. /// Gets the registration status.
  92. /// This overload supports existing plug-ins.
  93. /// </summary>
  94. /// <param name="feature">The feature.</param>
  95. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  96. /// <returns>Task{MBRegistrationRecord}.</returns>
  97. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent = null)
  98. {
  99. return GetRegistrationStatusInternal(feature, mb2Equivalent);
  100. }
  101. /// <summary>
  102. /// Gets the registration status.
  103. /// </summary>
  104. /// <param name="feature">The feature.</param>
  105. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  106. /// <param name="version">The version of this feature</param>
  107. /// <returns>Task{MBRegistrationRecord}.</returns>
  108. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent, string version)
  109. {
  110. return GetRegistrationStatusInternal(feature, mb2Equivalent, version);
  111. }
  112. private Task<MBRegistrationRecord> GetSupporterRegistrationStatus()
  113. {
  114. return GetRegistrationStatusInternal("MBSupporter", null, _appHost.ApplicationVersion.ToString());
  115. }
  116. /// <summary>
  117. /// Gets or sets the supporter key.
  118. /// </summary>
  119. /// <value>The supporter key.</value>
  120. public string SupporterKey
  121. {
  122. get
  123. {
  124. return LicenseFile.RegKey;
  125. }
  126. set
  127. {
  128. if (value != LicenseFile.RegKey)
  129. {
  130. LicenseFile.RegKey = value;
  131. LicenseFile.Save();
  132. // re-load registration info
  133. Task.Run(() => LoadAllRegistrationInfo());
  134. }
  135. }
  136. }
  137. public async Task<SupporterInfo> GetSupporterInfo()
  138. {
  139. var key = SupporterKey;
  140. if (string.IsNullOrWhiteSpace(key))
  141. {
  142. return new SupporterInfo();
  143. }
  144. var data = new Dictionary<string, string>
  145. {
  146. { "key", key },
  147. };
  148. var url = MbAdmin.HttpsUrl + "/service/supporter/retrieve";
  149. using (var stream = await _httpClient.Post(url, data, CancellationToken.None).ConfigureAwait(false))
  150. {
  151. var response = _jsonSerializer.DeserializeFromStream<SuppporterInfoResponse>(stream);
  152. var info = new SupporterInfo
  153. {
  154. Email = response.email,
  155. PlanType = response.planType,
  156. SupporterKey = response.supporterKey,
  157. ExpirationDate = string.IsNullOrWhiteSpace(response.expDate) ? (DateTime?)null : DateTime.Parse(response.expDate),
  158. RegistrationDate = DateTime.Parse(response.regDate),
  159. IsActiveSupporter = IsMBSupporter
  160. };
  161. info.IsExpiredSupporter = info.ExpirationDate.HasValue && info.ExpirationDate < DateTime.UtcNow && !string.IsNullOrWhiteSpace(info.SupporterKey);
  162. return info;
  163. }
  164. }
  165. /// <summary>
  166. /// Register an app store sale with our back-end. It will validate the transaction with the store
  167. /// and then register the proper feature and then fill in the supporter key on success.
  168. /// </summary>
  169. /// <param name="parameters">Json parameters to send to admin server</param>
  170. public async Task RegisterAppStoreSale(string parameters)
  171. {
  172. var options = new HttpRequestOptions()
  173. {
  174. Url = AppstoreRegUrl,
  175. CancellationToken = CancellationToken.None
  176. };
  177. options.RequestHeaders.Add("X-Emby-Token", /*_appHost.SystemId*/ "08606E86D043");
  178. options.RequestContent = parameters;
  179. options.RequestContentType = "application/json";
  180. try
  181. {
  182. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  183. {
  184. var reg = _jsonSerializer.DeserializeFromStream<RegRecord>(response.Content);
  185. if (!String.IsNullOrEmpty(reg.key))
  186. {
  187. SupporterKey = reg.key;
  188. }
  189. }
  190. }
  191. catch (Exception e)
  192. {
  193. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  194. //TODO - really need to write this to a file so we can re-try it automatically
  195. throw new ApplicationException("Error registering store sale");
  196. }
  197. }
  198. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  199. string mb2Equivalent = null,
  200. string version = null)
  201. {
  202. var lastChecked = LicenseFile.LastChecked(feature);
  203. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  204. var reg = new RegRecord
  205. {
  206. // Cache the result for up to a week
  207. registered = lastChecked > DateTime.UtcNow.AddDays(-7)
  208. };
  209. var success = reg.registered;
  210. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)))
  211. {
  212. var data = new Dictionary<string, string>
  213. {
  214. { "feature", feature },
  215. { "key", SupporterKey },
  216. { "mac", _appHost.SystemId },
  217. { "systemid", _appHost.SystemId },
  218. { "mb2equiv", mb2Equivalent },
  219. { "ver", version },
  220. { "platform", _appHost.OperatingSystemDisplayName },
  221. { "isservice", _appHost.IsRunningAsService.ToString().ToLower() }
  222. };
  223. try
  224. {
  225. using (var json = await _httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
  226. {
  227. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  228. success = true;
  229. }
  230. if (reg.registered)
  231. {
  232. LicenseFile.AddRegCheck(feature);
  233. }
  234. else
  235. {
  236. LicenseFile.RemoveRegCheck(feature);
  237. }
  238. }
  239. catch (Exception e)
  240. {
  241. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  242. }
  243. }
  244. var record = new MBRegistrationRecord
  245. {
  246. IsRegistered = reg.registered,
  247. ExpirationDate = reg.expDate,
  248. RegChecked = true,
  249. RegError = !success
  250. };
  251. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  252. record.IsValid = !record.RegChecked || (record.IsRegistered || record.TrialVersion);
  253. return record;
  254. }
  255. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  256. {
  257. //don't set this until we've successfully obtained exp date
  258. if (!regChecked)
  259. {
  260. return false;
  261. }
  262. var isInTrial = expirationDate > DateTime.UtcNow;
  263. return (isInTrial && !isRegistered);
  264. }
  265. /// <summary>
  266. /// Resets the supporter info.
  267. /// </summary>
  268. private void ResetSupporterInfo()
  269. {
  270. _isMbSupporter = null;
  271. _isMbSupporterInitialized = false;
  272. }
  273. }
  274. }