浏览代码

一点小优化

懒得勤快 4 年之前
父节点
当前提交
5847037e70

+ 42 - 23
src/Masuit.MyBlogs.Core/Common/CommonHelper.cs

@@ -8,6 +8,7 @@ using Masuit.Tools;
 using Masuit.Tools.Media;
 using MaxMind.GeoIP2;
 using MaxMind.GeoIP2.Exceptions;
+using MaxMind.GeoIP2.Model;
 using MaxMind.GeoIP2.Responses;
 using Microsoft.Extensions.DependencyInjection;
 using Polly;
@@ -21,6 +22,7 @@ using System.Net;
 using System.Net.Http;
 using System.Net.Sockets;
 using System.Text;
+using System.Threading;
 using System.Threading.Tasks;
 using TimeZoneConverter;
 
@@ -143,17 +145,24 @@ namespace Masuit.MyBlogs.Core.Common
         /// 是否是代理ip
         /// </summary>
         /// <param name="ip"></param>
+        /// <param name="cancellationToken"></param>
         /// <returns></returns>
-        public static async Task<bool> IsProxy(this IPAddress ip)
+        public static async Task<bool> IsProxy(this IPAddress ip, CancellationToken cancellationToken = default)
         {
             var httpClient = Startup.ServiceProvider.GetRequiredService<IHttpClientFactory>().CreateClient();
             httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.62");
-            var html = await httpClient.GetStringAsync("https://ipinfo.io/" + ip);
-            var ctx = BrowsingContext.New(Configuration.Default);
-            var doc = await ctx.OpenAsync(res => res.Content(html));
-            var isAnycast = doc.DocumentElement.QuerySelectorAll(".title").Where(e => e.TextContent.Contains("Anycast")).Select(e => e.Parent).Any(n => n.TextContent.Contains("True"));
-            var isproxy = doc.DocumentElement.QuerySelectorAll("#block-privacy img").Any(e => e.OuterHtml.Contains("right"));
-            return isAnycast || isproxy;
+            return await httpClient.GetStringAsync("https://ipinfo.io/" + ip, cancellationToken).ContinueWith(t =>
+            {
+                if (t.IsCompletedSuccessfully)
+                {
+                    var ctx = BrowsingContext.New(Configuration.Default);
+                    var doc = ctx.OpenAsync(res => res.Content(t.Result)).Result;
+                    var isAnycast = doc.DocumentElement.QuerySelectorAll(".title").Where(e => e.TextContent.Contains("Anycast")).Select(e => e.Parent).Any(n => n.TextContent.Contains("True"));
+                    var isproxy = doc.DocumentElement.QuerySelectorAll("#block-privacy img").Any(e => e.OuterHtml.Contains("right"));
+                    return isAnycast || isproxy;
+                }
+                return false;
+            });
         }
 
         public static AsnResponse GetIPAsn(this string ip)
@@ -192,6 +201,11 @@ namespace Masuit.MyBlogs.Core.Common
             {
                 return new IPLocation("内网", null, null, "内网IP", null);
             }
+
+            var city = GetCityResp(ip);
+            var asn = GetIPAsn(ip);
+            var countryName = city.Country.Names.GetValueOrDefault("zh-CN") ?? city.Country.Name;
+            var cityName = city.City.Names.GetValueOrDefault("zh-CN") ?? city.City.Name;
             switch (ip.AddressFamily)
             {
                 case AddressFamily.InterNetworkV6 when ip.IsIPv4MappedToIPv6:
@@ -201,19 +215,22 @@ namespace Masuit.MyBlogs.Core.Common
                     var parts = IPSearcher.MemorySearch(ip.ToString())?.Region.Split('|');
                     if (parts != null)
                     {
-                        var asn = GetIPAsn(ip);
-                        var network = parts[^1] == "0" ? asn.AutonomousSystemOrganization : parts[^1] + "(" + asn.AutonomousSystemOrganization + ")";
-                        var city = new Lazy<CityResponse>(() => GetCityResp(ip));
-                        parts[0] = parts[0] != "0" ? parts[0] : city.Value.Country.Names.GetValueOrDefault("zh-CN");
-                        parts[3] = parts[3] != "0" ? parts[3] : city.Value.City.Names.GetValueOrDefault("zh-CN");
-                        return new IPLocation(parts[0], parts[2], parts[3], network, asn.AutonomousSystemNumber);
+                        var network = parts[^1] == "0" ? asn.AutonomousSystemOrganization : parts[^1] + "/" + asn.AutonomousSystemOrganization;
+                        parts[0] = parts[0] != "0" ? parts[0] : countryName;
+                        parts[3] = parts[3] != "0" ? parts[3] : cityName;
+                        return new IPLocation(parts[0], parts[2], parts[3], network.TrimEnd('/'), asn.AutonomousSystemNumber)
+                        {
+                            Address2 = countryName + cityName,
+                            Coodinate = city.Location
+                        };
                     }
 
                     goto default;
                 default:
-                    var cityResp = GetCityResp(ip);
-                    var asnResp = GetIPAsn(ip);
-                    return new IPLocation(cityResp.Country.Names.GetValueOrDefault("zh-CN"), null, cityResp.City.Names.GetValueOrDefault("zh-CN"), asnResp.AutonomousSystemOrganization, asnResp.AutonomousSystemNumber);
+                    return new IPLocation(countryName, null, cityName, asn.AutonomousSystemOrganization, asn.AutonomousSystemNumber)
+                    {
+                        Coodinate = city.Location
+                    };
             }
         }
 
