浏览代码

gitlab图床支持

懒得勤快 6 年之前
父节点
当前提交
0e071cf329

+ 99 - 11
src/Masuit.MyBlogs.Core/Common/CommonHelper.cs

@@ -8,11 +8,14 @@ using Masuit.Tools.Systems;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Net.Http.Headers;
 using Newtonsoft.Json.Linq;
+using Polly;
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
+using System.Drawing;
 using System.IO;
 using System.Linq;
+using System.Net;
 using System.Net.Http;
 using System.Net.Http.Headers;
 #if !DEBUG
@@ -188,27 +191,65 @@ namespace Masuit.MyBlogs.Core.Common
         /// </summary>
         public static OssClient OssClient { get; set; } = new OssClient(AppConfig.AliOssConfig.EndPoint, AppConfig.AliOssConfig.AccessKeyId, AppConfig.AliOssConfig.AccessKeySecret);
 
+        /// <summary>
+        /// 阿里云Oss图床
+        /// </summary>
+        /// <param name="file"></param>
+        /// <returns></returns>
         public static (string url, bool success) UploadImage(string file)
         {
             if (!AppConfig.AliOssConfig.Enabled)
             {
-                return UploadSmms(file);
+                return UploadGitlab(file);
             }
 
             var objectName = DateTime.Now.ToString("yyyyMMdd") + "/" + SnowFlake.NewId + Path.GetExtension(file);
-            for (int i = 0; i < 3; i++)
+            var result = Policy.Handle<Exception>().Retry(5, (e, i) =>
+             {
+                 Console.ForegroundColor = ConsoleColor.Red;
+                 Console.WriteLine(e.Message);
+                 Console.ResetColor();
+             }).Execute(() => OssClient.PutObject(AppConfig.AliOssConfig.BucketName, objectName, file));
+            return result.HttpStatusCode == HttpStatusCode.OK ? (AppConfig.AliOssConfig.BucketDomain + "/" + objectName, true) : UploadSmms(file);
+        }
+
+        /// <summary>
+        /// gitlab图床
+        /// </summary>
+        /// <param name="file"></param>
+        /// <returns></returns>
+        public static (string url, bool success) UploadGitlab(string file)
+        {
+            if (!AppConfig.GitlabConfig.Enabled)
             {
-                try
-                {
-                    OssClient.PutObject(AppConfig.AliOssConfig.BucketName, objectName, file);
-                    return (AppConfig.AliOssConfig.BucketDomain + "/" + objectName, true);
-                }
-                catch
+                return UploadSmms(file);
+            }
+
+            using (Image image = Image.FromFile(file))
+            {
+                using (MemoryStream m = new MemoryStream())
                 {
+                    image.Save(m, image.RawFormat);
+                    string base64String = Convert.ToBase64String(m.ToArray());
+                    HttpClient httpClient = new HttpClient();
+                    httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", AppConfig.GitlabConfig.AccessToken);
+                    var resp = httpClient.PostAsJsonAsync(AppConfig.GitlabConfig.ApiUrl + Path.GetFileName(file), new
+                    {
+                        branch = AppConfig.GitlabConfig.Branch,
+                        author_email = "[email protected]",
+                        author_name = "ldqk",
+                        encoding = "base64",
+                        content = base64String,
+                        commit_message = "上传一张图片"
+                    }).Result;
+                    if (resp.IsSuccessStatusCode)
+                    {
+                        return (AppConfig.GitlabConfig.RawUrl + Path.GetFileName(file), true);
+                    }
+
+                    return UploadSmms(file);
                 }
             }
-
-            return UploadSmms(file);
         }
 
         /// <summary>
@@ -267,7 +308,54 @@ namespace Masuit.MyBlogs.Core.Common
                 }
             }
 
