Selaa lähdekoodia

1.图床
2.机器人访问排除
3.前端调整

懒得勤快 6 vuotta sitten
vanhempi
sitoutus
b6b8ea4b40

+ 69 - 5
src/Masuit.MyBlogs.Core/Common/CommonHelper.cs

@@ -15,8 +15,11 @@ using Masuit.Tools.Models;
 #endif
 using Masuit.Tools.NoSQL;
 using Masuit.Tools.Security;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Net.Http.Headers;
 using Newtonsoft.Json;
 using Newtonsoft.Json.Linq;
+using ContentDispositionHeaderValue = System.Net.Http.Headers.ContentDispositionHeaderValue;
 
 namespace Common
 {
@@ -298,8 +301,8 @@ namespace Common
                                     index++;
                                     if (index == apis.Length)
                                     {
-                                        Console.WriteLine("所有上传接口都挂掉了,重试sm.ms图床");
-                                        return UploadImageFallback(file);
+                                        Console.WriteLine("所有上传接口都挂掉了,重试人民网图床");
+                                        return UploadPeople(file);
                                     }
 
                                     Console.WriteLine("正在准备重试图片上传接口:" + apis[index]);
@@ -315,6 +318,57 @@ namespace Common
 
             return (url.Replace("/thumb150/", "/large/"), success);
         }
+        /// <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;
+                            if (!success)
+                            {
+                                Console.WriteLine("人民网图床上传接口都挂掉了,重试sm.ms图床");
+                                return UploadImageFallback(file);
+                            }
+                            return (str, success);
+                        }
+                    }
+                }
+            }
+        }
 
         /// <summary>
         /// 上传图片到sm图床
@@ -379,7 +433,7 @@ namespace Common
         }
 
         /// <summary>
-        /// 上传图片到百度图床
+        /// 上传图片到新浪图床
         /// </summary>
         /// <param name="file">文件名</param>
         /// <returns></returns>
@@ -444,7 +498,7 @@ namespace Common
         }
 
         /// <summary>
-        /// 上传图片到百度图床
+        /// 上传图片到新浪图床
         /// </summary>
         /// <param name="file">文件名</param>
         /// <returns></returns>
@@ -511,7 +565,7 @@ namespace Common
             {
                 if (!src.StartsWith("http"))
                 {
-                    var path = Path.Combine(AppContext.BaseDirectory, src.Replace("/", @"\").Substring(1));
+                    var path = Path.Combine(AppContext.BaseDirectory + "wwwroot", src.Replace("/", @"\").Substring(1));
                     if (File.Exists(path))
                     {
                         var (url, success) = UploadImage(path);
@@ -525,5 +579,15 @@ namespace Common
             }
             return content;
         }
+
+        /// <summary>
+        /// 是否是机器人访问
+        /// </summary>
+        /// <param name="req"></param>
+        /// <returns></returns>
+        public static bool IsRobot(this HttpRequest req)
+        {
+            return req.Headers[HeaderNames.UserAgent].ToString().Contains(new[] { "DNSPod", "Baidu", "spider", "Python", "bot" });
+        }
     }
 }

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

@@ -101,7 +101,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     return RedirectToAction("Post", "Home");
                 }
 
-                if (string.IsNullOrEmpty(HttpContext.Session.GetByRedis<string>("post" + id)))
+                if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.GetByRedis<string>("post" + id)))
                 {
                     HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), args: id);
                     HttpContext.Session.SetByRedis("post" + id, id.ToString());

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

