Przeglądaj źródła

IP库只使用maxmind

懒得勤快 10 miesięcy temu
rodzic
commit
3ce511d341

+ 17 - 51
src/Masuit.MyBlogs.Core/Common/CommonHelper.cs

@@ -52,7 +52,7 @@ namespace Masuit.MyBlogs.Core.Common
             ModRegex = ReadFile(Path.Combine(AppContext.BaseDirectory + "App_Data", "mod.txt"));
             DenyIP = ReadFile(Path.Combine(AppContext.BaseDirectory + "App_Data", "denyip.txt"));
             var lines = File.Open(Path.Combine(AppContext.BaseDirectory + "App_Data", "DenyIPRange.txt"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite).ReadAllLines(Encoding.UTF8);
-            DenyIPRange = new Dictionary<string, string>();
+            DenyIPRange = [];
             foreach (var line in lines)
             {
                 try
@@ -65,7 +65,7 @@ namespace Masuit.MyBlogs.Core.Common
                 }
             }
 
-            IPWhiteList = ReadFile(Path.Combine(AppContext.BaseDirectory + "App_Data", "whitelist.txt")).Split(',', ',').ToList();
+            IPWhiteList = [.. ReadFile(Path.Combine(AppContext.BaseDirectory + "App_Data", "whitelist.txt")).Split(',', ',')];
             Areas = JsonConvert.DeserializeObject<HashSet<Area>>(ReadFile(Path.Combine(AppContext.BaseDirectory + "App_Data", "areas.json")));
         }
 
@@ -121,10 +121,8 @@ namespace Masuit.MyBlogs.Core.Common
             return DenyIP.Contains(ip) || DenyIPRange.AsParallel().Any(kv => kv.Key.StartsWith(ip.Split('.')[0]) && ip.IpAddressInRange(kv.Key, kv.Value));
         }
 
-        private static readonly QQWrySearcher IPSearcher = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "qqwry.dat"));
         public static readonly DatabaseReader MaxmindReader = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-City.mmdb"));
         private static readonly DatabaseReader MaxmindAsnReader = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-ASN.mmdb"));
-        private static readonly DatabaseReader MaxmindCountryReader = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-Country.mmdb"));
 
         public static AsnResponse GetIPAsn(this IPAddress ip)
         {
@@ -141,11 +139,6 @@ namespace Masuit.MyBlogs.Core.Common
             return MaxmindReader.TryCity(ip, out var result) ? result : new CityResponse();
         }
 
