Skip to content

Commit

Permalink
1.搜索优化;
Browse files Browse the repository at this point in the history
2.防火墙规则优化;
3.广告商竞价模块;
4.强类型html;
5.一些前端样式调整
  • Loading branch information
ldqk committed Oct 28, 2019
1 parent 742d23a commit 7714467
Show file tree
Hide file tree
Showing 73 changed files with 2,013 additions and 3,945 deletions.
3,355 changes: 57 additions & 3,298 deletions database/mysql/myblogs.sql

Large diffs are not rendered by default.

19 changes: 14 additions & 5 deletions src/Masuit.MyBlogs.Core/Common/CommonHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,15 +144,24 @@ public static bool IsDenyIpAddress(this string ip)
return false;
}

var denyed = DenyIP.Contains(ip) || DenyIPRange.AsParallel().Any(kv => kv.Key.StartsWith(ip.Split('.')[0]) && ip.IpAddressInRange(kv.Key, kv.Value));
return DenyIP.Contains(ip) || DenyIPRange.AsParallel().Any(kv => kv.Key.StartsWith(ip.Split('.')[0]) && ip.IpAddressInRange(kv.Key, kv.Value));
}

/// <summary>
/// 是否是禁区
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsInDenyArea(this string ip)
{
if (SystemSettings.GetOrAdd("EnableDenyArea", "false") == "false")
{
return denyed;
var pos = GetIPLocation(ip);
var denyAreas = SystemSettings.GetOrAdd("DenyArea", "").Split(',', ',');
return pos.Contains(denyAreas) || denyAreas.Intersect(pos.Split("|")).Any();
}

var pos = GetIPLocation(ip);
var denyAreas = SystemSettings.GetOrAdd("DenyArea", "").Split(',', ',');
return denyed || pos.Contains(denyAreas) || denyAreas.Intersect(pos.Split("|")).Any();
return false;
}

public static string GetIPLocation(this IPAddress ip) => GetIPLocation(ip.MapToIPv4().ToString());
Expand Down
67 changes: 34 additions & 33 deletions src/Masuit.MyBlogs.Core/Common/ImagebedClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,6 @@ public ImagebedClient(IHttpClientFactory httpClientFactory)
/// <returns></returns>
public async Task<(string url, bool success)> UploadImage(Stream stream, string file)
{
if (AppConfig.GiteeConfig.Enabled && stream.Length < AppConfig.GiteeConfig.FileLimitSize)
{
return await UploadGitee(stream, file);
}

if (AppConfig.GitlabConfigs.Any())
{
return await UploadGitlab(stream, file);
Expand All @@ -63,30 +58,6 @@ public ImagebedClient(IHttpClientFactory httpClientFactory)
return await UploadSmms(stream, file);
}

/// <summary>
/// 码云图床
/// </summary>
/// <param name="stream"></param>
/// <param name="file"></param>
/// <returns></returns>
public async Task<(string url, bool success)> UploadGitee(Stream stream, string file)
{
string base64String = Convert.ToBase64String(stream.ToByteArray());
string path = $"{DateTime.Now:yyyyMMdd}/{Path.GetFileName(file)}";
using var resp = await _httpClient.PostAsJsonAsync(AppConfig.GiteeConfig.ApiUrl + HttpUtility.UrlEncode(path), new
{
access_token = AppConfig.GiteeConfig.AccessToken,
content = base64String,
message = "上传一张图片"
});
if (resp.IsSuccessStatusCode || (await resp.Content.ReadAsStringAsync()).Contains("already exists"))
{
return (AppConfig.GiteeConfig.RawUrl + path, true);
}

return AppConfig.AliOssConfig.Enabled ? await UploadOss(stream, file) : await UploadSmms(stream, file);
}

/// <summary>
/// gitlab图床
/// </summary>
Expand All @@ -101,9 +72,14 @@ public ImagebedClient(IHttpClientFactory httpClientFactory)
return AppConfig.AliOssConfig.Enabled ? await UploadOss(stream, file) : await UploadSmms(stream, file);
}

if (gitlab.ApiUrl.Contains("gitee.com"))
{
return await UploadGitee(gitlab, stream, file);
}

