浏览代码

修正bug

懒得勤快 2 年之前
父节点
当前提交
d15d6d29e9

+ 0 - 1
src/Masuit.MyBlogs.Core/App_Data/ueconfig.json

@@ -52,7 +52,6 @@
         "git.lug.ustc.edu.cn",
         "alicdn.com",
         "kuaizhan.com",
-        "qpic.cn",
         "s-msft.com",
         "geekbang.org",
         "jetbrains.com",

+ 177 - 176
src/Masuit.MyBlogs.Core/Controllers/ToolsController.cs

@@ -23,184 +23,185 @@ namespace Masuit.MyBlogs.Core.Controllers;
 [Route("tools")]
 public sealed class ToolsController : BaseController
 {
-    private readonly HttpClient _httpClient;
-
-    public ToolsController(IHttpClientFactory httpClientFactory)
-    {
-        _httpClient = httpClientFactory.CreateClient();
-    }
-
-    /// <summary>
-    /// 获取ip地址详细信息
-    /// </summary>
-    /// <param name="ip"></param>
-    /// <returns></returns>
-    [Route("ip"), Route("ip/{ip?}", Order = 1), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "ip" })]
-    public async Task<ActionResult> GetIpInfo([IsIPAddress] string ip)
-    {
-        if (!IPAddress.TryParse(ip, out var ipAddress))
-        {
-            ipAddress = ClientIP;
-        }
-
-        if (ipAddress.IsPrivateIP())
-        {
-            return Ok("内网IP");
-        }
-
-        ViewBag.IP = ip;
-        var loc = ipAddress.GetIPLocation();
-        var asn = ipAddress.GetIPAsn();
-        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 = loc.Coodinate,
-            Address = loc.Address,
-            Address2 = loc.Address2,
-            Network = new NetworkInfo
-            {
-                Asn = asn.AutonomousSystemNumber,
-                Router = asn.Network + "",
-                Organization = loc.ISP
-            },
-            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", "ASN" }) || domain.Length > 1 || await IsProxy(ipAddress, cts.Token),
-            Domain = domain
-        };
-        if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
-        {
-            return View(address);
-        }
-
-        return Json(address);
-    }
-
-    /// <summary>
-    /// 是否是代理ip
-    /// </summary>
-    /// <param name="ip"></param>
-    /// <param name="cancellationToken"></param>
-    /// <returns></returns>
-    private async Task<bool> IsProxy(IPAddress ip, CancellationToken cancellationToken = default)
-    {
-        _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");
-        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;
-        });
-    }
-
-    /// <summary>
-    /// 根据经纬度获取详细地理信息
-    /// </summary>
-    /// <param name="lat"></param>
-    /// <param name="lng"></param>
-    /// <returns></returns>
-    [HttpGet("pos"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "lat", "lng" })]
-    public async Task<ActionResult> Position(string lat, string lng)
-    {
-        if (string.IsNullOrEmpty(lat) || string.IsNullOrEmpty(lng))
-        {
-            var ip = ClientIP;
+	private readonly HttpClient _httpClient;
+
+	public ToolsController(IHttpClientFactory httpClientFactory)
+	{
+		_httpClient = httpClientFactory.CreateClient();
+	}
+
+	/// <summary>
+	/// 获取ip地址详细信息
+	/// </summary>
+	/// <param name="ip"></param>
+	/// <returns></returns>
+	[Route("ip"), Route("ip/{ip?}", Order = 1), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "ip" })]
+	public async Task<ActionResult> GetIpInfo([IsIPAddress] string ip)
+	{
+		ViewBag.IP = ip;
+		if (!IPAddress.TryParse(ip, out var ipAddress))
+		{
+			ipAddress = ClientIP;
+			ViewBag.IP = ClientIP;
+		}
+
+		if (ipAddress.IsPrivateIP())
+		{
+			return Ok("内网IP");
+		}
+
+		var loc = ipAddress.GetIPLocation();
+		var asn = ipAddress.GetIPAsn();
+		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 = loc.Coodinate,
+			Address = loc.Address,
+			Address2 = loc.Address2,
+			Network = new NetworkInfo
+			{
+				Asn = asn.AutonomousSystemNumber,
+				Router = asn.Network + "",
+				Organization = loc.ISP
+			},
+			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", "ASN" }) || domain.Length > 1 || await IsProxy(ipAddress, cts.Token),
+			Domain = domain
+		};
+		if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
+		{
+			return View(address);
+		}
+
+		return Json(address);
+	}
+
+	/// <summary>
+	/// 是否是代理ip
+	/// </summary>
+	/// <param name="ip"></param>
+	/// <param name="cancellationToken"></param>
+	/// <returns></returns>
+	private async Task<bool> IsProxy(IPAddress ip, CancellationToken cancellationToken = default)
+	{
+		_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");
+		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;
+		});
+	}
+
+	/// <summary>
+	/// 根据经纬度获取详细地理信息
+	/// </summary>
+	/// <param name="lat"></param>
+	/// <param name="lng"></param>
+	/// <returns></returns>
+	[HttpGet("pos"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "lat", "lng" })]
+	public async Task<ActionResult> Position(string lat, string lng)
+	{
+		if (string.IsNullOrEmpty(lat) || string.IsNullOrEmpty(lng))
+		{
+			var ip = ClientIP;
 #if DEBUG
-            var r = new Random();
-            ip = IPAddress.Parse($"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}");
+			var r = new Random();
+			ip = IPAddress.Parse($"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}");
 #endif
-            var location = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(() => new CityResponse()).Execute(() => CommonHelper.MaxmindReader.City(ip));
-            var address = new PhysicsAddress()
-            {
-                Status = 0,
-                AddressResult = new AddressResult()
-                {
-                    FormattedAddress = ip.GetIPLocation().Address,
-                    Location = new Location()
-                    {
-                        Lng = (decimal)location.Location.Longitude.GetValueOrDefault(),
-                        Lat = (decimal)location.Location.Latitude.GetValueOrDefault()
-                    }
-                }
-            };
-            return View(address);
-        }
-
-        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
-        var s = await _httpClient.GetStringAsync($"http://api.map.baidu.com/geocoder/v2/?location={lat},{lng}&output=json&pois=1&ak={AppConfig.BaiduAK}", cts.Token).ContinueWith(t =>
-        {
-            if (t.IsCompletedSuccessfully)
-            {
-                return JsonConvert.DeserializeObject<PhysicsAddress>(t.Result);
-            }
-
-            return new PhysicsAddress();
-        });
-
-        return View(s);
-    }
-
-    /// <summary>
-    /// 详细地理信息转经纬度
-    /// </summary>
-    /// <param name="addr"></param>
-    /// <returns></returns>
-    [Route("addr"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "addr" })]
-    public async Task<ActionResult> Address(string addr)
-    {
-        if (string.IsNullOrEmpty(addr))
-        {
-            var ip = ClientIP;
+			var location = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(() => new CityResponse()).Execute(() => CommonHelper.MaxmindReader.City(ip));
+			var address = new PhysicsAddress()
+			{
+				Status = 0,
+				AddressResult = new AddressResult()
+				{
+					FormattedAddress = ip.GetIPLocation().Address,
+					Location = new Location()
+					{
+						Lng = (decimal)location.Location.Longitude.GetValueOrDefault(),
+						Lat = (decimal)location.Location.Latitude.GetValueOrDefault()
+					}
+				}
+			};
+			return View(address);
+		}
+
+		using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
+		var s = await _httpClient.GetStringAsync($"http://api.map.baidu.com/geocoder/v2/?location={lat},{lng}&output=json&pois=1&ak={AppConfig.BaiduAK}", cts.Token).ContinueWith(t =>
+		{
+			if (t.IsCompletedSuccessfully)
+			{
+				return JsonConvert.DeserializeObject<PhysicsAddress>(t.Result);
+			}
+
+			return new PhysicsAddress();
+		});
+
+		return View(s);
+	}
+
+	/// <summary>
+	/// 详细地理信息转经纬度
+	/// </summary>
+	/// <param name="addr"></param>
+	/// <returns></returns>
+	[Route("addr"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "addr" })]
+	public async Task<ActionResult> Address(string addr)
+	{
+		if (string.IsNullOrEmpty(addr))
+		{
+			var ip = ClientIP;
 #if DEBUG
-            Random r = new Random();
-            ip = IPAddress.Parse($"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}");
+			Random r = new Random();
+			ip = IPAddress.Parse($"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}");
 #endif
-            var location = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(() => new CityResponse()).Execute(() => CommonHelper.MaxmindReader.City(ip));
-            var address = new PhysicsAddress()
-            {
-                Status = 0,
-                AddressResult = new AddressResult
-                {
-                    FormattedAddress = ip.GetIPLocation().Address,
-                    Location = new Location
-                    {
-                        Lng = (decimal)location.Location.Longitude.GetValueOrDefault(),
-                        Lat = (decimal)location.Location.Latitude.GetValueOrDefault()
-                    }
-                }
-            };
-            ViewBag.Address = address.AddressResult.FormattedAddress;
-            if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
-            {
-                return View(address.AddressResult.Location);
-            }
-
-            return Json(address.AddressResult.Location);
-        }
-
-        ViewBag.Address = addr;
-        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
-        var physicsAddress = await _httpClient.GetStringAsync($"http://api.map.baidu.com/geocoder/v2/?output=json&address={addr}&ak={AppConfig.BaiduAK}", cts.Token).ContinueWith(t =>
-        {
-            if (t.IsCompletedSuccessfully)
-            {
-                return JsonConvert.DeserializeObject<PhysicsAddress>(t.Result);
-            }
-
-            return new PhysicsAddress();
-        });
-        if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
-        {
-            return View(physicsAddress?.AddressResult?.Location);
-        }
-
-        return Json(physicsAddress?.AddressResult?.Location);
-    }
+			var location = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(() => new CityResponse()).Execute(() => CommonHelper.MaxmindReader.City(ip));
+			var address = new PhysicsAddress()
+			{
+				Status = 0,
+				AddressResult = new AddressResult
+				{
+					FormattedAddress = ip.GetIPLocation().Address,
+					Location = new Location
+					{
+						Lng = (decimal)location.Location.Longitude.GetValueOrDefault(),
+						Lat = (decimal)location.Location.Latitude.GetValueOrDefault()
+					}
+				}
+			};
+			ViewBag.Address = address.AddressResult.FormattedAddress;
+			if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
+			{
+				return View(address.AddressResult.Location);
+			}
+
+			return Json(address.AddressResult.Location);
+		}
+
+		ViewBag.Address = addr;
+		using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
+		var physicsAddress = await _httpClient.GetStringAsync($"http://api.map.baidu.com/geocoder/v2/?output=json&address={addr}&ak={AppConfig.BaiduAK}", cts.Token).ContinueWith(t =>
+		{
+			if (t.IsCompletedSuccessfully)
+			{
+				return JsonConvert.DeserializeObject<PhysicsAddress>(t.Result);
+			}
+
+			return new PhysicsAddress();
+		});
+		if (Request.Method.Equals(HttpMethods.Get) || (Request.Headers[HeaderNames.Accept] + "").StartsWith(ContentType.Json))
+		{
+			return View(physicsAddress?.AddressResult?.Location);
+		}
+
+		return Json(physicsAddress?.AddressResult?.Location);
+	}
 }

+ 102 - 100
src/Masuit.MyBlogs.Core/Extensions/UEditor/CrawlerHandler.cs

@@ -4,6 +4,7 @@ using Masuit.Tools.Logging;
 using System.Diagnostics;
 using System.Net;
 using System.Text.RegularExpressions;
+using Masuit.Tools.Files;
 
 namespace Masuit.MyBlogs.Core.Extensions.UEditor;
 
@@ -12,120 +13,121 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor;
 /// </summary>
 public class CrawlerHandler : Handler
 {
-    private readonly HttpClient _httpClient;
-    private readonly IConfiguration _configuration;
+	private readonly HttpClient _httpClient;
+	private readonly IConfiguration _configuration;
 
-    public CrawlerHandler(HttpContext context) : base(context)
-    {
-        _httpClient = context.RequestServices.GetRequiredService<IHttpClientFactory>().CreateClient();
-        _configuration = context.RequestServices.GetRequiredService<IConfiguration>();
-    }
+	public CrawlerHandler(HttpContext context) : base(context)
+	{
+		_httpClient = context.RequestServices.GetRequiredService<IHttpClientFactory>().CreateClient();
+		_configuration = context.RequestServices.GetRequiredService<IConfiguration>();
+	}
 
-    public override async Task<string> Process()
-    {
-        var form = await Request.ReadFormAsync();
-        string[] sources = form["source[]"];
-        if (sources?.Length > 0 || sources?.Length <= 10)
-        {
-            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
-            return WriteJson(new
-            {
-                state = "SUCCESS",
-                list = (await sources.SelectAsync(s =>
-                {
-                    return new Crawler(s, _httpClient, _configuration, Context).Fetch(cts.Token).ContinueWith(t => new
-                    {
-                        state = t.Result.State,
-                        source = t.Result.SourceUrl,
-                        url = t.Result.ServerUrl
-                    });
-                }))
-            });
-        }
+	public override async Task<string> Process()
+	{
+		var form = await Request.ReadFormAsync();
+		string[] sources = form["source[]"];
+		if (sources?.Length > 0 || sources?.Length <= 10)
+		{
+			using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
+			return WriteJson(new
+			{
+				state = "SUCCESS",
+				list = (await sources.SelectAsync(s =>
+				{
+					return new Crawler(s, _httpClient, _configuration, Context).Fetch(cts.Token).ContinueWith(t => new
+					{
+						state = t.Result.State,
+						source = t.Result.SourceUrl,
+						url = t.Result.ServerUrl
+					});
+				}))
+			});
+		}
 
-        return WriteJson(new
-        {
-            state = "参数错误:没有指定抓取源"
-        });
-    }
+		return WriteJson(new
+		{
+			state = "参数错误:没有指定抓取源"
+		});
+	}
 }
 
 public class Crawler
 {
-    public string SourceUrl { get; set; }
+	public string SourceUrl { get; set; }
 
-    public string ServerUrl { get; set; }
+	public string ServerUrl { get; set; }
 
-    public string State { get; set; }
+	public string State { get; set; }
 
-    private readonly HttpClient _httpClient;
-    private readonly IConfiguration _configuration;
-    private readonly HttpContext _httpContext;
+	private readonly HttpClient _httpClient;
+	private readonly IConfiguration _configuration;
+	private readonly HttpContext _httpContext;
 
-    public Crawler(string sourceUrl, HttpClient httpClient, IConfiguration configuration, HttpContext httpContext)
-    {
-        SourceUrl = sourceUrl;
-        _httpClient = httpClient;
-        _configuration = configuration;
-        _httpContext = httpContext;
-    }
+	public Crawler(string sourceUrl, HttpClient httpClient, IConfiguration configuration, HttpContext httpContext)
+	{
+		SourceUrl = sourceUrl;
+		_httpClient = httpClient;
+		_configuration = configuration;
+		_httpContext = httpContext;
+	}
 
-    public async Task<Crawler> Fetch(CancellationToken token)
-    {
-        if (!SourceUrl.IsExternalAddress())
-        {
-            State = "INVALID_URL";
-            return this;
-        }
-        try
-        {
-            _httpClient.DefaultRequestHeaders.Referrer = new Uri(SourceUrl);
-            using var response = await _httpClient.GetAsync(_configuration["HttpClientProxy:UriPrefix"] + SourceUrl);
-            if (response.StatusCode != HttpStatusCode.OK)
-            {
-                State = "远程地址返回了错误的状态吗:" + response.StatusCode;
-                return this;
-            }
+	public async Task<Crawler> Fetch(CancellationToken token)
+	{
+		if (!SourceUrl.IsExternalAddress())
+		{
+			State = "INVALID_URL";
+			return this;
+		}
+		try
+		{
+			_httpClient.DefaultRequestHeaders.Referrer = new Uri(SourceUrl);
+			using var response = await _httpClient.GetAsync(_configuration["HttpClientProxy:UriPrefix"] + SourceUrl, token);
+			if (response.StatusCode != HttpStatusCode.OK)
+			{
+				State = "远程地址返回了错误的状态吗:" + response.StatusCode;
+				return this;
+			}
 
-            ServerUrl = PathFormatter.Format(Path.GetFileNameWithoutExtension(SourceUrl), CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload") + UeditorConfig.GetString("catcherPathFormat")) + MimeMapper.ExtTypes[response.Content.Headers.ContentType?.MediaType ?? "image/jpeg"];
-            var stream = await response.Content.ReadAsStreamAsync();
-            var format = await Image.DetectFormatAsync(stream).ContinueWith(t => t.IsCompletedSuccessfully ? t.Result : null);
-            stream.Position = 0;
-            if (format != null)
-            {
-                ServerUrl = ServerUrl.Replace(Path.GetExtension(ServerUrl), "." + format.Name.ToLower());
-                if (!Regex.IsMatch(format.Name, "JPEG|PNG|Webp|GIF", RegexOptions.IgnoreCase))
-                {
-                    using var image = await Image.LoadAsync(stream);
-                    var memoryStream = new PooledMemoryStream();
-                    await image.SaveAsJpegAsync(memoryStream);
-                    await stream.DisposeAsync();
-                    stream = memoryStream;
-                    ServerUrl = ServerUrl.Replace(Path.GetExtension(ServerUrl), ".jpg");
-                }
-            }
+			var fileName = Path.GetFileNameWithoutExtension(SourceUrl).Next(s => Regex.Matches(s, @"\w+").LastOrDefault()?.Value);
+			ServerUrl = PathFormatter.Format(fileName, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload") + UeditorConfig.GetString("catcherPathFormat")) + MimeMapper.ExtTypes[response.Content.Headers.ContentType?.MediaType ?? "image/jpeg"];
+			var stream = await response.Content.ReadAsStreamAsync();
+			var format = await Image.DetectFormatAsync(stream).ContinueWith(t => t.IsCompletedSuccessfully ? t.Result : null);
+			stream.Position = 0;
+			if (format != null)
+			{
+				ServerUrl = ServerUrl.Replace(Path.GetExtension(ServerUrl), "." + format.Name.ToLower());
+				if (!Regex.IsMatch(format.Name, "JPEG|PNG|Webp|GIF", RegexOptions.IgnoreCase))
+				{
+					using var image = await Image.LoadAsync(stream, token);
+					var memoryStream = new PooledMemoryStream();
+					await image.SaveAsJpegAsync(memoryStream, token);
+					await stream.DisposeAsync();
+					stream = memoryStream;
+					ServerUrl = ServerUrl.Replace(Path.GetExtension(ServerUrl), ".jpg");
+				}
+			}
 
-            var savePath = AppContext.BaseDirectory + "wwwroot" + ServerUrl;
-            var (url, success) = await _httpContext.RequestServices.GetRequiredService<ImagebedClient>().UploadImage(stream, savePath, token);
-            if (success)
-            {
-                ServerUrl = url;
-            }
-            else
-            {
-                Directory.CreateDirectory(Path.GetDirectoryName(savePath));
-                await File.WriteAllBytesAsync(savePath, await stream.ToArrayAsync());
-            }
+			var savePath = AppContext.BaseDirectory + "wwwroot" + ServerUrl;
+			var (url, success) = await _httpContext.RequestServices.GetRequiredService<ImagebedClient>().UploadImage(stream, savePath, token);
+			if (success)
+			{
+				ServerUrl = url;
+			}
+			else
+			{
+				Directory.CreateDirectory(Path.GetDirectoryName(savePath));
+				await stream.SaveFileAsync(savePath);
+			}
 
-            await stream.DisposeAsync();
-            State = "SUCCESS";
-        }
-        catch (Exception e)
-        {
-            State = "抓取错误:" + e.Message;
-            LogManager.Error(e.Demystify());
-        }
+			await stream.DisposeAsync();
+			State = "SUCCESS";
+		}
+		catch (Exception e)
+		{
+			State = "抓取错误:" + e.Message;
+			LogManager.Error(e.Demystify());
+		}
 
-        return this;
-    }
+		return this;
+	}
 }

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

@@ -50,7 +50,7 @@
         <PackageReference Include="CLRStats" Version="1.0.0" />
         <PackageReference Include="Dispose.Scope.AspNetCore" Version="0.0.3" />
         <PackageReference Include="EntityFrameworkCore.Exceptions.PostgreSQL" Version="6.0.3" />
-        <PackageReference Include="FreeRedis" Version="1.1.8" />
+        <PackageReference Include="FreeRedis" Version="1.1.9" />
         <PackageReference Include="Hangfire" Version="1.8.5" />
         <PackageReference Include="Hangfire.MemoryStorage" Version="1.8.0" />
         <PackageReference Include="htmldiff.net" Version="1.4.1" />

+ 39 - 38
src/Masuit.MyBlogs.Core/Program.cs

@@ -10,64 +10,65 @@ using Z.EntityFramework.Plus;
 
 QueryCacheManager.DefaultMemoryCacheEntryOptions = new MemoryCacheEntryOptions()
 {
-    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
+	AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
 };
 AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
 
 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);
-    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
+	// 设置相关进程优先级为高于正常,防止其他进程影响应用程序的运行性能
+	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);
+	Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
 }
 
 // 确保IP数据库正常
 if (!"223.5.5.5".GetIPLocation().Contains("阿里"))
 {
-    throw new Exception("IP地址库初始化失败,请重启应用!");
+	throw new Exception("IP地址库初始化失败,请重启应用!");
 }
 
 InitOneDrive(); // 初始化Onedrive程序
 Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureWebHostDefaults(hostBuilder => hostBuilder.UseKestrel(opt =>
 {
-    var config = opt.ApplicationServices.GetService<IConfiguration>();
-    var port = config["Port"] ?? "5000";
-    var sslport = config["Https:Port"] ?? "5001";
-    opt.ListenAnyIP(port.ToInt32(), options => options.Protocols = HttpProtocols.Http1AndHttp2AndHttp3);
-    if (bool.Parse(config["Https:Enabled"]))
-    {
-        opt.ListenAnyIP(sslport.ToInt32(), s =>
-        {
-            if (Environment.OSVersion is { Platform: PlatformID.Win32NT, Version.Major: >= 10 })
-            {
-                s.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
-            }
+	var config = opt.ApplicationServices.GetService<IConfiguration>();
+	var port = config["Port"] ?? "5000";
+	var sslport = config["Https:Port"] ?? "5001";
+	opt.ListenAnyIP(port.ToInt32(), options => options.Protocols = HttpProtocols.Http1AndHttp2AndHttp3);
+	if (bool.Parse(config["Https:Enabled"]))
+	{
+		opt.ListenAnyIP(sslport.ToInt32(), s =>
+		{
+			if (Environment.OSVersion is { Platform: PlatformID.Win32NT, Version.Major: >= 10 })
+			{
+				s.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
+			}
 
-            s.UseHttps(AppContext.BaseDirectory + config["Https:CertPath"], config["Https:CertPassword"]);
-        });
-    }
+			s.UseHttps(AppContext.BaseDirectory + config["Https:CertPath"], config["Https:CertPassword"]);
+		});
+	}
 
-    opt.Limits.MaxRequestBodySize = null;
-    Console.WriteLine($"应用程序监听端口:http:{port},https:{sslport}");
+	opt.Limits.MaxRequestBodySize = null;
+	Console.WriteLine($"应用程序监听端口:http:{port},https:{sslport}");
 }).UseStartup<Startup>()).Build().Run();