-        private static CountryResponse GetCountryResp(IPAddress ip)
-        {
-            return MaxmindCountryReader.TryCountry(ip, out var result) ? result : new CountryResponse();
-        }
-
         public static IPLocation GetIPLocation(this string ip)
         {
             var b = IPAddress.TryParse(ip, out var ipAddress);
@@ -166,43 +159,22 @@ namespace Masuit.MyBlogs.Core.Common
 
             var cityTask = Task.Run(() => GetCityResp(ip));
             var asnTask = Task.Run(() => GetIPAsn(ip));
-            var countryTask = Task.Run(() => GetCountryResp(ip));
-            Task.WaitAll(cityTask, countryTask, asnTask);
+            Task.WaitAll(cityTask, asnTask);
             var city = cityTask.Result;
-            var country = countryTask.Result;
             var asn = asnTask.Result;
-            var countryName = country.Country.Names.GetValueOrDefault("zh-CN") ?? country.Country.Name;
+            var countryName = city.Country.Names.GetValueOrDefault("zh-CN") ?? city.Country.Name;
             var cityName = city.City.Names.GetValueOrDefault("zh-CN") ?? city.City.Name;
-            var continent = country.Continent.Names.GetValueOrDefault("zh-CN") ?? country.Continent.Name;
-            switch (ip.AddressFamily)
+            var continent = city.Continent.Names.GetValueOrDefault("zh-CN") ?? city.Continent.Name;
+            if (ip.AddressFamily is AddressFamily.InterNetworkV6 && ip.IsIPv4MappedToIPv6)
             {
-                case AddressFamily.InterNetworkV6 when ip.IsIPv4MappedToIPv6:
-                    ip = ip.MapToIPv4();
-                    goto case AddressFamily.InterNetwork;
-                case AddressFamily.InterNetwork:
-                    {
-                        var location = IPSearcher.GetIpLocation(ip);
-                        var network = location.Network + "/" + asn.AutonomousSystemOrganization;
-                        var state = Areas.FirstOrDefault(a => a.CountryCode == country.Country.IsoCode && (a.City == location.City || a.City_EN == location.City))?.State;
-                        return new IPLocation(countryName, location.City, network.Trim('/'), asn.AutonomousSystemNumber)
-                        {
-                            Address2 = new IPLocation.CountryCity(continent, countryName, state, location.City),
-                            Coodinate = city.Location,
-                            Continent = continent,
-                            State = state
-                        };
-                    }
-                default:
-                    {
-                        var state = Areas.FirstOrDefault(a => a.CountryCode == country.Country.IsoCode && (a.City == cityName || a.City_EN == city.City.Name))?.State;
-                        return new IPLocation(countryName, cityName, asn.AutonomousSystemOrganization, asn.AutonomousSystemNumber)
-                        {
-                            Coodinate = city.Location,
-                            Continent = continent,
-                            State = state
-                        };
-                    }
+                ip = ip.MapToIPv4();
             }
+            return new IPLocation(countryName, cityName, asn.AutonomousSystemOrganization, asn.AutonomousSystemNumber)
+            {
+                Coodinate = city.Location,
+                Continent = continent,
+                State = city.MostSpecificSubdivision.Names.GetValueOrDefault("zh-CN") ?? city.MostSpecificSubdivision.Name ?? Areas.FirstOrDefault(a => a.CountryCode == city.Country.IsoCode && (a.City == cityName || a.City_EN == city.City.Name))?.State
+            };
         }
 
         /// <summary>
@@ -379,7 +351,7 @@ namespace Masuit.MyBlogs.Core.Common
                 }
                 catch
                 {
-                    //
+                    // ignore
                 }
             }
             return stream;
@@ -409,20 +381,14 @@ namespace Masuit.MyBlogs.Core.Common
         }
     }
 
-    public record IPLocation(string country, string city, string ISP, long? ASN)
+    public record IPLocation(string Country, string City, string ISP, long? ASN)
     {
         public string Continent { get; set; }
 
-        public string Country { get; set; } = country?.Trim('0');
-
         public string State { get; set; }
 
-        public string City { get; set; } = city?.Trim('0');
-
         public string Address => new[] { Continent, Country, State, City }.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("");
 
-        public CountryCity Address2 { get; set; } = new("", "", "", "");
-
         public string Network => ASN.HasValue ? ISP + "(AS" + ASN + ")" : ISP;
 
         public Location Coodinate { get; set; }
@@ -441,7 +407,7 @@ namespace Masuit.MyBlogs.Core.Common
                 network = "未知网络";
             }
 
-            return new[] { address, Address2?.ToString(), network }.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("|");
+            return new[] { address, network }.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("|");
         }
 
         public static implicit operator string(IPLocation entry)
@@ -451,7 +417,7 @@ namespace Masuit.MyBlogs.Core.Common
 
         public void Deconstruct(out string location, out string network, out string info)
         {
-            location = new[] { Address, Address2 }.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("|");
+            location = Address;
             network = Network;
             info = ToString();
         }

+ 3 - 3
src/Masuit.MyBlogs.Core/Common/PerfCounter.cs

@@ -9,7 +9,7 @@ namespace Masuit.MyBlogs.Core.Common;
 
 public interface IPerfCounter
 {
-    public static ConcurrentLimitedQueue<PerformanceCounter> List { get; } = new(50000);
+    public static ConcurrentLimitedQueue<PerformanceCounter> List { get; } = new(150000);
 
     public static readonly DateTime StartTime = DateTime.Now;
 
@@ -108,7 +108,7 @@ public sealed class PerfCounterInDatabase(LoggerDbContext dbContext) : IPerfCoun
             dbContext.Add(result);
         }
 
