2
0

PluginSecurityManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using System.IO;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Security;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Common.Implementations.Security
  14. {
  15. /// <summary>
  16. /// Class PluginSecurityManager
  17. /// </summary>
  18. public class PluginSecurityManager : ISecurityManager
  19. {
  20. private const string MBValidateUrl = MbAdmin.HttpsUrl + "service/registration/validate";
  21. private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "http://mb3admin.com/test/admin/" + "service/appstore/register";
  22. /// <summary>
  23. /// The _is MB supporter
  24. /// </summary>
  25. private bool? _isMbSupporter;
  26. /// <summary>
  27. /// The _is MB supporter initialized
  28. /// </summary>
  29. private bool _isMbSupporterInitialized;
  30. /// <summary>
  31. /// The _is MB supporter sync lock
  32. /// </summary>
  33. private object _isMbSupporterSyncLock = new object();
  34. /// <summary>
  35. /// Gets a value indicating whether this instance is MB supporter.
  36. /// </summary>
  37. /// <value><c>true</c> if this instance is MB supporter; otherwise, <c>false</c>.</value>
  38. public bool IsMBSupporter
  39. {
  40. get
  41. {
  42. LazyInitializer.EnsureInitialized(ref _isMbSupporter, ref _isMbSupporterInitialized, ref _isMbSupporterSyncLock, () => GetSupporterRegistrationStatus().Result.IsRegistered);
  43. return _isMbSupporter.Value;
  44. }
  45. }
  46. private MBLicenseFile _licenseFile;
  47. private MBLicenseFile LicenseFile
  48. {
  49. get { return _licenseFile ?? (_licenseFile = new MBLicenseFile(_appPaths)); }
  50. }
  51. private readonly IHttpClient _httpClient;
  52. private readonly IJsonSerializer _jsonSerializer;
  53. private readonly IApplicationHost _appHost;
  54. private readonly ILogger _logger;
  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, ILogManager logManager)
  69. {
  70. if (httpClient == null)
  71. {
  72. throw new ArgumentNullException("httpClient");
  73. }
  74. _appHost = appHost;
  75. _httpClient = httpClient;
  76. _jsonSerializer = jsonSerializer;
  77. _appPaths = appPaths;
  78. _logger = logManager.GetLogger("SecurityManager");
  79. }
  80. /// <summary>
  81. /// Load all registration info for all entities that require registration
  82. /// </summary>
  83. /// <returns></returns>
  84. public async Task LoadAllRegistrationInfo()
  85. {
  86. var tasks = new List<Task>();
  87. ResetSupporterInfo();
  88. tasks.AddRange(RegisteredEntities.Select(i => i.LoadRegistrationInfoAsync()));
  89. await Task.WhenAll(tasks);
  90. }
  91. /// <summary>
  92. /// Gets the registration status.
  93. /// This overload supports existing plug-ins.
  94. /// </summary>
  95. /// <param name="feature">The feature.</param>
  96. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  97. /// <returns>Task{MBRegistrationRecord}.</returns>
  98. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent = null)
  99. {
  100. return GetRegistrationStatusInternal(feature, mb2Equivalent);
  101. }
  102. /// <summary>
  103. /// Gets the registration status.
  104. /// </summary>
  105. /// <param name="feature">The feature.</param>
  106. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  107. /// <param name="version">The version of this feature</param>
  108. /// <returns>Task{MBRegistrationRecord}.</returns>
  109. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent, string version)
  110. {
  111. return GetRegistrationStatusInternal(feature, mb2Equivalent, version);
  112. }
  113. private Task<MBRegistrationRecord> GetSupporterRegistrationStatus()
  114. {
  115. return GetRegistrationStatusInternal("MBSupporter", null, _appHost.ApplicationVersion.ToString());
  116. }
  117. /// <summary>
  118. /// Gets or sets the supporter key.
  119. /// </summary>
  120. /// <value>The supporter key.</value>
  121. public string SupporterKey
  122. {
  123. get
  124. {
  125. return LicenseFile.RegKey;
  126. }
  127. set
  128. {
  129. if (value != LicenseFile.RegKey)
  130. {
  131. LicenseFile.RegKey = value;
  132. LicenseFile.Save();
  133. // re-load registration info
  134. Task.Run(() => LoadAllRegistrationInfo());
  135. }
  136. }
  137. }
  138. public async Task<SupporterInfo> GetSupporterInfo()
  139. {
  140. var key = SupporterKey;
  141. if (string.IsNullOrWhiteSpace(key))
  142. {
  143. return new SupporterInfo();
  144. }
  145. var data = new Dictionary<string, string>
  146. {
  147. { "key", key },
  148. };
  149. var url = MbAdmin.HttpsUrl + "/service/supporter/retrieve";
  150. using (var stream = await _httpClient.Post(url, data, CancellationToken.None).ConfigureAwait(false))
  151. {
  152. var response = _jsonSerializer.DeserializeFromStream<SuppporterInfoResponse>(stream);
  153. var info = new SupporterInfo
  154. {
  155. Email = response.email,
  156. PlanType = response.planType,
  157. SupporterKey = response.supporterKey,
  158. ExpirationDate = string.IsNullOrWhiteSpace(response.expDate) ? (DateTime?)null : DateTime.Parse(response.expDate),
  159. RegistrationDate = DateTime.Parse(response.regDate),
  160. IsActiveSupporter = IsMBSupporter
  161. };
  162. info.IsExpiredSupporter = info.ExpirationDate.HasValue && info.ExpirationDate < DateTime.UtcNow && !string.IsNullOrWhiteSpace(info.SupporterKey);
  163. return info;
  164. }
  165. }
  166. /// <summary>
  167. /// Register an app store sale with our back-end. It will validate the transaction with the store
  168. /// and then register the proper feature and then fill in the supporter key on success.
  169. /// </summary>
  170. /// <param name="parameters">Json parameters to send to admin server</param>
  171. public async Task RegisterAppStoreSale(string parameters)
  172. {
  173. var options = new HttpRequestOptions()
  174. {
  175. Url = AppstoreRegUrl,
  176. CancellationToken = CancellationToken.None
  177. };
  178. options.RequestHeaders.Add("X-Emby-Token", /*_appHost.SystemId*/ "08606E86D043");
  179. options.RequestContent = parameters;
  180. options.RequestContentType = "application/json";
  181. try
  182. {
  183. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  184. {
  185. var reg = _jsonSerializer.DeserializeFromStream<RegRecord>(response.Content);
  186. if (reg == null)
  187. {
  188. var msg = "Result from appstore registration was null.";
  189. _logger.Error(msg);
  190. throw new ApplicationException(msg);
  191. }
  192. if (!String.IsNullOrEmpty(reg.key))
  193. {
  194. SupporterKey = reg.key;
  195. }
  196. }
  197. }
  198. catch (ApplicationException)
  199. {
  200. SaveAppStoreInfo(parameters);
  201. throw;
  202. }
  203. catch (Exception e)
  204. {
  205. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  206. SaveAppStoreInfo(parameters);
  207. //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually.
  208. throw new ApplicationException("Error registering store sale");
  209. }
  210. }
  211. private void SaveAppStoreInfo(string info)
  212. {
  213. // Save all transaction information to a file
  214. try
  215. {
  216. File.WriteAllText(Path.Combine(_appPaths.ProgramDataPath, "apptrans-error.txt"), info);
  217. }
  218. catch (IOException)
  219. {
  220. }
  221. }
  222. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  223. string mb2Equivalent = null,
  224. string version = null)
  225. {
  226. var lastChecked = LicenseFile.LastChecked(feature);
  227. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  228. var reg = new RegRecord
  229. {
  230. // Cache the result for up to a week
  231. registered = lastChecked > DateTime.UtcNow.AddDays(-7)
  232. };
  233. var success = reg.registered;
  234. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)))
  235. {
  236. var data = new Dictionary<string, string>
  237. {
  238. { "feature", feature },
  239. { "key", SupporterKey },
  240. { "mac", _appHost.SystemId },
  241. { "systemid", _appHost.SystemId },
  242. { "mb2equiv", mb2Equivalent },
  243. { "ver", version },
  244. { "platform", _appHost.OperatingSystemDisplayName },
  245. { "isservice", _appHost.IsRunningAsService.ToString().ToLower() }
  246. };
  247. try
  248. {
  249. using (var json = await _httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
  250. {
  251. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  252. success = true;
  253. }
  254. if (reg.registered)
  255. {
  256. LicenseFile.AddRegCheck(feature);
  257. }
  258. else
  259. {
  260. LicenseFile.RemoveRegCheck(feature);
  261. }
  262. }
  263. catch (Exception e)
  264. {
  265. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  266. }
  267. }
  268. var record = new MBRegistrationRecord
  269. {
  270. IsRegistered = reg.registered,
  271. ExpirationDate = reg.expDate,
  272. RegChecked = true,
  273. RegError = !success
  274. };
  275. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  276. record.IsValid = !record.RegChecked || (record.IsRegistered || record.TrialVersion);
  277. return record;
  278. }
  279. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  280. {
  281. //don't set this until we've successfully obtained exp date
  282. if (!regChecked)
  283. {
  284. return false;
  285. }
  286. var isInTrial = expirationDate > DateTime.UtcNow;
  287. return (isInTrial && !isRegistered);
  288. }
  289. /// <summary>
  290. /// Resets the supporter info.
  291. /// </summary>
  292. private void ResetSupporterInfo()
  293. {
  294. _isMbSupporter = null;
  295. _isMbSupporterInitialized = false;
  296. }
  297. }
  298. }