PluginSecurityManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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="store"></param>
  170. /// <param name="application"></param>
  171. /// <param name="product"></param>
  172. /// <param name="feature"></param>
  173. /// <param name="type"></param>
  174. /// <param name="storeId"></param>
  175. /// <param name="storeToken"></param>
  176. /// <param name="email"></param>
  177. /// <param name="amt"></param>
  178. public async Task RegisterAppStoreSale(string store, string application, string product, string feature,
  179. string type, string storeId, string storeToken, string email, string amt)
  180. {
  181. var data = new Dictionary<string, string>()
  182. {
  183. {"store", store},
  184. {"application", application},
  185. {"product", product},
  186. {"feature", feature},
  187. {"type", type},
  188. {"storeId", storeId},
  189. {"token", storeToken},
  190. {"email", email},
  191. {"amt", amt}
  192. };
  193. var options = new HttpRequestOptions()
  194. {
  195. Url = AppstoreRegUrl,
  196. CancellationToken = CancellationToken.None
  197. };
  198. options.RequestHeaders.Add("X-Emby-Token", /*_appHost.SystemId*/ "08606E86D043");
  199. try
  200. {
  201. using (var json = await _httpClient.Post(options, data).ConfigureAwait(false))
  202. {
  203. var reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  204. if (!String.IsNullOrEmpty(reg.key))
  205. {
  206. SupporterKey = reg.key;
  207. }
  208. }
  209. }
  210. catch (Exception e)
  211. {
  212. _logger.ErrorException("Error registering appstore purchase {0}", e, _jsonSerializer.SerializeToString(data));
  213. //TODO - really need to write this to a file so we can re-try it automatically
  214. throw new ApplicationException("Error registering store sale");
  215. }
  216. }
  217. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  218. string mb2Equivalent = null,
  219. string version = null)
  220. {
  221. var lastChecked = LicenseFile.LastChecked(feature);
  222. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  223. var reg = new RegRecord
  224. {
  225. // Cache the result for up to a week
  226. registered = lastChecked > DateTime.UtcNow.AddDays(-7)
  227. };
  228. var success = reg.registered;
  229. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)))
  230. {
  231. var data = new Dictionary<string, string>
  232. {
  233. { "feature", feature },
  234. { "key", SupporterKey },
  235. { "mac", _appHost.SystemId },
  236. { "systemid", _appHost.SystemId },
  237. { "mb2equiv", mb2Equivalent },
  238. { "ver", version },
  239. { "platform", _appHost.OperatingSystemDisplayName },
  240. { "isservice", _appHost.IsRunningAsService.ToString().ToLower() }
  241. };
  242. try
  243. {
  244. using (var json = await _httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
  245. {
  246. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  247. success = true;
  248. }
  249. if (reg.registered)
  250. {
  251. LicenseFile.AddRegCheck(feature);
  252. }
  253. else
  254. {
  255. LicenseFile.RemoveRegCheck(feature);
  256. }
  257. }
  258. catch (Exception e)
  259. {
  260. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  261. }
  262. }
  263. var record = new MBRegistrationRecord
  264. {
  265. IsRegistered = reg.registered,
  266. ExpirationDate = reg.expDate,
  267. RegChecked = true,
  268. RegError = !success
  269. };
  270. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  271. record.IsValid = !record.RegChecked || (record.IsRegistered || record.TrialVersion);
  272. return record;
  273. }
  274. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  275. {
  276. //don't set this until we've successfully obtained exp date
  277. if (!regChecked)
  278. {
  279. return false;
  280. }
  281. var isInTrial = expirationDate > DateTime.UtcNow;
  282. return (isInTrial && !isRegistered);
  283. }
  284. /// <summary>
  285. /// Resets the supporter info.
  286. /// </summary>
  287. private void ResetSupporterInfo()
  288. {
  289. _isMbSupporter = null;
  290. _isMbSupporterInitialized = false;
  291. }
  292. }
  293. }