-        var start = DateTime.Now.AddMonths(-1).GetTotalMilliseconds();
+        var start = DateTime.Now.AddMonths(-2).GetTotalMilliseconds();
         dbContext.Set<PerformanceCounter>().Where(e => e.Time < start).ExecuteDelete();
         dbContext.SaveChanges();
     }
@@ -193,4 +193,4 @@ public sealed class PerformanceCounter
     /// 网络下行
     /// </summary>
     public float Download { get; set; }
-}
+}

+ 0 - 324
src/Masuit.MyBlogs.Core/Common/QQWrySearcher.cs

@@ -1,324 +0,0 @@
-using System.Net;
-using System.Text;
-
-namespace Masuit.MyBlogs.Core.Common;
-
-/// <summary>
-/// QQWryIpSearch 请作为单例使用 数据库缓存在内存
-/// </summary>
-public sealed class QQWrySearcher : IDisposable
-{
-	private readonly SemaphoreSlim _initLock = new SemaphoreSlim(initialCount: 1, maxCount: 1);
-
-	private object _versionLock = new object();
-
-	private static readonly Encoding Gb2312Encoding;
-
-	/// <summary>
-	/// 数据库 缓存
-	/// </summary>
-	private byte[] _qqwryDbBytes;
-
-	/// <summary>
-	/// Ip索引 缓存
-	/// </summary>
-	private long[] _ipIndexCache;
-
-	/// <summary>
-	/// 起始定位
-	/// </summary>
-	private long _startPosition;
-
-	/// <summary>
-	/// 是否初始化
-	/// </summary>
-	private bool? _init;
-
-	private readonly string _dbPath;
-
-	private int? _ipCount;
-
-	private string _version;
-
-	/// <summary>
-	/// 记录总数
-	/// </summary>
-	public int IpCount
-	{
-		get
-		{
-			_ipCount ??= _ipIndexCache.Length;
-			return _ipCount.Value;
-		}
-	}
-
-	/// <summary>
-	/// 版本信息
-	/// </summary>
-	public string Version
-	{
-		get
-		{
-			if (!string.IsNullOrWhiteSpace(_version))
-			{
-				return _version;
-			}
-			lock (_versionLock)
-			{
-				if (!string.IsNullOrWhiteSpace(_version))
-				{
-					return _version;
-				}
-				_version = GetIpLocation(IPAddress.Parse("255.255.255.255")).Network;
-				return _version;
-			}
-		}
-	}
-
-	static QQWrySearcher()
-	{
-		Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
-		Gb2312Encoding = Encoding.GetEncoding("gb2312");
-	}
-
-	public QQWrySearcher(string dbPath)
-	{
-		_dbPath = dbPath;
-		Init();
-	}
-
-	/// <summary>
-	/// 初始化
-	/// </summary>
-	/// <returns></returns>
-	public bool Init(bool getNewDb = false)
-	{
-		if (_init != null && !getNewDb)
-		{
-			return _init.Value;
-		}
-		_initLock.Wait();
-		try
-		{
-			if (_init != null && !getNewDb)
-			{
-				return _init.Value;
-			}
-
-			_qqwryDbBytes = File.ReadAllBytes(_dbPath);
-			_ipIndexCache = BlockToArray(ReadIpBlock(_qqwryDbBytes, out _startPosition));
-			_ipCount = null;
-			_version = null;
-			_init = true;
-		}
-		finally
-		{
-			_initLock.Release();
-		}
-
-		if (_qqwryDbBytes == null)
-		{
-			throw new InvalidOperationException("无法打开IP数据库" + _dbPath + "!");
-		}
-
-		return true;
-
-	}
-
-	/// <summary>
-	///  获取指定IP所在地理位置
-	/// </summary>
-	/// <param name="ip">要查询的IP地址</param>
-	/// <returns></returns>
-	public (string City, string Network) GetIpLocation(IPAddress ip)
-	{
-		if (ip.IsPrivateIP())
-		{
-			return ("内网", "内网");
-		}
-		var ipnum = IpToLong(ip);
-		return ReadLocation(ipnum, _startPosition, _ipIndexCache, _qqwryDbBytes);
-	}
-
-	/// <inheritdoc />
-	/// <summary>
-	/// 释放
-	/// </summary>
-	public void Dispose()
-	{
-		_initLock?.Dispose();
-		_versionLock = null;
-		_qqwryDbBytes = null;
-		_qqwryDbBytes = null;
-		_ipIndexCache = null;
-		_init = null;
-	}
-
-	///<summary>
-	/// 将字符串形式的IP转换位long
-	///</summary>
-	///<param name="ip"></param>
-	///<returns></returns>
-	private static long IpToLong(IPAddress ip)
-	{
-		var bytes = ip.GetAddressBytes();
-		var ipBytes = new byte[8];
-		for (var i = 0; i < 4; i++)
-		{
-			ipBytes[i] = bytes[3 - i];
-		}
-
-		return BitConverter.ToInt64(ipBytes);
-	}
-
-	///<summary>
-	/// 将索引区字节块中的起始IP转换成Long数组
-	///</summary>
-	///<param name="ipBlock"></param>
-	private static long[] BlockToArray(byte[] ipBlock)
-	{
-		var ipArray = new long[ipBlock.Length / 7];
-		var ipIndex = 0;
-		var temp = new byte[8];
-		for (var i = 0; i < ipBlock.Length; i += 7)
-		{
-			Array.Copy(ipBlock, i, temp, 0, 4);
-			ipArray[ipIndex] = BitConverter.ToInt64(temp, 0);
-			ipIndex++;
-		}
-		return ipArray;
-	}
-
-	/// <summary>
-	///  从IP数组中搜索指定IP并返回其索引
-	/// </summary>
-	/// <param name="ip"></param>
-	/// <param name="ipArray">IP数组</param>
-	/// <param name="start">指定搜索的起始位置</param>
-	/// <param name="end">指定搜索的结束位置</param>
-	/// <returns></returns>
-	private static int SearchIp(long ip, long[] ipArray, int start, int end)
-	{
-		while (true)
-		{
-			//计算中间索引
-			var middle = (start + end) / 2;
-			if (middle == start)
-			{
-				return middle;
-			}
-
-			if (ip < ipArray[middle])
-			{
-				end = middle;
-			}
-			else
-			{
-				start = middle;
-			}
-		}
-	}
-
-	///<summary>
-	/// 读取IP文件中索引区块
-	///</summary>
-	///<returns></returns>
-	private static byte[] ReadIpBlock(byte[] bytes, out long startPosition)
-	{
-		long offset = 0;
-		startPosition = ReadLongX(bytes, offset, 4);
-		offset += 4;
-		var endPosition = ReadLongX(bytes, offset, 4);
-		offset = startPosition;
-		var count = (endPosition - startPosition) / 7 + 1;//总记录数
-		var ipBlock = new byte[count * 7];
-		for (var i = 0; i < ipBlock.Length; i++)
-		{
-			ipBlock[i] = bytes[offset + i];
-		}
-
-		return ipBlock;
-	}
-
-	/// <summary>
-	///  从IP文件中读取指定字节并转换位long
-	/// </summary>
-	/// <param name="bytes"></param>
-	/// <param name="offset"></param>
-	/// <param name="bytesCount">需要转换的字节数,主意不要超过8字节</param>
-	/// <returns></returns>
-	private static long ReadLongX(byte[] bytes, long offset, int bytesCount)
-	{
-		var cBytes = new byte[8];
-		for (var i = 0; i < bytesCount; i++)
-		{
-			cBytes[i] = bytes[offset + i];
-		}
-
-		return BitConverter.ToInt64(cBytes, 0);
-	}
-
-	/// <summary>
-	///  从IP文件中读取字符串
-	/// </summary>
-	/// <param name="bytes"></param>
-	/// <param name="flag">转向标志</param>
-	/// <param name="offset"></param>
-	/// <returns></returns>
-	private static string ReadString(byte[] bytes, int flag, ref long offset)
-	{
-		if (flag == 1 || flag == 2)//转向标志
-		{
-			offset = ReadLongX(bytes, offset, 3);
-		}
-		else
-		{
-			offset -= 1;
-		}
-
-		var list = new List<byte>();
-		var b = bytes[offset];
-		offset += 1;
-		while (b > 0)
-		{
-			list.Add(b);
-			b = bytes[offset];
-			offset += 1;
-		}
-
-		return Gb2312Encoding.GetString(list.ToArray());
-	}
-
-	private static (string City, string Network) ReadLocation(long ip, long startPosition, long[] ipIndex, byte[] qqwryDbBytes)
-	{
-		long offset = SearchIp(ip, ipIndex, 0, ipIndex.Length) * 7 + 4;
-
-		//偏移
-		var arrayOffset = startPosition + offset;
-		//跳过结束IP
-		arrayOffset = ReadLongX(qqwryDbBytes, arrayOffset, 3) + 4;
-		//读取标志
-		var flag = qqwryDbBytes[arrayOffset];
-		arrayOffset += 1;
-		//表示国家和地区被转向
-		if (flag == 1)
-		{
-			arrayOffset = ReadLongX(qqwryDbBytes, arrayOffset, 3);
-			//再读标志
-			flag = qqwryDbBytes[arrayOffset];
-			arrayOffset += 1;
-		}
-		var countryOffset = arrayOffset;
-		var city = ReadString(qqwryDbBytes, flag, ref arrayOffset);
-
-		if (flag == 2)
-		{
-			arrayOffset = countryOffset + 3;
-		}
-
-		flag = qqwryDbBytes[arrayOffset];
-		arrayOffset += 1;
-		var network = ReadString(qqwryDbBytes, flag, ref arrayOffset);
-		return (city, network);
-	}
-}