string base64String = Convert.ToBase64String(stream.ToByteArray());
string path = $"{DateTime.Now:yyyy/MM/dd}/{SnowFlake.NewId + Path.GetExtension(file)}";
_httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", gitlab.AccessToken);
string path = $"{DateTime.Now:yyyyMMdd}/{Path.GetFileName(file)}";
using var resp = await _httpClient.PostAsJsonAsync(gitlab.ApiUrl.Contains("/v3/") ? gitlab.ApiUrl : gitlab.ApiUrl + HttpUtility.UrlEncode(path), new
{
file_path = path,
Expand All @@ -123,6 +99,31 @@ public ImagebedClient(IHttpClientFactory httpClientFactory)
return AppConfig.AliOssConfig.Enabled ? await UploadOss(stream, file) : await UploadSmms(stream, file);
}

/// <summary>
/// 码云图床
/// </summary>
/// <param name="config"></param>
/// <param name="stream"></param>
/// <param name="file"></param>
/// <returns></returns>
private async Task<(string url, bool success)> UploadGitee(GitlabConfig config, Stream stream, string file)
{
string base64String = Convert.ToBase64String(stream.ToByteArray());
string path = $"{DateTime.Now:yyyy/MM/dd}/{Path.GetFileName(file)}";
using var resp = await _httpClient.PostAsJsonAsync(config.ApiUrl + HttpUtility.UrlEncode(path), new
{
access_token = config.AccessToken,
content = base64String,
message = "上传一张图片"
});
if (resp.IsSuccessStatusCode || (await resp.Content.ReadAsStringAsync()).Contains("already exists"))
{
return (config.RawUrl + path, true);
}

return AppConfig.AliOssConfig.Enabled ? await UploadOss(stream, file) : await UploadSmms(stream, file);
}

/// <summary>
/// 阿里云Oss图床
/// </summary>
Expand All @@ -132,13 +133,13 @@ public ImagebedClient(IHttpClientFactory httpClientFactory)
public async Task<(string url, bool success)> UploadOss(Stream stream, string file)
{
var objectName = DateTime.Now.ToString("yyyyMMdd") + "/" + SnowFlake.NewId + Path.GetExtension(file);
var result = Policy.Handle<Exception>().Retry(5, (e, i) =>
var policy = Policy.Handle<Exception>().Retry(5, (e, i) =>
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
Console.ResetColor();
}).Execute(() => OssClient.PutObject(AppConfig.AliOssConfig.BucketName, objectName, stream));
return result.HttpStatusCode == HttpStatusCode.OK ? (AppConfig.AliOssConfig.BucketDomain + "/" + objectName, true) : await UploadSmms(stream, file);
});
return policy.Wrap(Policy<(string url, bool success)>.Handle<Exception>().Fallback(() => UploadSmms(stream, file).Result)).Execute(() => OssClient.PutObject(AppConfig.AliOssConfig.BucketName, objectName, stream).HttpStatusCode == HttpStatusCode.OK ? (AppConfig.AliOssConfig.BucketDomain + "/" + objectName, true) : UploadSmms(stream, file).Result);
}

/// <summary>
Expand Down
5 changes: 0 additions & 5 deletions src/Masuit.MyBlogs.Core/Configs/AppConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,5 @@ public class AppConfig
/// gitlab图床配置
/// </summary>
public static List<GitlabConfig> GitlabConfigs { get; set; } = new List<GitlabConfig>();

/// <summary>
/// 码云图床配置
/// </summary>
public static GitlabConfig GiteeConfig { get; set; } = new GitlabConfig();
}
}
4 changes: 4 additions & 0 deletions src/Masuit.MyBlogs.Core/Configs/MappingProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Masuit.MyBlogs.Core.Models.Enum;
using Masuit.MyBlogs.Core.Models.ViewModel;
using Masuit.Tools.Systems;
using System;
using System.Linq;

namespace Masuit.MyBlogs.Core.Configs
Expand Down Expand Up @@ -83,6 +84,9 @@ public MappingProfile()
CreateMap<PostMergeRequest, PostMergeRequestOutputDto>().ForMember(p => p.PostTitle, e => e.MapFrom(r => r.Post.Title));
CreateMap<PostMergeRequest, Post>().ForMember(p => p.Id, e => e.Ignore()).ForMember(p => p.Status, e => e.Ignore()).ReverseMap();
CreateMap<Post, PostMergeRequestOutputDto>().ReverseMap();