-            return (url, success);
+            return success ? (url, true) : UploadPeople(file);
+        }
+
+        /// <summary>
+        /// 上传图片到人民网图床
+        /// </summary>
+        /// <param name="file"></param>
+        /// <returns></returns>
+        public static (string url, bool success) UploadPeople(string file)
+        {
+            bool success = false;
+            using (var httpClient = new HttpClient())
+            {
+                httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Chrome/72.0.3626.96"));
+                using (var stream = File.OpenRead(file))
+                {
+                    using (var sc = new StreamContent(stream))
+                    {
+                        using (var mc = new MultipartFormDataContent
+                        {
+                            { sc, "Filedata", Path.GetFileName(file) },
+                            {new StringContent("."+Path.GetExtension(file)),"filetype"}
+                        })
+                        {
+                            var str = httpClient.PostAsync("http://bbs1.people.com.cn/postImageUpload.do", mc).ContinueWith(t =>
+                            {
+                                if (t.IsCompletedSuccessfully)
+                                {
+                                    var res = t.Result;
+                                    if (res.IsSuccessStatusCode)
+                                    {
+                                        string result = res.Content.ReadAsStringAsync().Result;
+                                        string url = "http://bbs1.people.com.cn" + (string)JObject.Parse(result)["imageUrl"];
+                                        if (url.EndsWith(Path.GetExtension(file)))
+                                        {
+                                            success = true;
+                                            return url;
+                                        }
+                                    }
+                                }
+
+                                return "";
+                            }).Result;
+                            return (str, success);
+                        }
+                    }
+                }
+            }
         }
 
         /// <summary>

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

@@ -25,6 +25,11 @@
         /// </summary>
         public static AliOssConfig AliOssConfig { get; set; } = new AliOssConfig();
 
+        /// <summary>
+        /// gitlab图床配置
+        /// </summary>
+        public static GitlabConfig GitlabConfig { get; set; } = new GitlabConfig();
+
         /// <summary>
         /// 图床域名
         /// </summary>

+ 11 - 0
src/Masuit.MyBlogs.Core/Configs/GitlabConfig.cs

@@ -0,0 +1,11 @@
+namespace Masuit.MyBlogs.Core.Configs
+{
+    public class GitlabConfig
+    {
+        public bool Enabled { get; set; }
+        public string ApiUrl { get; set; }
+        public string RawUrl { get; set; }
+        public string AccessToken { get; set; }
+        public string Branch { get; set; }
+    }
+}

+ 0 - 2
src/Masuit.MyBlogs.Core/Controllers/SystemController.cs

@@ -13,7 +13,6 @@ using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Mvc;
 using Newtonsoft.Json;
 using System;