+ 1 - 2
src/Masuit.MyBlogs.Core/Controllers/ToolsController.cs

@@ -56,7 +56,6 @@ public sealed class ToolsController : BaseController
         {
             Location = loc.Coodinate,
             Address = loc.Address,
-            Address2 = loc.Address2,
             Network = new NetworkInfo
             {
                 Asn = asn.AutonomousSystemNumber,
@@ -207,4 +206,4 @@ public sealed class ToolsController : BaseController
     {
         return View();
     }
-}
+}

+ 108 - 116
src/Masuit.MyBlogs.Core/Extensions/Firewall/IRequestLogger.cs

@@ -6,145 +6,137 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall;
 
 public interface IRequestLogger
 {
-	void Log(string ip, string url, string userAgent, string traceid);
+    void Log(string ip, string url, string userAgent, string traceid);
 
-	void Process();
+    void Process();
 }
 
 public class RequestNoneLogger : IRequestLogger
 {
-	public void Log(string ip, string url, string userAgent, string traceid)
-	{
-	}
+    public void Log(string ip, string url, string userAgent, string traceid)
+    {
+    }
 
-	public void Process()
-	{
-	}
+    public void Process()
+    {
+    }
 }
 
 public class RequestFileLogger : IRequestLogger
 {
-	public void Log(string ip, string url, string userAgent, string traceid)
-	{
-		TrackData.RequestLogs.AddOrUpdate(ip, new RequestLog
-		{
-			Count = 1,
-			RequestUrls =
-			{
-				url
-			},
-			UserAgents =
-			{
-				userAgent
-			}
-		}, (_, i) =>
-		{
-			i.UserAgents.Add(userAgent);
-			i.RequestUrls.Add(url);
-			i.Count++;
-			return i;
-		});
-	}
-
-	public void Process()
-	{
-	}
+    public void Log(string ip, string url, string userAgent, string traceid)
+    {
+        TrackData.RequestLogs.AddOrUpdate(ip, new RequestLog
+        {
+            Count = 1,
+            RequestUrls =
+            {
+                url
+            },
+            UserAgents =
+            {
+                userAgent
+            }
+        }, (_, i) =>
+        {
+            i.UserAgents.Add(userAgent);
+            i.RequestUrls.Add(url);
+            i.Count++;
+            return i;
+        });
+    }
+
+    public void Process()
+    {
+    }
 }
 
 public class RequestDatabaseLogger : IRequestLogger
 {
-	private static readonly ConcurrentQueue<RequestLogDetail> Queue = new();
-	private readonly LoggerDbContext _dataContext;
-
-	public RequestDatabaseLogger(LoggerDbContext dataContext)
-	{
-		_dataContext = dataContext;
-	}
-
-	public void Log(string ip, string url, string userAgent, string traceid)
-	{
-		Queue.Enqueue(new RequestLogDetail
-		{
-			Time = DateTime.Now,
-			UserAgent = userAgent,
-			RequestUrl = url,
-			IP = ip,
-			TraceId = traceid
-		});
-	}
-
-	public void Process()
-	{
-		if (Debugger.IsAttached)
-		{
-			return;
-		}
-
-		while (Queue.TryDequeue(out var result))
-		{
-			var location = result.IP.GetIPLocation();
-			result.Location = location;
-			result.Country = new[]
-			{
-				location.Country,
-				location.Address2.Country
-			}.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("|");
-			result.City = new[]
-			{
-				location.City,
-				location.Address2.City
-			}.Where(s => !string.IsNullOrEmpty(s)).Distinct().Join("|");
-			result.Network = location.Network;
-			_dataContext.Add(result);
-		}
-
-		var start = DateTime.Now.AddMonths(-6);
-		_dataContext.Set<RequestLogDetail>().Where(e => e.Time < start).ExecuteDelete();
-		_dataContext.SaveChanges();
-	}
+    private static readonly ConcurrentQueue<RequestLogDetail> Queue = new();
+    private readonly LoggerDbContext _dataContext;
+
+    public RequestDatabaseLogger(LoggerDbContext dataContext)
+    {
+        _dataContext = dataContext;
+    }
+
+    public void Log(string ip, string url, string userAgent, string traceid)
+    {
+        Queue.Enqueue(new RequestLogDetail
+        {
+            Time = DateTime.Now,
+            UserAgent = userAgent,
+            RequestUrl = url,
+            IP = ip,
+            TraceId = traceid
+        });
+    }
+
+    public void Process()
+    {
+        if (Debugger.IsAttached)
+        {
+            return;
+        }
+
+        while (Queue.TryDequeue(out var result))
+        {
+            var location = result.IP.GetIPLocation();
+            result.Location = location;
+            result.Country = location.Country;
+            result.City = location.City;
+            result.Network = location.Network;
+            _dataContext.Add(result);
+        }
+
+        var start = DateTime.Now.AddMonths(-6);
+        _dataContext.Set<RequestLogDetail>().Where(e => e.Time < start).ExecuteDelete();
+        _dataContext.SaveChanges();
+    }
 }
 
 public class RequestLoggerBackService : ScheduledService
 {
-	private readonly IServiceScopeFactory _scopeFactory;
+    private readonly IServiceScopeFactory _scopeFactory;
 
-	public RequestLoggerBackService(IServiceScopeFactory scopeFactory) : base(TimeSpan.FromMinutes(5))
-	{
-		_scopeFactory = scopeFactory;
-	}
+    public RequestLoggerBackService(IServiceScopeFactory scopeFactory) : base(TimeSpan.FromMinutes(5))
+    {
+        _scopeFactory = scopeFactory;
+    }
 
-	protected override Task ExecuteAsync()
-	{
+    protected override Task ExecuteAsync()
+    {
 #if RELEASE
-		using var scope = _scopeFactory.CreateAsyncScope();
-		var logger = scope.ServiceProvider.GetRequiredService<IRequestLogger>();
-		logger.Process();
+        using var scope = _scopeFactory.CreateAsyncScope();
+        var logger = scope.ServiceProvider.GetRequiredService<IRequestLogger>();
+        logger.Process();
 #endif
-		return Task.CompletedTask;
-	}
+        return Task.CompletedTask;
+    }
 }
 
 public static class RequestLoggerServiceExtension
 {
-	public static IServiceCollection AddRequestLogger(this IServiceCollection services, IConfiguration configuration)
-	{
-		switch (configuration["RequestLogStorage"])
-		{
-			case "database":
-				services.AddScoped<IRequestLogger, RequestDatabaseLogger>();
-				services.TryAddScoped<RequestDatabaseLogger>();
-				break;
-
-			case "file":
-				services.AddSingleton<IRequestLogger, RequestFileLogger>();
-				break;
-
-			default:
-				services.AddSingleton<IRequestLogger, RequestNoneLogger>();
-				break;
-		}
-
-		services.AddHostedService<RequestLoggerBackService>();
-		return services;
-	}
-}
+    public static IServiceCollection AddRequestLogger(this IServiceCollection services, IConfiguration configuration)
+    {
+        switch (configuration["RequestLogStorage"])
+        {
+            case "database":
+                services.AddScoped<IRequestLogger, RequestDatabaseLogger>();
+                services.TryAddScoped<RequestDatabaseLogger>();
+                break;
+
+            case "file":
+                services.AddSingleton<IRequestLogger, RequestFileLogger>();
+                break;
+
+            default:
+                services.AddSingleton<IRequestLogger, RequestNoneLogger>();
+                break;
+        }
+
+        services.AddHostedService<RequestLoggerBackService>();
+        return services;
+    }
+}

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