CreateMap<Advertisement, AdvertisementViewModel>().ForMember(a => a.CategoryName, e => e.MapFrom(a => a.Category.Name));
CreateMap<AdvertisementInputDto, Advertisement>().ForMember(a => a.CategoryId, e => e.MapFrom(d => string.IsNullOrEmpty(d.CategoryId) ? null : d.CategoryId)).ForMember(a => a.Status, e => e.Ignore()).ForMember(a => a.UpdateTime, e => e.MapFrom(a => DateTime.Now));
}
}
}
114 changes: 114 additions & 0 deletions src/Masuit.MyBlogs.Core/Controllers/AdvertisementController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
using AutoMapper.QueryableExtensions;
using Masuit.LuceneEFCore.SearchEngine.Linq;
using Masuit.MyBlogs.Core.Common;
using Masuit.MyBlogs.Core.Extensions;
using Masuit.MyBlogs.Core.Models.DTO;
using Masuit.MyBlogs.Core.Models.Entity;
using Masuit.MyBlogs.Core.Models.Enum;
using Masuit.MyBlogs.Core.Models.ViewModel;
using Masuit.Tools.Core.Net;
using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Masuit.MyBlogs.Core.Controllers
{
[Route("ads/[action]")]
public class AdvertisementController : BaseController
{
/// <summary>
/// 前往
/// </summary>
/// <param name="id">广告id</param>
/// <returns></returns>
[HttpGet("{id:int}")]
public async Task<IActionResult> Redirect(int id)
{
var ad = AdsService.GetById(id) ?? throw new NotFoundException("广告不存在");
if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get<string>("ads" + id)))
{
HttpContext.Session.Set("ads" + id, id.ToString());
ad.ViewCount++;
await AdsService.SaveChangesAsync();
}

return RedirectPermanent(ad.Url);
}

/// <summary>
/// 获取文章分页
/// </summary>
/// <returns></returns>
[Authority]
public ActionResult GetPageData([Range(1, int.MaxValue, ErrorMessage = "页数必须大于0")]int page = 1, [Range(1, int.MaxValue, ErrorMessage = "页大小必须大于0")]int size = 10, string kw = "")
{
Expression<Func<Advertisement, bool>> where = p => true;
if (!string.IsNullOrEmpty(kw))
{
where = where.And(p => p.Title.Contains(kw) || p.Description.Contains(kw));
}

var query = AdsService.GetQuery(where);
var total = query.Count();
var list = query.OrderByDescending(p => p.Price).ThenByDescending(a => a.Weight).Skip((page - 1) * size).Take(size).ProjectTo<AdvertisementViewModel>(MapperConfig).ToList();
var pageCount = Math.Ceiling(total * 1.0 / size).ToInt32();
return PageResult(list, pageCount, total);
}

/// <summary>
/// 保存banner
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost, Authority]
public async Task<IActionResult> Save(AdvertisementInputDto model)
{
model.CategoryId = model.CategoryId?.Replace("null", "");
var entity = AdsService.GetById(model.Id);
if (entity != null)
{
Mapper.Map(model, entity);
bool b1 = await AdsService.SaveChangesAsync() > 0;
return ResultData(null, b1, b1 ? "修改成功" : "修改失败");
}

bool b = AdsService.AddEntitySaved(model.Mapper<Advertisement>()) != null;
return ResultData(null, b, b ? "添加成功" : "添加失败");
}

/// <summary>
/// 删除banner
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost("{id}"), HttpGet("{id}"), Authority]
public IActionResult Delete(int id)
{
bool b = AdsService.DeleteByIdSaved(id);
return ResultData(null, b, b ? "删除成功" : "删除失败");
}


/// <summary>
/// 禁用或开启文章评论
/// </summary>
/// <param name="id">文章id</param>
/// <returns></returns>
[Authority, HttpPost("{id}")]
public ActionResult ChangeState(int id)
{
var ad = AdsService.GetById(id);
if (ad != null)
{
ad.Status = ad.Status == Status.Available ? Status.Unavailable : Status.Available;
return ResultData(null, AdsService.SaveChanges() > 0, ad.Status == Status.Available ? $"【{ad.Title}】已上架!" : $"【{ad.Title}】已下架!");
}

return ResultData(null, false, "广告不存在");
}

}
}
4 changes: 3 additions & 1 deletion src/Masuit.MyBlogs.Core/Controllers/BaseController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public class BaseController : Controller
/// </summary>
public ILinksService LinksService { get; set; }

public IAdvertisementService AdsService { get; set; }

public UserInfoOutputDto CurrentUser => HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();

