فهرست منبع

文章链接增加跟踪参数

懒得勤快 3 سال پیش
والد
کامیت
5249ec71bb

+ 2 - 2
src/Masuit.MyBlogs.Core/Controllers/AdvertisementController.cs

@@ -34,7 +34,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         public async Task<IActionResult> Redirect(int id)
         {
             var ad = await AdsService.GetByIdAsync(id) ?? throw new NotFoundException("推广链接不存在");
-            if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get<string>("ads" + id)))
+            if (!Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get<string>("ads" + id)))
             {
                 HttpContext.Session.Set("ads" + id, id.ToString());
                 ad.ClickRecords.Add(new AdvertisementClickRecord()
@@ -138,7 +138,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         public async Task<ActionResult> RandomGo()
         {
             var ad = AdsService.GetByWeightedPrice((AdvertiseType)new Random().Next(1, 4), Request.Location());
-            if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get<string>("ads" + ad.Id)))
+            if (!Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get<string>("ads" + ad.Id)))
             {
                 HttpContext.Session.Set("ads" + ad.Id, ad.Id.ToString());
                 ad.ClickRecords.Add(new AdvertisementClickRecord()

+ 14 - 18
src/Masuit.MyBlogs.Core/Controllers/BaseController.cs

@@ -13,6 +13,7 @@ using Masuit.MyBlogs.Core.Models.Enum;
 using Masuit.MyBlogs.Core.Models.ViewModel;
 using Masuit.Tools;
 using Masuit.Tools.Core.Net;
+using Masuit.Tools.Linq;
 using Masuit.Tools.Security;
 using Masuit.Tools.Strings;
 using Microsoft.AspNetCore.Mvc;
@@ -31,23 +32,13 @@ namespace Masuit.MyBlogs.Core.Controllers
     [ApiExplorerSettings(IgnoreApi = true), ServiceFilter(typeof(FirewallAttribute))]
     public class BaseController : Controller
     {
-        /// <summary>
-        /// UserInfoService
-        /// </summary>
         public IUserInfoService UserInfoService { get; set; }
-
-        /// <summary>
-        /// MenuService
-        /// </summary>
         public IMenuService MenuService { get; set; }
-
-        /// <summary>
-        /// LinksService
-        /// </summary>
         public ILinksService LinksService { get; set; }
-
         public IAdvertisementService AdsService { get; set; }
         public IVariablesService VariablesService { get; set; }
+        public IMapper Mapper { get; set; }
+        public MapperConfiguration MapperConfig { get; set; }
 
         public UserInfoDto CurrentUser => HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
 
@@ -61,9 +52,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         public bool VisitorTokenValid => Request.Cookies["Email"].MDString3(AppConfig.BaiduAK).Equals(Request.Cookies["FullAccessToken"]);
 
-
-        public IMapper Mapper { get; set; }
-        public MapperConfiguration MapperConfig { get; set; }
+        public int[] HideCategories => HttpContext.Session.Get<int[]>(SessionKey.HideCategories) ?? Request.Cookies[SessionKey.HideCategories]?.Split(',').Select(s => s.ToInt32()).ToArray() ?? Request.Query[SessionKey.SafeMode].ToString().Split(',').Select(s => s.ToInt32()).ToArray();
 
         /// <summary>
         /// 响应数据
@@ -275,13 +264,20 @@ namespace Masuit.MyBlogs.Core.Controllers
                         return false;
                 }
             });
+            posts.RemoveAll(p => HideCategories.Contains(p.CategoryId));
         }
 
         protected Expression<Func<Post, bool>> PostBaseWhere()
         {
+            Expression<Func<Post, bool>> where = _ => true;
+            if (HideCategories.Length > 0)
+            {
+                where = where.And(p => !HideCategories.Contains(p.CategoryId));
+            }
+
             if (CurrentUser.IsAdmin || VisitorTokenValid || Request.IsRobot())
             {
-                return _ => true;
+                return where;
             }
 
             var location = Request.Location() + "|" + Request.Headers[HeaderNames.Referer] + "|" + Request.Headers[HeaderNames.UserAgent];
@@ -294,10 +290,10 @@ namespace Masuit.MyBlogs.Core.Controllers
                 }
             }
 
-            return p => p.LimitMode == null || p.LimitMode == RegionLimitMode.All ? true :
+            return where.And(p => p.LimitMode == null || p.LimitMode == RegionLimitMode.All ? true :
                    p.LimitMode == RegionLimitMode.AllowRegion ? Regex.IsMatch(location, p.Regions) :
                    p.LimitMode == RegionLimitMode.ForbidRegion ? !Regex.IsMatch(location, p.Regions) :
-                   p.LimitMode == RegionLimitMode.AllowRegionExceptForbidRegion ? Regex.IsMatch(location, p.Regions) && !Regex.IsMatch(location, p.ExceptRegions) : !Regex.IsMatch(location, p.Regions) || Regex.IsMatch(location, p.ExceptRegions);
+                   p.LimitMode == RegionLimitMode.AllowRegionExceptForbidRegion ? Regex.IsMatch(location, p.Regions) && !Regex.IsMatch(location, p.ExceptRegions) : !Regex.IsMatch(location, p.Regions) || Regex.IsMatch(location, p.ExceptRegions));
         }
 
         protected void CheckPermission(Post post)