@@ -46,10 +46,10 @@
         <PackageReference Include="CHTCHSConv" Version="1.0.0" />
         <PackageReference Include="CLRStats" Version="1.0.0" />
         <PackageReference Include="Dispose.Scope.AspNetCore" Version="0.0.3" />
-        <PackageReference Include="EFCoreSecondLevelCacheInterceptor" Version="4.8.7" />
+        <PackageReference Include="EFCoreSecondLevelCacheInterceptor" Version="4.9.0" />
         <PackageReference Include="EntityFrameworkCore.Exceptions.PostgreSQL" Version="8.1.3" />
-        <PackageReference Include="FreeRedis" Version="1.3.3" />
-        <PackageReference Include="Hangfire" Version="1.8.15" />
+        <PackageReference Include="FreeRedis" Version="1.3.4" />
+        <PackageReference Include="Hangfire" Version="1.8.17" />
         <PackageReference Include="Hangfire.MemoryStorage" Version="1.8.1.1" />
         <PackageReference Include="Karambolo.AspNetCore.Bundling.NUglify" Version="3.9.0" />
         <PackageReference Include="Mammoth.Core" Version="1.0.1" />
@@ -59,13 +59,13 @@
         <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="9.0.0" />
         <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="9.0.0" />
         <PackageReference Include="Microsoft.NETCore.Platforms" Version="7.0.4" />
