LicenseUtils.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.NetworkInformation;
  8. namespace InABox.Core
  9. {
  10. public static class LicenseUtils
  11. {
  12. #region Mac Addresses
  13. public static String[] GetMacAddresses()
  14. {
  15. return NetworkInterface
  16. .GetAllNetworkInterfaces()
  17. .Where(nic =>
  18. nic.OperationalStatus == OperationalStatus.Up &&
  19. nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  20. .Select(nic => nic.GetPhysicalAddress().ToString()).ToArray();
  21. }
  22. public static bool ValidateMacAddresses(String[] addresses)
  23. {
  24. var hardware = GetMacAddresses();
  25. return hardware.Any(addresses.Contains);
  26. }
  27. #endregion
  28. #region License Generation
  29. public static LicenseData RenewLicense(LicenseData oldLicense, DateTime renewed, DateTime newExpiry, DateTime renewAvailable, String[] addresses)
  30. {
  31. return new LicenseData
  32. {
  33. LastRenewal = renewed,
  34. Expiry = newExpiry,
  35. CustomerID = oldLicense?.CustomerID ?? Guid.Empty,
  36. RenewalAvailable = renewAvailable,
  37. Addresses = addresses,
  38. IsDynamic = oldLicense?.IsDynamic ?? false
  39. };
  40. }
  41. private static readonly byte[] LicenseKey = Convert.FromBase64String("dCyTyQkj1o1rqJJQlT+Jcnkxr+OQnO4KCoF/b+6cx54=");
  42. public static string? EncryptLicenseRequest(LicenseRequest request)
  43. {
  44. return Encryption.EncryptV2(Serialization.Serialize(request), LicenseKey);
  45. }
  46. public static bool TryEncryptLicenseRequest(LicenseRequest request, [NotNullWhen(true)] out string? result, [NotNullWhen(false)] out string? error)
  47. {
  48. return Encryption.TryEncryptV2(Serialization.Serialize(request), LicenseKey, out result, out error);
  49. }
  50. /// <summary>
  51. /// Decrypts <paramref name="request"/>.
  52. /// </summary>
  53. /// <param name="request">The request to decrypt.</param>
  54. /// <returns>
  55. /// The new license request, or <see langword="null"/> if errors occurred.
  56. /// </returns>
  57. public static bool TryDecryptLicenseRequest(string data, [NotNullWhen(true)] out LicenseRequest? result, [NotNullWhen(false)] out string? error)
  58. {
  59. if (!Encryption.TryDecryptV2(data, LicenseKey, out var decrypted, out error))
  60. {
  61. result = null;
  62. return false;
  63. }
  64. result = Serialization.Deserialize<LicenseRequest>(decrypted);
  65. if(result == null)
  66. {
  67. error = "Request deserialization failed";
  68. return false;
  69. }
  70. return true;
  71. }
  72. /// <summary>
  73. /// Decrypts <paramref name="request"/>, throwing an <see cref="Exception"/> on fail.
  74. /// </summary>
  75. /// <param name="request">The data to decrypt.</param>
  76. /// <returns>
  77. /// The new license request.
  78. /// </returns>
  79. public static LicenseRequest DecryptLicenseRequest(string data)
  80. {
  81. if (!TryDecryptLicenseRequest(data, out var result, out var error))
  82. throw new Exception(error);
  83. return result;
  84. }
  85. /// <summary>
  86. /// Encrypts the license data.
  87. /// </summary>
  88. /// <param name="license">The license to encrypt.</param>
  89. /// <returns>
  90. /// The encrypted data.
  91. /// </returns>
  92. public static string? EncryptLicense(LicenseData license)
  93. {
  94. return Encryption.EncryptV2(Serialization.Serialize(license), LicenseKey);
  95. }
  96. public static bool TryEncryptLicense(LicenseData license, [NotNullWhen(true)] out string? result, [NotNullWhen(false)] out string? error)
  97. {
  98. return Encryption.TryEncryptV2(Serialization.Serialize(license), LicenseKey, out result, out error);
  99. }
  100. /// <summary>
  101. /// Decrypts <paramref name="license"/>.
  102. /// </summary>
  103. /// <param name="license">The license to decrypt.</param>
  104. /// <returns>
  105. /// The new license data, or <see langword="null"/> if errors occurred.
  106. /// </returns>
  107. public static bool TryDecryptLicense(string data, [NotNullWhen(true)] out LicenseData? result, [NotNullWhen(false)] out string? error)
  108. {
  109. if (!Encryption.TryDecryptV2(data, LicenseKey, out var decrypted, out error))
  110. {
  111. result = null;
  112. return false;
  113. }
  114. result = Serialization.Deserialize<LicenseData>(decrypted);
  115. if(result == null)
  116. {
  117. error = "License deserialization failed";
  118. return false;
  119. }
  120. return true;
  121. }
  122. /// <summary>
  123. /// Decrypts <paramref name="license"/>, throwing an <see cref="Exception"/> on fail.
  124. /// </summary>
  125. /// <param name="license">The license to decrypt.</param>
  126. /// <returns>
  127. /// The new license data.
  128. /// </returns>
  129. public static LicenseData DecryptLicense(string data)
  130. {
  131. if (!TryDecryptLicense(data, out var result, out var error))
  132. throw new Exception(error);
  133. return result;
  134. }
  135. #endregion
  136. #region Fees & Discounts
  137. private static readonly Dictionary<String, double> _licensefees = new Dictionary<String, double>();
  138. private static readonly Dictionary<int, double> _periods = new Dictionary<int, double>();
  139. private static readonly Dictionary<int, double> _userDiscounts = new Dictionary<int, double>();
  140. public static double GetLicenseFee(String type)
  141. {
  142. return _licensefees.GetValueOrDefault(type, 0);
  143. }
  144. public static double GetLicenseFee<T>() where T : LicenseToken
  145. {
  146. return GetLicenseFee(typeof(T).EntityName());
  147. }
  148. public static IEnumerable<String> LicenseTypes()
  149. {
  150. return _licensefees.Keys;
  151. }
  152. public static double GetUserDiscount(int users)
  153. {
  154. var key = _userDiscounts.Keys
  155. .Where(x => x <= users)
  156. .DefaultIfEmpty(-1)
  157. .Max();
  158. if (key == -1)
  159. return 0;
  160. return _userDiscounts[key];
  161. }
  162. public static double GetTimeDiscount(int months)
  163. {
  164. var period = _periods.Keys
  165. .Where(x => x <= months)
  166. .DefaultIfEmpty(-1)
  167. .Max();
  168. if (period == -1)
  169. return 0;
  170. return _periods[period];
  171. }
  172. public static IEnumerable<int> TimeDiscountLevels()
  173. {
  174. return _periods.Keys;
  175. }
  176. public static double CalculateLicenseFee(Dictionary<String, int> licenses, int time)
  177. {
  178. double licensefee = 0.00F;
  179. foreach (var license in licenses.Keys)
  180. if (_licensefees.ContainsKey(license))
  181. licensefee += _licensefees[license] * licenses[license];
  182. var users = licenses.Values.OrderBy(x => x).LastOrDefault();
  183. var userdiscount = GetUserDiscount(users);
  184. var timediscount = GetTimeDiscount(time);
  185. var result = licensefee * ((100.0F - userdiscount) / 100.0F) * ((100.0F - timediscount) / 100.0F);
  186. return result;
  187. }
  188. public static void LoadSummary(LicenseFeeResponse feeResponse)
  189. {
  190. _licensefees.Clear();
  191. _periods.Clear();
  192. _userDiscounts.Clear();
  193. foreach (var license in feeResponse.LicenseFees)
  194. _licensefees[license.Key] = license.Value;
  195. foreach (var (months, period) in feeResponse.TimeDiscounts)
  196. _periods[months] = period;
  197. foreach (var (users, discount) in feeResponse.UserDiscounts)
  198. _userDiscounts[users] = discount;
  199. }
  200. /// <summary>
  201. /// Gets a map from entities to their associated licenses.
  202. /// </summary>
  203. /// <returns>A map of entity types to license types.</returns>
  204. public static Dictionary<Type, Type> LicenseMap()
  205. {
  206. var result = new Dictionary<Type, Type>();
  207. var entities = CoreUtils.Entities.Where(x => x.IsClass && !x.IsGenericType && x.IsSubclassOf(typeof(Entity)));
  208. foreach (var entity in entities)
  209. {
  210. var lic = entity.GetInterfaces()
  211. .FirstOrDefault(x => x.IsConstructedGenericType && x.GetGenericTypeDefinition() == typeof(ILicense<>));
  212. result[entity] = lic?.GenericTypeArguments.FirstOrDefault();
  213. }
  214. return result;
  215. }
  216. public static void SaveLicenseSummary(string filename)
  217. {
  218. var entitymap = LicenseMap();
  219. var summary = new List<string> { "\"License Token\",\"Class Name\"" };
  220. foreach (var mapentry in entitymap.OrderBy(x => x.Value))
  221. summary.Add(string.Format("\"{0}\",\"{1}\"", mapentry.Value?.GetCaption(), mapentry.Value.EntityName()));
  222. File.WriteAllLines(filename, summary.ToArray());
  223. }
  224. public static void Reset()
  225. {
  226. _licensefees.Clear();
  227. _periods.Clear();
  228. _userDiscounts.Clear();
  229. }
  230. #endregion
  231. }
  232. public class LicenseFeeRequest
  233. {
  234. public Guid RegistrationID { get; set; }
  235. }
  236. public class LicenseFeeResponse
  237. {
  238. public LicenseFeeResponse()
  239. {
  240. LicenseFees = new Dictionary<string, double>();
  241. TimeDiscounts = new Dictionary<int, double>();
  242. UserDiscounts = new Dictionary<int, double>();
  243. }
  244. public Dictionary<string, double> LicenseFees { get; set; }
  245. public Dictionary<int, double> TimeDiscounts { get; set; }
  246. public Dictionary<int, double> UserDiscounts { get; set; }
  247. }
  248. }