HomeController.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using Applications.UniversalApi_WebConsole_App.Models;
  9. using Edge.Core;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.AspNetCore.Mvc.ApiExplorer;
  12. using Microsoft.Extensions.Configuration;
  13. using Microsoft.Extensions.Logging;
  14. using Newtonsoft.Json;
  15. using RestSharp;
  16. namespace Applications.UniversalApi_WebConsole_App.Controllers
  17. {
  18. public class HomeController : Controller
  19. {
  20. private readonly ILogger<HomeController> _logger;
  21. JsonSerializerSettings _jsonSetting =
  22. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
  23. private readonly IApiDescriptionGroupCollectionProvider _apiDescriptionsProvider;
  24. private readonly string _apiBaseAddress;
  25. private string _checkLicenseUrl;
  26. private string _verifyLicenseUrl;
  27. private readonly string _serviceDiscoveryUrl;
  28. public HomeController(ILogger<HomeController> logger,
  29. IApiDescriptionGroupCollectionProvider apiDescriptionsProvider,
  30. IConfiguration configuration)
  31. {
  32. _logger = logger;
  33. _apiDescriptionsProvider = apiDescriptionsProvider;
  34. _apiBaseAddress = configuration.GetValue<string>("BaseUrl");
  35. _checkLicenseUrl = configuration.GetValue<string>("CheckLicenseUrl");
  36. _verifyLicenseUrl = configuration.GetValue<string>("VerifyLicenseUrl");
  37. _serviceDiscoveryUrl = configuration.GetValue<string>("ServiceDiscoveryUrl");
  38. }
  39. public async Task<IActionResult> Index()
  40. {
  41. var applicableApiDescriptions = _apiDescriptionsProvider.ApiDescriptionGroups.Items
  42. .SelectMany(group => group.Items);
  43. if (await CheckLicense() == true)
  44. {
  45. return View("Index", _apiDescriptionsProvider.ApiDescriptionGroups.Items
  46. .SelectMany(group => group.Items));
  47. }
  48. else
  49. {
  50. return View("InputLicense", Licensing.Instance().GetMacAddress(_logger));
  51. }
  52. }
  53. public IActionResult Privacy()
  54. {
  55. return View();
  56. }
  57. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  58. public IActionResult Error()
  59. {
  60. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  61. }
  62. public async Task<IActionResult> InputLicense()
  63. {
  64. return View("InputLicense");
  65. }
  66. public async Task<IActionResult> SaveLicense(string license)
  67. {
  68. if (await LicenseVerify(license) == true)
  69. {
  70. return RedirectToAction(nameof(Index), _apiDescriptionsProvider.ApiDescriptionGroups.Items.SelectMany(group => group.Items));
  71. }
  72. else
  73. {
  74. return View("InputLicense");
  75. }
  76. }
  77. private async Task<bool> CheckLicense()
  78. {
  79. var result = false;
  80. var path = await getServiceUrl("webapi", "CheckLicense", "LicensingApp");
  81. if (path != string.Empty)
  82. {
  83. _checkLicenseUrl = path;
  84. }
  85. try
  86. {
  87. var restClient = new RestClient(_apiBaseAddress);
  88. RestRequest request = new RestRequest(_checkLicenseUrl, Method.POST);
  89. request.AddHeader("Content-Type", "application/json");
  90. request.AddJsonBody("");
  91. request.RequestFormat = DataFormat.Json;
  92. var response = await restClient.ExecuteTaskAsync(request);
  93. if (response.StatusCode != System.Net.HttpStatusCode.OK)
  94. {
  95. _logger.LogInformation($"CheckLicense {_checkLicenseUrl} with Status code: " + response.StatusCode);
  96. }
  97. else
  98. {
  99. result = JsonConvert.DeserializeObject<bool>(response.Content);
  100. }
  101. }
  102. catch (Exception _)
  103. {
  104. }
  105. return result;
  106. }
  107. private async Task<bool> LicenseVerify(string license)
  108. {
  109. var result = false;
  110. try
  111. {
  112. var path = await getServiceUrl("webapi", "VerifyLicense", "LicensingApp");
  113. if (path != string.Empty)
  114. {
  115. _verifyLicenseUrl = path;
  116. }
  117. var restClient = new RestClient(_apiBaseAddress);
  118. RestRequest request = new RestRequest(_verifyLicenseUrl, Method.POST);
  119. request.AddHeader("Content-Type", "application/json");
  120. request.AddJsonBody(license);
  121. request.RequestFormat = DataFormat.Json;
  122. var response = await restClient.ExecuteTaskAsync(request);
  123. if (response.StatusCode != System.Net.HttpStatusCode.OK)
  124. {
  125. _logger.LogInformation($"LicenseVerify {_verifyLicenseUrl} with Status code: " + response.StatusCode);
  126. }
  127. else
  128. {
  129. result = JsonConvert.DeserializeObject<bool>(response.Content);
  130. }
  131. }
  132. catch (Exception _)
  133. {
  134. }
  135. return result;
  136. }
  137. /// <summary>
  138. /// serviceType canbe "webapi"/"localMqtt"/"remotemqtt"
  139. /// </summary>
  140. /// <param name="serviceType"></param>
  141. /// <param name="apiName"></param>
  142. /// <param name="tag"></param>
  143. /// <returns></returns>
  144. private async Task<string> getServiceUrl(string serviceType,string apiName,string tag)
  145. {
  146. var result = string.Empty;
  147. object[] requestBody = new object[]{ serviceType, new object[] { tag} };
  148. try
  149. {
  150. var restClient = new RestClient(_apiBaseAddress);
  151. RestRequest request = new RestRequest(_serviceDiscoveryUrl, Method.POST);
  152. request.AddHeader("Content-Type", "application/json");
  153. request.AddJsonBody(requestBody);
  154. request.RequestFormat = DataFormat.Json;
  155. var response = await restClient.ExecuteTaskAsync(request);
  156. if (response.StatusCode != System.Net.HttpStatusCode.OK)
  157. {
  158. _logger.LogInformation($"serviceDiscovery {_serviceDiscoveryUrl} with Status code: " + response.StatusCode);
  159. }
  160. else
  161. {
  162. var data = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(response.Content);
  163. if (data.Count > 0)
  164. {
  165. foreach (var d in data)
  166. {
  167. if (d["ApiName"].ToString() == apiName)
  168. {
  169. result = d["Path"].ToString().Substring(1);
  170. break;
  171. }
  172. }
  173. }
  174. }
  175. }
  176. catch (Exception _)
  177. {
  178. }
  179. return result;
  180. }
  181. }
  182. }