-        <PackageReference Include="MiniProfiler.AspNetCore.Mvc" Version="4.3.8" />
-        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.10" />
-        <PackageReference Include="MiniProfiler.EntityFrameworkCore" Version="4.3.8" />
+        <PackageReference Include="MiniProfiler.AspNetCore.Mvc" Version="4.5.4" />
+        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.2" />
+        <PackageReference Include="MiniProfiler.EntityFrameworkCore" Version="4.5.4" />
         <PackageReference Include="PanGu.HighLight" Version="1.0.0" />
         <PackageReference Include="Rin" Version="2.6.0" />
         <PackageReference Include="SixLabors.ImageSharp.Web" Version="3.1.3" />
-        <PackageReference Include="System.Linq.Dynamic.Core" Version="1.4.8" />
+        <PackageReference Include="System.Linq.Dynamic.Core" Version="1.5.0" />
         <PackageReference Include="System.Net.Http" Version="4.3.4" />
         <PackageReference Include="System.Text.Encodings.Web" Version="9.0.0" />
         <PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />

+ 1 - 1
src/Masuit.MyBlogs.Core/Models/Entity/Post.cs

@@ -309,4 +309,4 @@ public enum ProtectContentMode
     /// 仅搜索引擎可见
     /// </summary>
     OnlyForSearchEngine,