+return;
 
 static void InitOneDrive()
 {
-    //初始化
-    if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "App_Data", "OneDrive.db")))
-    {
-        File.Copy(Path.Combine("App_Data", "OneDrive.template.db"), Path.Combine("App_Data", "OneDrive.db"));
-        Console.WriteLine("数据库创建成功");
-    }
+	//初始化
+	if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "App_Data", "OneDrive.db")))
+	{
+		File.Copy(Path.Combine("App_Data", "OneDrive.template.db"), Path.Combine("App_Data", "OneDrive.db"));
+		Console.WriteLine("数据库创建成功");
+	}
 
-    using var settingService = new SettingService(new DriveContext());
-    if (settingService.Get("IsInit") != "true")
-    {
-        settingService.Set("IsInit", "true").Wait();
-        Console.WriteLine("数据初始化成功");
-        Console.WriteLine($"请登录 {OneDriveConfiguration.BaseUri}/#/admin 进行身份及其他配置");
-    }
+	using var settingService = new SettingService(new DriveContext());
+	if (settingService.Get("IsInit") != "true")
+	{
+		settingService.Set("IsInit", "true").Wait();
+		Console.WriteLine("数据初始化成功");
+		Console.WriteLine($"请登录 {OneDriveConfiguration.BaseUri}/#/admin 进行身份及其他配置");
+	}
 }

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

@@ -84,18 +84,18 @@
             var map = new BMapGL.Map("allmap"); // 创建Map实例,设置地图允许的最小/大级别
 
             map.centerAndZoom(new BMapGL.Point(@(Model.Location.Longitude), @(Model.Location.Latitude)), [email protected]().ToString().Length);
-	        map.enableScrollWheelZoom(true);
-	        var new_point = new BMapGL.Point(@(Model.Location.Longitude), @(Model.Location.Latitude));
+            map.enableScrollWheelZoom(true);
+            var new_point = new BMapGL.Point(@(Model.Location.Longitude), @(Model.Location.Latitude));
             var marker = new BMapGL.Marker(new_point); // 创建标注
             var circle = new BMapGL.Circle(new_point, @Model.Location.AccuracyRadius.GetValueOrDefault()* 100, {
                 strokeColor: 'blue',
                 strokeWeight: 2,
                 strokeOpacity: 0.1
             });
-	        map.addOverlay(marker); // 将标注添加到地图中
+            map.addOverlay(marker); // 将标注添加到地图中
             map.addOverlay(circle); // 将标注添加到地图中
-	        marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
-	        map.panTo(new_point);
+            marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
+            map.panTo(new_point);
         </script>
     }
 </div>