@@ -79,7 +79,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 wd = wd.Trim().Replace("+", " ");
                 if (!string.IsNullOrWhiteSpace(wd) && !wd.Contains("锟斤拷"))
                 {
-                    if (!HttpContext.Session.TryGetValue("search:" + wd, out _))
+                    if (!HttpContext.Session.TryGetValue("search:" + wd, out _) && !HttpContext.Request.IsRobot())
                     {
                         SearchDetailsService.AddEntity(new SearchDetails
                         {

+ 4 - 4
src/Masuit.MyBlogs.Core/Extensions/ExceptionMiddleware.cs

@@ -38,13 +38,13 @@ namespace Masuit.MyBlogs.Core.Extensions
             }
             catch (DbUpdateConcurrencyException ex)
             {
-                var err = $"异常源:{ex.Source},异常类型:{ex.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{HttpUtility.UrlDecode(context.Request.Path)},请求参数:{HttpUtility.UrlDecode(context.Request.Body.ToByteArray(), Encoding.UTF8)},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t{ex.InnerException?.Message}\t";
+                var err = $"异常源:{ex.Source},异常类型:{ex.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{HttpUtility.UrlDecode(context.Request.Path)},请求参数:{HttpUtility.UrlDecode(context.Request.Body.ReadToEnd(Encoding.UTF8))},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t{ex.InnerException?.Message}\t";
                 LogManager.Error(err, ex);
                 await RedirectError(context);
             }
             catch (DbUpdateException ex)
             {
-                var err = $"异常源:{ex.Source},异常类型:{ex.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{HttpUtility.UrlDecode(context.Request.Path)},请求参数:{HttpUtility.UrlDecode(context.Request.Body.ToByteArray(), Encoding.UTF8)},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t{ex?.InnerException?.Message}\t";
+                var err = $"异常源:{ex.Source},异常类型:{ex.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{HttpUtility.UrlDecode(context.Request.Path)},请求参数:{HttpUtility.UrlDecode(context.Request.Body.ReadToEnd(Encoding.UTF8))},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t{ex?.InnerException?.Message}\t";
                 LogManager.Error(err, ex);
                 await RedirectError(context);
             }
@@ -53,7 +53,7 @@ namespace Masuit.MyBlogs.Core.Extensions
                 LogManager.Debug("↓↓↓" + ex.Message + "↓↓↓");
                 ex.Handle(e =>
                 {
-                    LogManager.Error($"异常源:{e.Source},异常类型:{e.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{HttpUtility.UrlDecode(context.Request.Path)},请求参数:{HttpUtility.UrlDecode(context.Request.Body.ToByteArray(), Encoding.UTF8)},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t", e);
+                    LogManager.Error($"异常源:{e.Source},异常类型:{e.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{HttpUtility.UrlDecode(context.Request.Path)},请求参数:{HttpUtility.UrlDecode(context.Request.Body.ReadToEnd(Encoding.UTF8))},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t", e);
                     return true;
                 });
                 await RedirectError(context);
@@ -61,7 +61,7 @@ namespace Masuit.MyBlogs.Core.Extensions
             catch (Exception ex)
             {
                 //LogManager.Error(ex);
-                LogManager.Error($"异常源:{ex.Source},异常类型:{ex.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{HttpUtility.UrlDecode(context.Request.Path)},请求参数:{HttpUtility.UrlDecode(context.Request.Body.ToByteArray(), Encoding.UTF8)},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t", ex);
+                LogManager.Error($"异常源:{ex.Source},异常类型:{ex.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{HttpUtility.UrlDecode(context.Request.Path)},请求参数:{HttpUtility.UrlDecode(context.Request.Body.ReadToEnd(Encoding.UTF8))},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t", ex);
                 await RedirectError(context);
             }
         }

+ 1 - 3
src/Masuit.MyBlogs.Core/Extensions/FirewallMiddleware.cs

@@ -4,7 +4,6 @@ using Masuit.MyBlogs.Core.Extensions.Hangfire;
 using Masuit.Tools;
 using Masuit.Tools.NoSQL;
 using Microsoft.AspNetCore.Http;
-using Microsoft.Net.Http.Headers;
 using System;
 using System.Threading.Tasks;
 using System.Web;
@@ -62,8 +61,7 @@ namespace Masuit.MyBlogs.Core.Extensions
                 return;
             }
 
-            bool isSpider = context.Request.Headers[HeaderNames.UserAgent].ToString().Contains(new[] { "DNSPod", "Baidu", "spider", "Python", "bot" });
-            if (isSpider)
+            if (context.Request.IsRobot())
             {
                 await _next.Invoke(context);
                 return;

+ 3 - 2
src/Masuit.MyBlogs.Core/Extensions/RequestInterceptMiddleware.cs

@@ -1,4 +1,5 @@
-using Masuit.Tools.Core.Net;
+using Common;
+using Masuit.Tools.Core.Net;
 using Masuit.Tools.NoSQL;
 using Microsoft.AspNetCore.Http;
 using System.Threading.Tasks;
@@ -26,7 +27,7 @@ namespace Masuit.MyBlogs.Core.Extensions
 
         public async Task Invoke(HttpContext context)
         {
-            if (!context.Session.TryGetValue("session", out _))
+            if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot())
             {
                 context.Session.Set("session", 0);
                 _redisHelper.StringIncrement("Interview:ViewCount");

+ 9 - 10
src/Masuit.MyBlogs.Core/Extensions/UEditor/CrawlerHandler.cs

@@ -1,4 +1,6 @@
-using Masuit.Tools;
+using Common;
+using Hangfire;
+using Masuit.Tools;
 using Microsoft.AspNetCore.Http;
 using System;
 using System.IO;
@@ -49,9 +51,6 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
         public string ServerUrl { get; set; }
         public string State { get; set; }
 
-        //private HttpServerUtility Server { get; set; }
-
-
         public Crawler(string sourceUrl)
         {
             SourceUrl = sourceUrl;
@@ -92,12 +91,12 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
                             stream.CopyTo(ms);
                             File.WriteAllBytes(savePath, ms.GetBuffer());
                         }
-                        //var (url, success) = CommonHelper.UploadImage(savePath);
-                        //if (success)
-                        //{
-                        //    ServerUrl = url;
-                        //    BackgroundJob.Enqueue(() => File.Delete(savePath));
-                        //}
+                        var (url, success) = CommonHelper.UploadImage(savePath);
+                        if (success)
+                        {
+                            ServerUrl = url;
+                            BackgroundJob.Enqueue(() => File.Delete(savePath));
+                        }
                     }
                     State = "SUCCESS";
                 }

+ 20 - 18
src/Masuit.MyBlogs.Core/Extensions/UEditor/UploadHandler.cs

@@ -1,4 +1,6 @@
-using Microsoft.AspNetCore.Http;
+using Common;
+using Hangfire;
+using Microsoft.AspNetCore.Http;
 using System;
 using System.IO;
 using System.Linq;
@@ -71,23 +73,23 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
                     Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                 }
                 File.WriteAllBytes(localPath, uploadFileBytes);