+ 8 - 2
src/Masuit.MyBlogs.Core/Controllers/PostController.cs

@@ -70,8 +70,14 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="kw"></param>
         /// <returns></returns>
         [Route("{id:int}"), Route("{id:int}/comments/{cid:int}"), ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
-        public async Task<ActionResult> Details(int id, string kw)
+        public async Task<ActionResult> Details(int id, string kw, string t)
         {
+            var notRobot = !Request.IsRobot();
+            if (string.IsNullOrEmpty(t) && notRobot)
+            {
+                return RedirectToAction("Details", new { id, kw, t = SnowFlake.NewId });
+            }
+
             var post = await PostService.GetAsync(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到");
             CheckPermission(post);
             ViewBag.Keyword = post.Keyword + "," + post.Label;
@@ -97,7 +103,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 return View("Details_Admin", post);
             }
 
-            if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get<string>("post" + id)))
+            if (notRobot && string.IsNullOrEmpty(HttpContext.Session.Get<string>("post" + id)))
             {
                 HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), args: new dynamic[] { id, ClientIP, Request.Headers[HeaderNames.Referer].ToString(), HttpUtility.UrlDecode(Request.Scheme + "://" + Request.Host + Request.Path + Request.QueryString) });
                 HttpContext.Session.Set("post" + id, id.ToString());

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

@@ -42,7 +42,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             ViewBag.Keyword = wd;
             if (!string.IsNullOrWhiteSpace(wd))
             {
-                if (!HttpContext.Session.TryGetValue("search:" + wd, out _) && !HttpContext.Request.IsRobot())
+                if (!HttpContext.Session.TryGetValue("search:" + wd, out _) && !Request.IsRobot())
                 {
                     SearchDetailsService.AddEntity(new SearchDetails
                     {

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

@@ -1,6 +1,7 @@
 using CacheManager.Core;
 using Masuit.MyBlogs.Core.Common;
 using Masuit.MyBlogs.Core.Configs;
+using Masuit.MyBlogs.Core.Controllers;
 using Masuit.MyBlogs.Core.Models.ViewModel;
 using Masuit.Tools;
 using Masuit.Tools.AspNetCore.Mime;
@@ -14,7 +15,6 @@ using System.Net;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Web;
-using Masuit.MyBlogs.Core.Controllers;
 using HeaderNames = Microsoft.Net.Http.Headers.HeaderNames;
 
 namespace Masuit.MyBlogs.Core.Extensions.Firewall
@@ -81,6 +81,17 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall
                 return;
             }
 
+            //安全模式
+            if (request.Query[SessionKey.SafeMode].Count > 0)
+            {
+                context.HttpContext.Session.Set(SessionKey.HideCategories, request.Query[SessionKey.SafeMode].ToString().Split(',').Select(s => s.ToInt32()).ToArray());
+                context.HttpContext.Response.Cookies.Append(SessionKey.HideCategories, request.Query[SessionKey.SafeMode].ToString(), new CookieOptions
+                {
+                    Expires = DateTime.Now.AddYears(1),
+                    SameSite = SameSiteMode.Lax
+                });
+            }
+
             //白名单地区
             var (location, network, pos) = ip.GetIPLocation();
             var allowedAreas = CommonHelper.SystemSettings.GetOrAdd("AllowedArea", "").Split(new[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries);

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

@@ -38,7 +38,7 @@
 
     <ItemGroup>
         <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.2.0" />
-        <PackageReference Include="AutoMapper.Extensions.ExpressionMapping" Version="4.1.3" />
+        <PackageReference Include="AutoMapper.Collection.EntityFrameworkCore" Version="7.1.3" />
         <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
         <PackageReference Include="CacheManager.Serialization.Json" Version="1.2.0" />
         <PackageReference Include="CacheManager.StackExchange.Redis" Version="1.2.0" />

+ 2 - 0
src/Masuit.MyBlogs.Core/Models/ViewModel/SessionKey.cs

@@ -3,11 +3,13 @@
     public static class SessionKey
     {
         public const string UserInfo = "userinfo";
+        public const string HideCategories = nameof(HideCategories);
         public const string TimeZone = "TimeZone";
         public const string RawIP = "rawip";
         public const string ChallengeMode = nameof(ChallengeMode);
         public const string CaptchaChallenge = nameof(CaptchaChallenge);
         public const string JSChallenge = nameof(JSChallenge);
         public const string ChallengeBypass = "challenge-bypass";
+        public const string SafeMode = "safemode";
     }
 }