Browse Source

移除阿里云oss

懒得勤快 4 years ago
parent
commit
ca34023956

+ 35 - 59
src/Masuit.MyBlogs.Core/Common/ImagebedClient.cs

@@ -1,5 +1,4 @@
-using Aliyun.OSS;
-using Hangfire;
+using Hangfire;
 using Masuit.MyBlogs.Core.Configs;
 using Masuit.Tools;
 using Masuit.Tools.Html;
@@ -11,7 +10,6 @@ using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
-using System.Net;
 using System.Net.Http;
 using System.Net.Http.Headers;
 using System.Threading;
@@ -39,11 +37,6 @@ namespace Masuit.MyBlogs.Core.Common
             _httpClient = httpClient;
         }
 
-        /// <summary>
-        /// OSS客户端
-        /// </summary>
-        public static OssClient OssClient { get; set; } = new(AppConfig.AliOssConfig.EndPoint, AppConfig.AliOssConfig.AccessKeyId, AppConfig.AliOssConfig.AccessKeySecret);
-
         /// <summary>
         /// 上传图片
         /// </summary>
@@ -58,13 +51,7 @@ namespace Masuit.MyBlogs.Core.Common
             }
 
             file = Path.GetFileName(file);
-            var fallbackPolicy = Policy<(string url, bool success)>.Handle<Exception>().FallbackAsync(async _ =>
-            {
-                await Task.CompletedTask;
-                return UploadOss(stream, file);
-            });
-            var retryPolicy = Policy<(string url, bool success)>.Handle<Exception>().RetryAsync(3);
-            return await fallbackPolicy.WrapAsync(retryPolicy).ExecuteAsync(() => UploadGitlab(stream, file, cancellationToken));
+            return await Policy<(string url, bool success)>.Handle<Exception>().RetryAsync(3).ExecuteAsync(() => UploadGit(stream, file, cancellationToken));
         }
 
         private readonly List<string> _failedList = new();
@@ -75,7 +62,7 @@ namespace Masuit.MyBlogs.Core.Common
         /// <param name="stream"></param>
         /// <param name="file"></param>
         /// <returns></returns>
-        private async Task<(string url, bool success)> UploadGitlab(Stream stream, string file, CancellationToken cancellationToken)
+        private Task<(string url, bool success)> UploadGit(Stream stream, string file, CancellationToken cancellationToken)
         {
             var gitlabs = AppConfig.GitlabConfigs.Where(c => c.FileLimitSize >= stream.Length && !_failedList.Contains(c.ApiUrl)).OrderBy(c => Guid.NewGuid()).ToList();
             if (gitlabs.Count > 0)
@@ -83,45 +70,18 @@ namespace Masuit.MyBlogs.Core.Common
                 var gitlab = gitlabs[0];
                 if (gitlab.ApiUrl.Contains("gitee.com"))
                 {
-                    return await UploadGitee(gitlab, stream, file, cancellationToken);
+                    return UploadGitee(gitlab, stream, file, cancellationToken);
                 }
 
                 if (gitlab.ApiUrl.Contains("api.github.com"))
                 {
-                    return await UploadGithub(gitlab, stream, file, cancellationToken);
+                    return UploadGithub(gitlab, stream, file, cancellationToken);
                 }
 
-                var path = $"{DateTime.Now:yyyy\\/MM\\/dd}/{file}";
-                _httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", gitlab.AccessToken);
-                return await _httpClient.PostAsJsonAsync(gitlab.ApiUrl.Contains("/v3/") ? gitlab.ApiUrl : gitlab.ApiUrl + HttpUtility.UrlEncode(path), new
-                {
-                    file_path = path,
-                    branch_name = gitlab.Branch,
-                    branch = gitlab.Branch,
-                    author_email = CommonHelper.SystemSettings["ReceiveEmail"],
-                    author_name = SnowFlake.NewId,
-                    encoding = "base64",
-                    content = Convert.ToBase64String(stream.ToArray()),
-                    commit_message = SnowFlake.NewId
-                }, cancellationToken).ContinueWith(t =>
-                {
-                    if (t.IsCompletedSuccessfully)
-                    {
-                        using var resp = t.Result;
-                        using var content = resp.Content;
-                        if (resp.IsSuccessStatusCode || content.ReadAsStringAsync().Result.Contains("already exists"))
-                        {
-                            return (gitlab.RawUrl + path, true);
-                        }
-                    }
-
-                    LogManager.Info($"图片上传到gitlab({gitlab.ApiUrl})失败。");
-                    _failedList.Add(gitlab.ApiUrl);
-                    throw t.Exception ?? new Exception(t.Result.ReasonPhrase);
-                });
+                return UploadGitlab(gitlab, stream, file, cancellationToken);
             }
 
-            return UploadOss(stream, file);
+            return Task.FromResult<(string url, bool success)>((null, false));
         }
 
         /// <summary>
@@ -195,25 +155,41 @@ namespace Masuit.MyBlogs.Core.Common
         }
 
         /// <summary>
-        /// 阿里云Oss图床
+        /// github图床
         /// </summary>
+        /// <param name="config"></param>
         /// <param name="stream"></param>
         /// <param name="file"></param>
         /// <returns></returns>