@@ -407,24 +424,26 @@ namespace Masuit.MyBlogs.Core.Common
         public string City { get; set; }
         public string ISP { get; set; }
         public long? ASN { get; set; }
-        public string Location => new[] { Country, Province, City }.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("");
+        public string Address => new[] { Country, Province, City }.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("");
+        public string Address2 { get; set; }
         public string Network => ASN.HasValue ? ISP + "(AS" + ASN + ")" : ISP;
+        public Location Coodinate { get; set; }
 
         public override string ToString()
         {
-            string location = Location;
+            string address = Address;
             string network = Network;
-            if (string.IsNullOrWhiteSpace(location))
+            if (string.IsNullOrWhiteSpace(address))
             {
-                location = string.Intern("未知地区");
+                address = "未知地区";
             }
 
             if (string.IsNullOrWhiteSpace(network))
             {
-                network = string.Intern("未知网络");
+                network = "未知网络";
             }
 
-            return location + "|" + network;
+            return new[] { address, Address2, network }.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("|");
         }
 
         public static implicit operator string(IPLocation entry)
@@ -434,7 +453,7 @@ namespace Masuit.MyBlogs.Core.Common
 
         public void Deconstruct(out string location, out string network, out string info)
         {
-            location = Location;
+            location = new[] { Address, Address2 }.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("|");
             network = Network;
             info = ToString();
         }

+ 10 - 10
src/Masuit.MyBlogs.Core/Common/HttpContextExtension.cs

@@ -30,17 +30,17 @@ namespace Masuit.MyBlogs.Core.Common
             if (robotUA)
             {
                 var nslookup = new LookupClient();
-                using var cts = new CancellationTokenSource(100);
+                using var cts = new CancellationTokenSource(1000);
                 return nslookup.QueryReverseAsync(req.HttpContext.Connection.RemoteIpAddress, cts.Token).ContinueWith(t => t.IsCompletedSuccessfully && t.Result.Answers.Any(r => r.ToString().Contains(new[]
-                   {
-                        "baidu.com",
-                        "google.com",
-                        "bing.com",
-                        "sogou.com",
-                        "soso.com",
-                        "yandex.com",
-                        "sm.cn"
-                     }))).Result;
+                {
+                    "baidu.com",
+                    "google.com",
+                    "bing.com",
+                    "sogou.com",
+                    "soso.com",
+                    "yandex.com",
+                    "sm.cn"
+                 }))).Result;
             }
 
             return robotUA;

+ 1 - 1
src/Masuit.MyBlogs.Core/Controllers/ErrorController.cs

