1
0

ToolsController.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. using Masuit.MyBlogs.Core.Common;
  2. using Masuit.MyBlogs.Core.Configs;
  3. using Masuit.MyBlogs.Core.Models.ViewModel;
  4. using Masuit.Tools;
  5. using Masuit.Tools.Core.Validator;
  6. using Masuit.Tools.Models;
  7. using MaxMind.GeoIP2.Exceptions;
  8. using MaxMind.GeoIP2.Responses;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Newtonsoft.Json;
  12. using Polly;
  13. using System;
  14. using System.Net.Http;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using TimeZoneConverter;
  18. #if DEBUG
  19. #endif
  20. namespace Masuit.MyBlogs.Core.Controllers
  21. {
  22. /// <summary>
  23. /// 黑科技
  24. /// </summary>
  25. [Route("tools")]
  26. public class ToolsController : BaseController
  27. {
  28. private readonly HttpClient _httpClient;
  29. public ToolsController(IHttpClientFactory httpClientFactory)
  30. {
  31. _httpClient = httpClientFactory.CreateClient();
  32. }
  33. /// <summary>
  34. /// 获取ip地址详细信息
  35. /// </summary>
  36. /// <param name="ip"></param>
  37. /// <returns></returns>
  38. [Route("ip"), Route("ip/{ip?}", Order = 1), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "ip" }, VaryByHeader = "Cookie")]
  39. public async Task<ActionResult> GetIpInfo([IsIPAddress] string ip)
  40. {
  41. if (string.IsNullOrEmpty(ip))
  42. {
  43. ip = ClientIP;
  44. }
  45. if (ip.IsPrivateIP())
  46. {
  47. return Ok("内网IP");
  48. }
  49. ViewBag.IP = ip;
  50. var cityInfo = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(() => new CityResponse()).Execute(() => CommonHelper.MaxmindReader.City(ip));
  51. var location = ip.GetIPLocation();
  52. var address = new IpInfo()
  53. {
  54. CityInfo = cityInfo,
  55. Address = $"{location}(UTC{TZConvert.GetTimeZoneInfo(cityInfo.Location.TimeZone ?? "Asia/Shanghai").BaseUtcOffset.Hours:+#;-#;0})",
  56. Asn = ip.GetIPAsn(),
  57. IsProxy = location.Contains(new[] { "cloud", "Compute", "Serv", "Tech", "Solution", "Host", "云", "Data Services" }) || await ip.IsProxy()
  58. };
  59. if (Request.Method.Equals(HttpMethods.Get))
  60. {
  61. return View(address);
  62. }
  63. return Json(address);
  64. }
  65. /// <summary>
  66. /// 根据经纬度获取详细地理信息
  67. /// </summary>
  68. /// <param name="lat"></param>
  69. /// <param name="lng"></param>
  70. /// <returns></returns>
  71. [HttpGet("pos"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "lat", "lng" }, VaryByHeader = "Cookie")]
  72. public async Task<ActionResult> Position(string lat, string lng)
  73. {
  74. if (string.IsNullOrEmpty(lat) || string.IsNullOrEmpty(lng))
  75. {
  76. var ip = ClientIP;
  77. #if DEBUG
  78. var r = new Random();
  79. ip = $"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}";
  80. #endif
  81. var location = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(() => new CityResponse()).Execute(() => CommonHelper.MaxmindReader.City(ip));
  82. var address = new PhysicsAddress()
  83. {
  84. Status = 0,
  85. AddressResult = new AddressResult()
  86. {
  87. FormattedAddress = ip.GetIPLocation(),
  88. Location = new Location()
  89. {
  90. Lng = location.Location.Longitude ?? 0,
  91. Lat = location.Location.Latitude ?? 0
  92. }
  93. }
  94. };
  95. return View(address);
  96. }
  97. var s = await _httpClient.GetStringAsync($"http://api.map.baidu.com/geocoder/v2/?location={lat},{lng}&output=json&pois=1&ak={AppConfig.BaiduAK}", new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token).ContinueWith(t =>
  98. {
  99. if (t.IsCompletedSuccessfully)
  100. {
  101. return JsonConvert.DeserializeObject<PhysicsAddress>(t.Result);
  102. }
  103. return new PhysicsAddress();
  104. });
  105. return View(s);
  106. }
  107. /// <summary>
  108. /// 详细地理信息转经纬度
  109. /// </summary>
  110. /// <param name="addr"></param>
  111. /// <returns></returns>
  112. [Route("addr"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "addr" }, VaryByHeader = "Cookie")]
  113. public async Task<ActionResult> Address(string addr)
  114. {
  115. if (string.IsNullOrEmpty(addr))
  116. {
  117. var ip = ClientIP;
  118. #if DEBUG
  119. Random r = new Random();
  120. ip = $"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}";
  121. #endif
  122. var location = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(() => new CityResponse()).Execute(() => CommonHelper.MaxmindReader.City(ip));
  123. var address = new PhysicsAddress()
  124. {
  125. Status = 0,
  126. AddressResult = new AddressResult()
  127. {
  128. FormattedAddress = ip.GetIPLocation(),
  129. Location = new Location()
  130. {
  131. Lng = location.Location.Longitude ?? 0,
  132. Lat = location.Location.Latitude ?? 0
  133. }
  134. }
  135. };
  136. ViewBag.Address = address.AddressResult.FormattedAddress;
  137. if (Request.Method.Equals(HttpMethods.Get))
  138. {
  139. return View(address.AddressResult.Location);
  140. }
  141. return Json(address.AddressResult.Location);
  142. }
  143. ViewBag.Address = addr;
  144. var physicsAddress = await _httpClient.GetStringAsync($"http://api.map.baidu.com/geocoder/v2/?output=json&address={addr}&ak={AppConfig.BaiduAK}", new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token).ContinueWith(t =>
  145. {
  146. if (t.IsCompletedSuccessfully)
  147. {
  148. return JsonConvert.DeserializeObject<PhysicsAddress>(t.Result);
  149. }
  150. return new PhysicsAddress();
  151. });
  152. if (Request.Method.Equals(HttpMethods.Get))
  153. {
  154. return View(physicsAddress?.AddressResult?.Location);
  155. }
  156. return Json(physicsAddress?.AddressResult?.Location);
  157. }
  158. }
  159. }