-using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
@@ -166,7 +165,6 @@ namespace Masuit.MyBlogs.Core.Controllers
         public ActionResult Save(string sets)
         {
             SystemSetting[] settings = JsonConvert.DeserializeObject<List<SystemSetting>>(sets).ToArray();
-            ConcurrentDictionary<string, HashSet<string>> dic = new ConcurrentDictionary<string, HashSet<string>>();
             foreach (var set in settings)
             {
                 var entry = SystemSettingService.GetFirstEntity(s => s.Name.Equals(set.Name));

+ 26 - 0
src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.xml

@@ -87,12 +87,33 @@
             OSS客户端
             </summary>
         </member>
+        <member name="M:Masuit.MyBlogs.Core.Common.CommonHelper.UploadImage(System.String)">
+            <summary>
+            阿里云Oss图床
+            </summary>
+            <param name="file"></param>
+            <returns></returns>
+        </member>
+        <member name="M:Masuit.MyBlogs.Core.Common.CommonHelper.UploadGitlab(System.String)">
+            <summary>
+            gitlab图床
+            </summary>
+            <param name="file"></param>
+            <returns></returns>
+        </member>
         <member name="M:Masuit.MyBlogs.Core.Common.CommonHelper.UploadSmms(System.String)">
             <summary>
             上传图片到sm图床
             </summary>
             <returns></returns>
         </member>
+        <member name="M:Masuit.MyBlogs.Core.Common.CommonHelper.UploadPeople(System.String)">
+            <summary>
+            上传图片到人民网图床
+            </summary>
+            <param name="file"></param>
+            <returns></returns>
+        </member>
         <member name="M:Masuit.MyBlogs.Core.Common.CommonHelper.ReplaceImgSrc(System.String)">
             <summary>
             替换img标签的src属性
@@ -216,6 +237,11 @@
             OSS配置
             </summary>
         </member>
+        <member name="P:Masuit.MyBlogs.Core.Configs.AppConfig.GitlabConfig">
+            <summary>
+            gitlab图床配置
+            </summary>
+        </member>
         <member name="P:Masuit.MyBlogs.Core.Configs.AppConfig.ImgbedDomains">
             <summary>
             图床域名

+ 3 - 2
src/Masuit.MyBlogs.Core/Startup.cs

@@ -67,8 +67,9 @@ namespace Masuit.MyBlogs.Core
             AppConfig.ConnString = configuration[nameof(AppConfig.ConnString)];
             AppConfig.BaiduAK = configuration[nameof(AppConfig.BaiduAK)];
             AppConfig.Redis = configuration[nameof(AppConfig.Redis)];
-            configuration.Bind("AliyunOSS", AppConfig.AliOssConfig);
-            configuration.Bind("ImgbedDomains", AppConfig.ImgbedDomains);
+            configuration.Bind("Imgbed:AliyunOSS", AppConfig.AliOssConfig);
+            configuration.Bind("Imgbed:Gitlab", AppConfig.GitlabConfig);
+            configuration.Bind("Imgbed:ImgbedDomains", AppConfig.ImgbedDomains);
         }
 
         /// <summary>

+ 42 - 31
src/Masuit.MyBlogs.Core/appsettings.json

@@ -1,33 +1,44 @@
-{
-	"Logging":{
-		"LogLevel":{
-			"Default":"Error"
-		}
-	},
-	"AllowedHosts":"*",
-	"cert":{
-		"path":"App_Data/cert/server.pfx",
-		"password":"cEHlnUGu"
-	},
-	"ConnString":"Server=127.0.0.1;Port=3306;Database=MyBlogs;Uid=root;Pwd=;Charset=utf8mb4",
-	//"ConnString": "Data Source=.;Initial Catalog=MyBlogs;Integrated Security=True",
-	"BaiduAK":"您的BaiduAK",
-	"Redis":"127.0.0.1:6379,allowadmin=true,connectTimeout=20000,connectRetry=1,responseTimeout=20000,syncTimeout=10000",
-    "AliyunOSS": {
-        "Enabled": true, // 是否启用阿里云OSS
-        "EndPoint": "阿里云OSS节点",
-        "BucketDomain": "阿里云OSS bucket节点访问地址",
-        "AccessKeyId": "OSS AccessKeyId",
-        "AccessKeySecret": "OSS AccessKeySecret",
-        "BucketName": "BucketName"
+锘縶
+    "Logging": {
+        "LogLevel": {
+            "Default": "Error"
+        }
     },
-	"ImgbedDomains": [
-		"git.imweb.io",
-		"git.lug.ustc.edu.cn",
-		"loli.net",
-		"sinaimg.cn",
-		"alicdn.com",
-		"kuaizhan.com",
-		"qpic.cn"
-	]
+    "AllowedHosts": "*",
+    "cert": {
+        "path": "App_Data/cert/server.pfx",
+        "password": "cEHlnUGu"
+    },
+    "ConnString": "Server=127.0.0.1;Port=3306;Database=MyBlogs;Uid=root;Pwd=;Charset=utf8mb4",
+    //"ConnString": "Data Source=.;Initial Catalog=MyBlogs;Integrated Security=True",
+    "BaiduAK": "浣犵殑BaiduAK",
+    "Redis": "127.0.0.1:6379,allowadmin=true,connectTimeout=20000,connectRetry=1,responseTimeout=20000,syncTimeout=10000",
+    "Imgbed": { // 鍥惧簥鐩稿叧閰嶇疆
+        "AliyunOSS": {
+            "Enabled": false,
+            "EndPoint": "Oss鑺傜偣鍩熷悕",
+            "BucketDomain": "Oss鍩熷悕URL",
+            "AccessKeyId": "AccessKeyId",
+            "AccessKeySecret": "AccessKeySecret",
+            "BucketName": "BucketName"
+        },
+        "Gitlab": {
+            "Enabled": false,
+            "ApiUrl": "https://gitlab.com/api/v4/projects/<浣犵殑椤圭洰id>/repository/files/", // /api/v4/projects/<椤圭洰id>/repository/files/锛屼娇鐢ㄥ墠璇峰厛鑾峰彇private_token锛岀劧鍚庢牴private_token鎹�潵鑾峰彇椤圭洰id锛�/api/v4/projects?private_token=<浣犵殑private_token>&search=<椤圭洰浠撳簱鍚�>
+            "RawUrl": "https://gitlab.com/masuit/imgbed/raw/master/",
+            "AccessToken": "浣犵殑private_token",
+            "Branch": "master"
+        },
+        "ImgbedDomains": [
+            "git.imweb.io",
+            "gitlab.com",
+            "github.com",
+            "git.lug.ustc.edu.cn",
+            "loli.net",
+            "sinaimg.cn",
+            "alicdn.com",
+            "kuaizhan.com",
+            "qpic.cn"
+        ]
+    }
 }