@@ -91,7 +91,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     case AccessDenyException:
                         var entry = ip.GetIPLocation();
                         var tips = Template.Create(CommonHelper.SystemSettings.GetOrAdd("AccessDenyTips", @"<h4>遇到了什么问题?</h4>
-                <h4>基于主观因素考虑,您所在的地区暂时不允许访问本站,如有疑问,请联系站长!或者请联系站长开通本站的访问权限!</h4>")).Set("clientip", ip.ToString()).Set("location", entry.Location).Set("network", entry.Network).Render();
+                <h4>基于主观因素考虑,您所在的地区暂时不允许访问本站,如有疑问,请联系站长!或者请联系站长开通本站的访问权限!</h4>")).Set("clientip", ip.ToString()).Set("location", entry.Address).Set("network", entry.Network).Render();
                         Response.StatusCode = 403;
                         return View("AccessDeny", tips);
                     case TempDenyException:

+ 0 - 1
src/Masuit.MyBlogs.Core/Controllers/SearchController.cs

@@ -6,7 +6,6 @@ using Masuit.MyBlogs.Core.Models.DTO;
 using Masuit.MyBlogs.Core.Models.Entity;
 using Masuit.MyBlogs.Core.Models.Enum;
 using Masuit.MyBlogs.Core.Models.ViewModel;
-using Masuit.Tools;
 using Masuit.Tools.Core.Net;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;

+ 0 - 1
src/Masuit.MyBlogs.Core/Controllers/SubscribeController.cs

@@ -22,7 +22,6 @@ namespace Masuit.MyBlogs.Core.Controllers
     /// <summary>
     /// 订阅服务
     /// </summary>
-    [ServiceFilter(typeof(FirewallAttribute))]
     public class SubscribeController : Controller
     {
         public IPostService PostService { get; set; }

+ 22 - 17
src/Masuit.MyBlogs.Core/Controllers/ToolsController.cs

@@ -1,25 +1,26 @@
-using Masuit.MyBlogs.Core.Common;
+using DnsClient;
+using Masuit.MyBlogs.Core.Common;
 using Masuit.MyBlogs.Core.Configs;
 using Masuit.MyBlogs.Core.Models.ViewModel;
 using Masuit.Tools;
+using Masuit.Tools.AspNetCore.Mime;
 using Masuit.Tools.Core.Validator;
 using Masuit.Tools.Models;
 using MaxMind.GeoIP2.Exceptions;
 using MaxMind.GeoIP2.Responses;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
+using Microsoft.Net.Http.Headers;
 using Newtonsoft.Json;
 using Polly;
 using System;
+using System.Linq;
 using System.Net;
 using System.Net.Http;
 using System.Threading;
 using System.Threading.Tasks;
 using TimeZoneConverter;
 
-#if DEBUG
-#endif
-
 namespace Masuit.MyBlogs.Core.Controllers
 {
     /// <summary>
@@ -55,23 +56,27 @@ namespace Masuit.MyBlogs.Core.Controllers
 
             var ipAddress = IPAddress.Parse(ip);
             ViewBag.IP = ip;
-            var cityInfo = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(() => new CityResponse()).Execute(() => CommonHelper.MaxmindReader.City(ipAddress));
             var loc = ipAddress.GetIPLocation();
             var asn = ipAddress.GetIPAsn();
-            var address = new IpInfo()
+            var nslookup = new LookupClient();
+            using var cts = new CancellationTokenSource(2000);
+            var domain = await nslookup.QueryReverseAsync(ipAddress, cts.Token).ContinueWith(t => t.IsCompletedSuccessfully ? t.Result.Answers.Select(r => r.ToString()).Join("; ") : "无");
+            var address = new IpInfo
             {
-                Location = cityInfo.Location,
-                Address = loc.Location,
-                Network = new NetworkInfo()
+                Location = loc.Coodinate,
+                Address = loc.Address,
+                Address2 = loc.Address2,
+                Network = new NetworkInfo
                 {
                     Asn = asn.AutonomousSystemNumber,
                     Router = asn.Network + "",
-                    Organization = asn.AutonomousSystemOrganization
+                    Organization = loc.ISP
                 },
-                TimeZone = $"UTC{TZConvert.GetTimeZoneInfo(cityInfo.Location.TimeZone ?? "Asia/Shanghai").BaseUtcOffset.Hours:+#;-#;0}",
-                IsProxy = loc.Network.Contains(new[] { "cloud", "Compute", "Serv", "Tech", "Solution", "Host", "云", "Datacenter", "Data Center", "Business" }) || await ipAddress.IsProxy()
+                TimeZone = loc.Coodinate.TimeZone + $"  UTC{TZConvert.GetTimeZoneInfo(loc.Coodinate.TimeZone ?? "Asia/Shanghai").BaseUtcOffset.Hours:+#;-#;0}",
+                IsProxy = loc.Network.Contains(new[] { "cloud", "Compute", "Serv", "Tech", "Solution", "Host", "云", "Datacenter", "Data Center", "Business" }) || domain.Length > 1 || await ipAddress.IsProxy(cts.Token),
+                Domain = domain
             };
-            if (Request.Method.Equals(HttpMethods.Get))
+            if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
             {
                 return View(address);
             }
@@ -101,7 +106,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     Status = 0,
                     AddressResult = new AddressResult()
                     {
-                        FormattedAddress = ip.GetIPLocation(),
+                        FormattedAddress = IPAddress.Parse(ip).GetIPLocation().Address,
                         Location = new Location()
                         {
                             Lng = location.Location.Longitude ?? 0,
@@ -146,7 +151,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     Status = 0,
                     AddressResult = new AddressResult()
                     {
-                        FormattedAddress = ip.GetIPLocation(),
+                        FormattedAddress = IPAddress.Parse(ip).GetIPLocation().Address,
                         Location = new Location()
                         {
                             Lng = location.Location.Longitude ?? 0,
@@ -155,7 +160,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     }
                 };
                 ViewBag.Address = address.AddressResult.FormattedAddress;
-                if (Request.Method.Equals(HttpMethods.Get))
+                if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
                 {
                     return View(address.AddressResult.Location);
                 }
@@ -173,7 +178,7 @@ namespace Masuit.MyBlogs.Core.Controllers
 
                  return new PhysicsAddress();
              });
-            if (Request.Method.Equals(HttpMethods.Get))
+            if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
             {
                 return View(physicsAddress?.AddressResult?.Location);
             }

+ 2 - 6
src/Masuit.MyBlogs.Core/Controllers/UploadController.cs

@@ -20,7 +20,6 @@ using System;
 using System.ComponentModel.DataAnnotations;
 using System.IO;
 using System.Linq;
-using System.Text;
 using System.Text.RegularExpressions;
 using System.Threading;
 using System.Threading.Tasks;
@@ -39,15 +38,12 @@ namespace Masuit.MyBlogs.Core.Controllers
 
         public ActionResult ResultData(object data, bool isTrue = true, string message = "")
         {
-            return Content(JsonConvert.SerializeObject(new
+            return Json(new
             {
                 Success = isTrue,
                 Message = message,
                 Data = data
-            }, new JsonSerializerSettings
-            {
-                MissingMemberHandling = MissingMemberHandling.Ignore
-            }), "application/json", Encoding.UTF8);
+            });
         }
 
         #region Word上传转码

+ 1 - 1
src/Masuit.MyBlogs.Core/Extensions/Firewall/FirewallAttribute.cs

@@ -63,7 +63,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall
                 throw new AccessDenyException("访问地区限制");
             }
 
-            if (Regex.IsMatch(request.Method, "OPTIONS|HEAD", RegexOptions.IgnoreCase) || agent.IsRobot)
+            if (Regex.IsMatch(request.Method, "OPTIONS|HEAD", RegexOptions.IgnoreCase) || request.IsRobot())
             {
                 return;
             }

+ 1 - 1
src/Masuit.MyBlogs.Core/Extensions/TranslateMiddleware.cs

@@ -37,7 +37,7 @@ namespace Masuit.MyBlogs.Core.Extensions
             lang ??= context.Request.Cookies["lang"];
             if (string.IsNullOrEmpty(lang))
             {
-                if (context.Request.Location().Location.Contains(new[] { "台湾", "香港", "澳门", "Taiwan", "TW", "HongKong", "HK" }))
+                if (context.Request.Location().Address.Contains(new[] { "台湾", "香港", "澳门", "Taiwan", "TW", "HongKong", "HK" }))
                 {
                     return Traditional(context);
                 }

+ 2 - 2
src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.csproj

@@ -2,7 +2,7 @@
 
     <PropertyGroup>
         <TargetFramework>net5.0</TargetFramework>
-        <ServerGarbageCollection>false</ServerGarbageCollection>
+        <ServerGarbageCollection>true</ServerGarbageCollection>
         <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
         <Authors>懒得勤快</Authors>
         <Product>懒得勤快的博客</Product>
@@ -35,7 +35,7 @@
         <PackageReference Include="CLRStats" Version="1.0.0" />
         <PackageReference Include="CSRedisCore" Version="3.6.6" />
         <PackageReference Include="EFCoreSecondLevelCacheInterceptor" Version="3.1.2" />
-        <PackageReference Include="Hangfire" Version="1.7.24" />
+        <PackageReference Include="Hangfire" Version="1.7.25" />
         <PackageReference Include="Hangfire.Autofac" Version="2.3.1" />
         <PackageReference Include="Hangfire.MemoryStorage" Version="1.7.0" />
         <PackageReference Include="htmldiff.net-core" Version="1.3.6" />

+ 2 - 0
src/Masuit.MyBlogs.Core/Models/ViewModel/IpInfo.cs

@@ -9,6 +9,8 @@ namespace Masuit.MyBlogs.Core.Models.ViewModel
         public NetworkInfo Network { get; set; }
         public bool IsProxy { get; set; }
         public string TimeZone { get; set; }
+        public string Domain { get; set; }
+        public string Address2 { get; set; }
     }
 
     public class NetworkInfo

+ 1 - 1
src/Masuit.MyBlogs.Core/Views/Dashboard/Counter.razor

@@ -56,7 +56,7 @@
             <th>@_driveInfos.Select(kv => kv.Name + " " + (kv.TotalSize * 1.0 / 1073741824).ToDecimal(2) + "GB").Join(" | ")</th>
             <td>磁盘剩余空间</td>
             <th>@_driveInfos.Select(kv => kv.Name + " " + (kv.TotalFreeSpace * 1.0 / 1073741824).ToDecimal(2) + "GB").Join(" | ")</th>
-            <td>磁盘使用率</td>
+            <td>磁盘用率</td>
             <th>@_driveInfos.Select(kv => kv.Name + " " + (kv.AvailableFreeSpace * 1m / kv.TotalSize).ToString("P")).Join(" | ")</th>
         </tr>
         <tr>

+ 9 - 1
src/Masuit.MyBlogs.Core/Views/Tools/GetIPInfo.cshtml

@@ -45,9 +45,13 @@
             <td>@Model.Network.Asn</td>
         </tr>
         <tr>
-            <td>参考地理位置:</td>
+            <td>参考地理位置1:</td>
             <td>@Model.Address</td>
         </tr>
+        <tr>
+            <td>参考地理位置2:</td>
+            <td>@Model.Address2</td>
+        </tr>
         <tr>
             <td>时区:</td>
             <td>@Model.TimeZone</td>
@@ -60,6 +64,10 @@
             <td>代理或任播节点:</td>
             <td>@Model.IsProxy</td>
         </tr>
+        <tr>
+            <td>域名解析:</td>
+            <td>@Model.Domain</td>
+        </tr>
     </table>
 </div>
 <div class="container-fluid">

+ 20 - 1
src/Masuit.MyBlogs.Core/wwwroot/Scripts/global/scripts.js

@@ -173,6 +173,17 @@ var clearSelect= "getSelection" in window ? function(){
  document.selection.empty();
 };
 
+function hackClip() {
+    let transfer = document.createElement('input');
+    document.body.appendChild(transfer);
+    transfer.value = '1';
+    transfer.select();
+    if (document.execCommand('copy')) {
+        document.execCommand('copy');
+    }
+    document.body.removeChild(transfer);
+}
+
 /**禁止复制 */
 function CopyrightProtect() {
     setInterval(function() {
@@ -198,14 +209,17 @@ function CopyrightProtect() {
                     return false;
                 }
             }
-            document.ondragstart=function () {
+            document.ondragstart=async function () {
+                hackClip();
                 return false;
             }
             $(".article-content").on("copy",function (e) {
+                hackClip();
                 e.returnValue = false;
                 return false;
             });
             document.oncontextmenu = function (e) {
+                hackClip();
                 e.returnValue = false;
                 return false;
             }
@@ -231,10 +245,12 @@ function CopyrightProtect4Editor() {
                 }
             }
             document.getElementById("ueditor_0").contentWindow.document.body.ondragstart = function (e) {
+                hackClip();
                 e.returnValue = false;
                 return false;
             }
             document.getElementById("ueditor_0").contentWindow.document.body.oncopy = function (e) {
+                hackClip();
                 e.returnValue = false;
                 return false;
             }
@@ -269,13 +285,16 @@ function GlobalCopyrightProtect() {
                 }
             }
             document.ondragstart=function () {
+                hackClip();
                 return false;
             }
             $(".article-content").on("copy",function (e) {
+                hackClip();
                 e.returnValue = false;
                 return false;
             });
             document.oncontextmenu = function () {
+                hackClip();
                 event.returnValue = false;
                 return false;
             }