public IMapper Mapper { get; set; }
Expand Down Expand Up @@ -143,7 +145,7 @@ public override void OnActionExecuted(ActionExecutedContext filterContext)
ViewBag.menus = MenuService.GetQueryFromCache<MenuOutputDto>(m => m.Status == Status.Available).OrderBy(m => m.Sort).ToList(); //菜单
var model = new PageFootViewModel //页脚
{
Links = LinksService.GetQueryFromCache<LinksOutputDto>(l => l.Status == Status.Available).OrderBy(l => l.Recommend).ThenByDescending(l => l.Weight).ThenByDescending(l => new Random().Next()).Take(40).ToList()
Links = LinksService.GetQueryFromCache<LinksOutputDto>(l => l.Status == Status.Available).OrderByDescending(l => l.Recommend).ThenByDescending(l => l.Weight).ThenByDescending(l => new Random().Next()).Take(40).ToList()
};
ViewBag.Footer = model;

Expand Down
2 changes: 1 addition & 1 deletion src/Masuit.MyBlogs.Core/Controllers/DonateController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace Masuit.MyBlogs.Core.Controllers
{
/// <summary>
/// 捐赠管理
/// 打赏管理
/// </summary>
public class DonateController : AdminController
{
Expand Down
13 changes: 5 additions & 8 deletions src/Masuit.MyBlogs.Core/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,6 @@ public class HomeController : BaseController
/// </summary>
public IFastShareService FastShareService { get; set; }

/// <summary>
/// banner
/// </summary>
public IBannerService BannerService { get; set; }

/// <summary>
/// 首页
/// </summary>
Expand All @@ -54,7 +49,7 @@ public class HomeController : BaseController
public ActionResult Index()
{
ViewBag.Total = PostService.Count(p => p.Status == Status.Pended || CurrentUser.IsAdmin);
var banners = BannerService.GetAllFromCache().OrderBy(b => new Random().Next()).ToList();
var banners = AdsService.GetsByWeightedPrice(8, AdvertiseType.Banner).OrderBy(a => Guid.NewGuid()).ToList();
var fastShares = FastShareService.GetAllFromCache(s => s.Sort).ToList();
ViewBag.FastShare = fastShares;
var viewModel = GetIndexPageViewModel(1, 15, OrderBy.ModifyDate, CurrentUser);
Expand Down Expand Up @@ -171,7 +166,7 @@ public async Task<ActionResult> Category(int id, [Optional]OrderBy? orderBy, [Ra
/// <returns></returns>
private IndexPageViewModel GetIndexPageViewModel(int page, int size, OrderBy? orderBy, UserInfoOutputDto user)
{
IQueryable<PostOutputDto> postsQuery = PostService.GetQuery<PostOutputDto>(p => (p.Status == Status.Pended || user.IsAdmin)); //准备文章的查询
var postsQuery = PostService.GetQuery<PostOutputDto>(p => (p.Status == Status.Pended || user.IsAdmin)); //准备文章的查询
var notices = NoticeService.GetPagesFromCache<DateTime, NoticeOutputDto>(1, 5, out int _, n => (n.Status == Status.Display || user.IsAdmin), n => n.ModifyDate, false).ToList(); //加载前5条公告
var cats = CategoryService.GetQueryFromCache<string, CategoryOutputDto>(c => c.Status == Status.Available, c => c.Name).ToList(); //加载分类目录
var hotSearches = RedisHelper.Get<List<KeywordsRankOutputDto>>("SearchRank:Week").Take(10).ToList(); //热词统计
Expand Down Expand Up @@ -232,7 +227,9 @@ private IndexPageViewModel GetIndexPageViewModel(int page, int size, OrderBy? or
Posts = posts,
Tags = newdic,
Top6Post = hot6Post,
PostsQueryable = postsQuery
PostsQueryable = postsQuery,
SidebarAds = AdsService.GetsByWeightedPrice(2, AdvertiseType.SideBar),
ListAdvertisement = AdsService.GetByWeightedPrice(AdvertiseType.PostList)
};
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Masuit.MyBlogs.Core/Controllers/MiscController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class MiscController : BaseController
public IMiscService MiscService { get; set; }

/// <summary>
/// 捐赠
/// 打赏
/// </summary>
public IDonateService DonateService { get; set; }

Expand All @@ -47,7 +47,7 @@ public ActionResult Index(int id)
}

/// <summary>
/// 捐赠
/// 打赏
/// </summary>
/// <returns></returns>
[Route("donate")]
Expand All @@ -57,7 +57,7 @@ public ActionResult Donate()
}

/// <summary>
/// 捐赠列表
/// 打赏列表
/// </summary>
/// <param name="page"></param>
/// <param name="size"></param>
Expand Down
Loading

0 comments on commit 7714467

Please sign in to comment.