-}
+}

+ 9 - 10
src/Masuit.MyBlogs.Core/Models/ViewModel/IpInfo.cs

@@ -5,18 +5,17 @@ namespace Masuit.MyBlogs.Core.Models.ViewModel;
 
 public class IpInfo
 {
-	public string Address { get; set; }
-	public Location Location { get; set; }
-	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 string Address { get; set; }
+    public Location Location { get; set; }
+    public NetworkInfo Network { get; set; }
+    public bool IsProxy { get; set; }
+    public string TimeZone { get; set; }
+    public string Domain { get; set; }
 }
 
 public class NetworkInfo
 {
-	public string Router { get; set; }
-	public long? Asn { get; set; }
-	public string Organization { get; set; }
+    public string Router { get; set; }
+    public long? Asn { get; set; }
+    public string Organization { get; set; }
 }

+ 2 - 9
src/Masuit.MyBlogs.Core/Program.cs

@@ -11,7 +11,6 @@ try
     if (Environment.OSVersion.Platform is not (PlatformID.MacOSX or PlatformID.Unix))
     {
         // 设置相关进程优先级为高于正常,防止其他进程影响应用程序的运行性能
-        Process.GetProcessesByName("mysqld").ForEach(p => p.PriorityClass = ProcessPriorityClass.AboveNormal);
         Process.GetProcessesByName("pg_ctl").ForEach(p => p.PriorityClass = ProcessPriorityClass.AboveNormal);
         Process.GetProcessesByName("postgres").ForEach(p => p.PriorityClass = ProcessPriorityClass.AboveNormal);
         Process.GetProcessesByName("redis-server").ForEach(p => p.PriorityClass = ProcessPriorityClass.AboveNormal);
@@ -23,13 +22,7 @@ catch
     // ignored
 }
 