-                //if (UploadConfig.AllowExtensions.Contains(Path.GetExtension(localPath)))
-                //{
-                //    var (url, success) = CommonHelper.UploadImage(localPath);
-                //    if (success)
-                //    {
-                //        Result.Url = url;
-                //        BackgroundJob.Enqueue(() => File.Delete(localPath));
-                //    }
-                //    else
-                //    {
-                //        Result.Url = savePath;
-                //    }
-                //}
-                //else
-                //{
-                Result.Url = savePath;
-                //}
+                if (UploadConfig.AllowExtensions.Contains(Path.GetExtension(localPath)))
+                {
+                    var (url, success) = CommonHelper.UploadImage(localPath);
+                    if (success)
+                    {
+                        Result.Url = url;
+                        BackgroundJob.Enqueue(() => File.Delete(localPath));
+                    }
+                    else
+                    {
+                        Result.Url = savePath;
+                    }
+                }
+                else
+                {
+                    Result.Url = savePath;
+                }
                 Result.State = UploadState.Success;
             }
             catch (Exception e)

+ 6 - 4
src/Masuit.MyBlogs.Core/Views/Misc/About.cshtml

@@ -29,10 +29,12 @@
         border-top: 3px solid rebeccapurple;
     }
 </style>
-<ol class="cd-breadcrumb triangle">
-    <li>@Html.ActionLink("首页", "Index", "Home")</li>
-    <li class="current"><em>@ViewBag.Title</em></li>
-</ol>
+<div class="container">
+    <ol class="cd-breadcrumb triangle">
+        <li>@Html.ActionLink("首页", "Index", "Home")</li>
+        <li class="current"><em>@ViewBag.Title</em></li>
+    </ol>
+</div>
 <div class="bg-title">
     <div class="header-content text-center">
         <h1 class="size48">

+ 44 - 42
src/Masuit.MyBlogs.Core/Views/Misc/Disclaimer.cshtml

@@ -35,10 +35,12 @@
         font-size: 24px;
     }
 </style>
-<ol class="cd-breadcrumb triangle">
-    <li>@Html.ActionLink("首页", "Index", "Home")</li>
-    <li class="current"><em>@ViewBag.Title</em></li>
-</ol>
+<div class="container">
+    <ol class="cd-breadcrumb triangle">
+        <li>@Html.ActionLink("首页", "Index", "Home")</li>
+        <li class="current"><em>@ViewBag.Title</em></li>
+    </ol>
+</div>
 <div class="bg-title">
     <div class="header-content text-center">
         <h1 class="size48">
@@ -106,43 +108,43 @@
     <!--PC和WAP自适应版-->
     <div id="SOHUCS" sid="disclaimer"></div>
     <script type="text/javascript">
-	                (function() {
-		                var appid = 'cytsT3QgK';
-		                var conf = 'prod_0358240040a6c9611add9de991099d42';
-		                var width = window.innerWidth || document.documentElement.clientWidth;
-		                if (width < 960) {
-			                window.document.write(
-				                '<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' +
-				                appid + '&conf=' + conf + '"><\/script>');
-		                } else {
-			                var loadJs = function(d, a) {
-				                var c = document.getElementsByTagName("head")[0] || document.head || document.documentElement;
-				                var b = document.createElement("script");
-				                b.setAttribute("type", "text/javascript");
-				                b.setAttribute("charset", "UTF-8");
-				                b.setAttribute("src", d);
-				                if (typeof a === "function") {
-					                if (window.attachEvent) {
-						                b.onreadystatechange = function() {
-							                var e = b.readyState;
-							                if (e === "loaded" || e === "complete") {
-								                b.onreadystatechange = null;
-								                a()
-							                }
-						                }
-					                } else {
-						                b.onload = a
-					                }
-				                }
-				                c.appendChild(b)
-			                };
-			                loadJs("https://changyan.sohu.com/upload/changyan.js", function() {
-				                window.changyan.api.config({
-					                appid: appid,
-					                conf: conf
-				                })
-			                });
-		                }
-	                })();
+        (function () {
+            var appid = 'cytsT3QgK';
+            var conf = 'prod_0358240040a6c9611add9de991099d42';
+            var width = window.innerWidth || document.documentElement.clientWidth;
+            if (width < 960) {
+                window.document.write(
+                    '<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' +
+                    appid + '&conf=' + conf + '"><\/script>');
+            } else {
+                var loadJs = function (d, a) {
+                    var c = document.getElementsByTagName("head")[0] || document.head || document.documentElement;
+                    var b = document.createElement("script");
+                    b.setAttribute("type", "text/javascript");
+                    b.setAttribute("charset", "UTF-8");
+                    b.setAttribute("src", d);
+                    if (typeof a === "function") {
+                        if (window.attachEvent) {
+                            b.onreadystatechange = function () {
+                                var e = b.readyState;
+                                if (e === "loaded" || e === "complete") {
+                                    b.onreadystatechange = null;
+                                    a()
+                                }
+                            }
+                        } else {
+                            b.onload = a
+                        }
+                    }
+                    c.appendChild(b)
+                };
+                loadJs("https://changyan.sohu.com/upload/changyan.js", function () {
+                    window.changyan.api.config({
+                        appid: appid,
+                        conf: conf
+                    })
+                });
+            }
+        })();
     </script>
 </div>

+ 1 - 3
src/Masuit.MyBlogs.Core/Views/Shared/_ArticleListItem.cshtml

@@ -52,9 +52,7 @@
             <div class="col-md-@(string.IsNullOrEmpty(imgSrc) ? 12 : 9)">
                 <div class="small padding-bot10">
                     作者:<i class="icon-user-check"></i><strong class="label label-primary">@Model.Author</strong> <span class="text-muted">
-                        |
-                        发表时间:<i class="fa fa-clock-o"></i> @Model.ModifyDate.ToString("yyyy-MM-dd HH:mm") |
-                        分类:<i class="icon-map-pin"></i>@Html.ActionLink(Model.CategoryName, "Category", "Home", new { id = Model.CategoryId }, null)
+                        | 发表时间:<i class="fa fa-clock-o"></i> @Model.ModifyDate.ToString("yyyy-MM-dd HH:mm") | 分类:<i class="icon-map-pin"></i>@Html.ActionLink(Model.CategoryName, "Category", "Home", new { id = Model.CategoryId }, null)
                     </span>
                 </div>
                 <p>

+ 9 - 1
src/Masuit.MyBlogs.Core/wwwroot/Assets/highlight/css/highlight.css

@@ -1 +1,9 @@
-.highlight{background-color:#fff34d;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;-moz-box-shadow:0 1px 4px rgba(0,0,0,.7);-webkit-box-shadow:0 1px 4px rgba(0,0,0,.7);box-shadow:0 1px 4px rgba(0,0,0,.7)}.button{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:inline-block;padding:1px 2px;font-size:12px;cursor:pointer;text-align:center;text-decoration:none;outline:0;color:#fff;background-color:#4caf50;border:0;border-radius:8px;box-shadow:0 2px #999;height:20px;width:100px;bottom:10px;right:20px}.button:hover{background-color:#3e8e41}.button:active{background-color:#3e8e41;box-shadow:0 1px #666;transform:translateY(4px)}
+.highlight {
+    background-color: #fff34d;
+    /*-moz-border-radius: 5px;
+    -webkit-border-radius: 5px;
+    border-radius: 5px;
+    -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, .7);
+    -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, .7);
+    box-shadow: 0 1px 4px rgba(0, 0, 0, .7)*/
+}