-        private (string url, bool success) UploadOss(Stream stream, string file)
+        private Task<(string url, bool success)> UploadGitlab(GitlabConfig config, Stream stream, string file, CancellationToken cancellationToken)
         {
-            if (!AppConfig.AliOssConfig.Enabled)
+            var path = $"{DateTime.Now:yyyy\\/MM\\/dd}/{file}";
+            _httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", config.AccessToken);
+            return _httpClient.PostAsJsonAsync(config.ApiUrl.Contains("/v3/") ? config.ApiUrl : config.ApiUrl + HttpUtility.UrlEncode(path), new
             {
-                return (null, false);
-            }
-
-            var objectName = $"{DateTime.Now:yyyy\\/MM\\/dd}/{file}";
-            var fallbackPolicy = Policy<(string url, bool success)>.Handle<Exception>().Fallback(_ => (null, false));
-            var retryPolicy = Policy<(string url, bool success)>.Handle<Exception>().Retry(3);
-            return fallbackPolicy.Wrap(retryPolicy).Execute(() =>
+                file_path = path,
+                branch_name = config.Branch,
+                branch = config.Branch,
+                author_email = CommonHelper.SystemSettings["ReceiveEmail"],
+                author_name = SnowFlake.NewId,
+                encoding = "base64",
+                content = Convert.ToBase64String(stream.ToArray()),
+                commit_message = SnowFlake.NewId
+            }, cancellationToken).ContinueWith(t =>
             {
-                var result = OssClient.PutObject(AppConfig.AliOssConfig.BucketName, objectName, stream);
-                return result.HttpStatusCode == HttpStatusCode.OK ? (AppConfig.AliOssConfig.BucketDomain + "/" + objectName, true) : throw new Exception("上传oss失败");
+                if (t.IsCompletedSuccessfully)
+                {
+                    using var resp = t.Result;
+                    using var content = resp.Content;
+                    if (resp.IsSuccessStatusCode || content.ReadAsStringAsync().Result.Contains("already exists"))
+                    {
+                        return (config.RawUrl + path, true);
+                    }
+                }
+
+                LogManager.Info($"图片上传到gitlab({config.ApiUrl})失败。");
+                _failedList.Add(config.ApiUrl);
+                throw t.Exception ?? new Exception(t.Result.ReasonPhrase);
             });
         }
 

+ 0 - 12
src/Masuit.MyBlogs.Core/Configs/AliOssConfig.cs

@@ -1,12 +0,0 @@
-namespace Masuit.MyBlogs.Core.Configs
-{
-    public class AliOssConfig
-    {
-        public bool Enabled { get; set; }
-        public string EndPoint { get; set; }
-        public string BucketDomain { get; set; }
-        public string AccessKeyId { get; set; }
-        public string AccessKeySecret { get; set; }
-        public string BucketName { get; set; }
-    }
-}

+ 0 - 5
src/Masuit.MyBlogs.Core/Configs/AppConfig.cs

@@ -22,11 +22,6 @@ namespace Masuit.MyBlogs.Core.Configs
         /// </summary>
         public static string Redis { get; set; }
 
-        /// <summary>
-        /// OSS配置
-        /// </summary>
-        public static AliOssConfig AliOssConfig { get; set; } = new AliOssConfig();
-
         /// <summary>
         /// gitlab图床配置
         /// </summary>

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

@@ -95,7 +95,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall
                 RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
                 Time = DateTime.Now,
                 UserAgent = request.Headers[HeaderNames.UserAgent],
-                Remark = "无权限查看该文章",
+                Remark = remark,
                 Address = request.Location()
             });
             var limit = CommonHelper.SystemSettings.GetOrAdd("LimitIPInterceptTimes", "30").ToInt32();

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

@@ -56,7 +56,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall
                     RequestUrl = requestUrl,
                     Time = DateTime.Now,
                     UserAgent = request.Headers[HeaderNames.UserAgent],
-                    Remark = "无权限查看该文章",
+                    Remark = $"检测到敏感词拦截:{match.Value}",
                     Address = request.Location()
                 });
                 context.Response.StatusCode = 400;

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

@@ -25,7 +25,6 @@
     </ItemGroup>
 
     <ItemGroup>
-        <PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.13.0" />
         <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.1.0" />
         <PackageReference Include="AutoMapper.Extensions.ExpressionMapping" Version="4.1.1" />
         <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />

+ 0 - 1
src/Masuit.MyBlogs.Core/Startup.cs

@@ -69,7 +69,6 @@ namespace Masuit.MyBlogs.Core
                 AppConfig.Redis = configuration[nameof(AppConfig.Redis)];
                 AppConfig.TrueClientIPHeader = configuration[nameof(AppConfig.TrueClientIPHeader)] ?? "CF-Connecting-IP";
                 AppConfig.EnableIPDirect = bool.Parse(configuration[nameof(AppConfig.EnableIPDirect)] ?? "false");
-                configuration.Bind("Imgbed:AliyunOSS", AppConfig.AliOssConfig);
                 configuration.Bind("Imgbed:Gitlabs", AppConfig.GitlabConfigs);
                 configuration.AddToMasuitTools();
             }

+ 1 - 9
src/Masuit.MyBlogs.Core/appsettings.json

@@ -58,15 +58,7 @@
             //    "Branch": "main",
             //    "FileLimitSize": 1048576
             //}
-        ],
-        "AliyunOSS": {
-            "Enabled": false,
-            "EndPoint": "Oss节点域名",
-            "BucketDomain": "Oss域名URL",
-            "AccessKeyId": "AccessKeyId",
-            "AccessKeySecret": "AccessKeySecret",
-            "BucketName": "BucketName"
-        }
+        ]
     },
     "HttpClientProxy": { // HttpClient代理设置
         "Enabled": true,