-// 确保IP数据库正常
-if (!"223.5.5.5".GetIPLocation().Contains("阿里"))
-{
-    throw new Exception("IP地址库初始化失败,请重启应用!");
-}
-
-Host.CreateDefaultBuilder(args).ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json", true, true)).ConfigureLogging(logger => logger.AddRinLogger()).UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureWebHostDefaults(hostBuilder => hostBuilder.UseQuic().UseKestrel(opt =>
+await Host.CreateDefaultBuilder(args).ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json", true, true)).ConfigureLogging(logger => logger.AddRinLogger()).UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureWebHostDefaults(hostBuilder => hostBuilder.UseQuic().UseKestrel(opt =>
 {
     var config = opt.ApplicationServices.GetService<IConfiguration>();
     var port = config["Port"] ?? "5000";
@@ -50,4 +43,4 @@ Host.CreateDefaultBuilder(args).ConfigureAppConfiguration(builder => builder.Add
 
     opt.Limits.MaxRequestBodySize = null;
     Console.WriteLine($"应用程序监听端口:http:{port},https:{sslport}");
-}).UseStartup<Startup>()).Build().Run();
+}).UseStartup<Startup>()).Build().RunAsync();

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

@@ -194,7 +194,7 @@
     public static Masuit.MyBlogs.Core.Common.PerformanceCounter GetCurrentPerformanceCounter()
     {
         try {
-            return IPerfCounter.GetCurrentPerformanceCounter();
+            return IPerfCounter.List.LastOrDefault()??IPerfCounter.GetCurrentPerformanceCounter();
         }
         catch (Exception e) {
             LogManager.Error(e.Demystify());
@@ -216,7 +216,7 @@
 
     public Dictionary<string, dynamic> GetCounterPercent()
     {
-        var counters = PerfCounter.CreateDataSource().Where(c => c.ServerIP==_ip).OrderByRandom().Take(5000).ToList();
+        var counters = PerfCounter.CreateDataSource().Where(c => c.ServerIP==_ip).OrderByRandom().Take(15000).ToList();
         var cpuLoads = counters.Select(c => c.CpuLoad).ToList();
         var memUse = counters.Select(c => c.MemoryUsage).ToList();
         var reads = counters.Select(c => c.DiskRead).ToList();

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

@@ -50,13 +50,9 @@
             <td>@Model.Network.Asn</td>
         </tr>
         <tr>
-            <td>参考地理位置1:</td>
+            <td>参考地理位置:</td>
             <td>@Model.Address</td>
         </tr>
-        <tr>
-            <td>参考地理位置2:</td>
-            <td>@Model.Address2</td>
-        </tr>
         <tr>
             <td>时区:</td>
             <td>@Model.TimeZone</td>

Plik diff jest za duży
+ 0 - 1
src/Masuit.MyBlogs.Core/wwwroot/Assets/UEditor/dialogs/image/image.js


Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików