Forráskód Böngészése

增加模板变量功能

懒得勤快 4 éve
szülő
commit
df68269ada

+ 26 - 0
src/Masuit.MyBlogs.Core/Controllers/BaseController.cs

@@ -10,12 +10,14 @@ using Masuit.MyBlogs.Core.Models.ViewModel;
 using Masuit.Tools;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Security;
+using Masuit.Tools.Strings;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.Filters;
 using System;
 using System.Linq;
 using System.Net;
+using System.Text.RegularExpressions;
 
 namespace Masuit.MyBlogs.Core.Controllers
 {
@@ -41,6 +43,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         public ILinksService LinksService { get; set; }
 
         public IAdvertisementService AdsService { get; set; }
+        public IVariablesService VariablesService { get; set; }
 
         public UserInfoDto CurrentUser => HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
 
@@ -79,6 +82,29 @@ namespace Masuit.MyBlogs.Core.Controllers
             });
         }
 
+        protected string ReplaceVariables(string text)
+        {
+            if (string.IsNullOrEmpty(text))
+            {
+                return text;
+            }
+
+            var keys = Regex.Matches(text, @"\{\{\w+\}\}").Select(m => m.Value).Join(",");
+            if (!string.IsNullOrEmpty(keys))
+            {
+                var dic = VariablesService.GetQueryFromCache(v => keys.Contains(v.Key)).ToDictionary(v => v.Key, v => v.Value);
+                var template = Template.Create(text);
+                foreach (var (key, value) in dic)
+                {
+                    template.Set(key, value);
+                }
+
+                return template.Render();
+            }
+
+            return text;
+        }
+
         /// <summary>在调用操作方法前调用。</summary>
         /// <param name="filterContext">有关当前请求和操作的信息。</param>
         public override void OnActionExecuting(ActionExecutingContext filterContext)

+ 1 - 0
src/Masuit.MyBlogs.Core/Controllers/MiscController.cs

@@ -46,6 +46,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             var misc = await MiscService.GetFromCacheAsync(m => m.Id == id) ?? throw new NotFoundException("页面未找到");
             misc.ModifyDate = misc.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
             misc.PostDate = misc.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
+            misc.Content = ReplaceVariables(misc.Content);
             return View(misc);
         }
 

+ 3 - 0
src/Masuit.MyBlogs.Core/Controllers/NoticeController.cs

@@ -47,6 +47,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 n.ModifyDate = n.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
                 n.PostDate = n.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
+                n.Content = ReplaceVariables(n.Content);
             }
 
             ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.PostList);
@@ -71,6 +72,7 @@ namespace Masuit.MyBlogs.Core.Controllers
 
             notice.ModifyDate = notice.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
             notice.PostDate = notice.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
+            notice.Content = ReplaceVariables(notice.Content);
             ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage);
             return View(notice);
         }
@@ -160,6 +162,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 notice.ModifyDate = notice.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
                 notice.PostDate = notice.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
+                notice.Content = ReplaceVariables(notice.Content);
             }
 
             return ResultData(notice);

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

@@ -48,6 +48,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         public IPostHistoryVersionService PostHistoryVersionService { get; set; }
         public IInternalMessageService MessageService { get; set; }
         public IPostMergeRequestService PostMergeRequestService { get; set; }
+
         public IWebHostEnvironment HostEnvironment { get; set; }
         public ISearchEngine<DataContext> SearchEngine { get; set; }
         public ImagebedClient ImagebedClient { get; set; }
@@ -84,6 +85,8 @@ namespace Masuit.MyBlogs.Core.Controllers
             ViewBag.Related = related;
             post.ModifyDate = post.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
             post.PostDate = post.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
+            post.Content = ReplaceVariables(post.Content);
+            post.ProtectContent = ReplaceVariables(post.ProtectContent);
             if (CurrentUser.IsAdmin)
             {
                 return View("Details_Admin", post);
@@ -181,6 +184,8 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             var post = await PostHistoryVersionService.GetAsync(v => v.Id == hid && (v.Post.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到");
             CheckPermission(post.Post);
+            post.Content = ReplaceVariables(post.Content);
+            post.ProtectContent = ReplaceVariables(post.ProtectContent);
             var next = await PostHistoryVersionService.GetAsync(p => p.PostId == id && p.ModifyDate > post.ModifyDate, p => p.ModifyDate);
             var prev = await PostHistoryVersionService.GetAsync(p => p.PostId == id && p.ModifyDate < post.ModifyDate, p => p.ModifyDate, false);
             ViewBag.Next = next;
@@ -207,8 +212,8 @@ namespace Masuit.MyBlogs.Core.Controllers
             main.Id = id;
             var diff = new HtmlDiff.HtmlDiff(right.Content, left.Content);
             var diffOutput = diff.Build();
-            right.Content = Regex.Replace(Regex.Replace(diffOutput, "<ins.+?</ins>", string.Empty), @"<\w+></\w+>", string.Empty);
-            left.Content = Regex.Replace(Regex.Replace(diffOutput, "<del.+?</del>", string.Empty), @"<\w+></\w+>", string.Empty);
+            right.Content = ReplaceVariables(Regex.Replace(Regex.Replace(diffOutput, "<ins.+?</ins>", string.Empty), @"<\w+></\w+>", string.Empty));
+            left.Content = ReplaceVariables(Regex.Replace(Regex.Replace(diffOutput, "<del.+?</del>", string.Empty), @"<\w+></\w+>", string.Empty));
             ViewBag.Ads = AdsService.GetsByWeightedPrice(2, AdvertiseType.InPage, main.CategoryId);
             ViewBag.DisableCopy = post.DisableCopy;
             return View(new[] { main, left, right });

+ 34 - 0
src/Masuit.MyBlogs.Core/Controllers/ValuesController.cs

@@ -0,0 +1,34 @@
+using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
+using Masuit.MyBlogs.Core.Models.Entity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+using System.Threading.Tasks;
+
+namespace Masuit.MyBlogs.Core.Controllers
+{
+    [Route("values")]
+    public class ValuesController : AdminController
+    {
+        public IVariablesService VariablesService { get; set; }
+
+        [HttpGet("list")]
+        public async Task<ActionResult> GetAll()
+        {
+            return ResultData(await VariablesService.GetAll().ToListAsync());
+        }
+
+        [HttpPost]
+        public async Task<ActionResult> Save(Variables model)
+        {
+            var b = await VariablesService.AddOrUpdateSavedAsync(v => v.Key, model) > 0;
+            return ResultData(null, b, b ? "保存成功" : "保存失败");
+        }
+
+        [HttpPost("{id:int}")]
+        public ActionResult Delete(int id)
+        {
+            var b = VariablesService - id;
+            return ResultData(null, b, b ? "删除成功" : "保存失败");
+        }
+    }
+}

+ 1 - 4
src/Masuit.MyBlogs.Core/Infrastructure/DataContext.cs

@@ -63,10 +63,6 @@ namespace Masuit.MyBlogs.Core.Infrastructure
                     entry.OriginalValues.SetValues(databaseValues);
                     entry.CurrentValues.SetValues(resolvedValues);
                 }
-                catch
-                {
-                    throw;
-                }
             }
 
             throw ex;
@@ -94,5 +90,6 @@ namespace Masuit.MyBlogs.Core.Infrastructure
 
         public virtual DbSet<PostMergeRequest> PostMergeRequests { get; set; }
         public virtual DbSet<Advertisement> Advertisements { get; set; }
+        public virtual DbSet<Variables> Variables { get; set; }
     }
 }

+ 1 - 0
src/Masuit.MyBlogs.Core/Infrastructure/Repository/Interface/IBaseRepository.cs

@@ -652,4 +652,5 @@ namespace Masuit.MyBlogs.Core.Infrastructure.Repository.Interface
     public partial interface ISeminarPostHistoryVersionRepository : IBaseRepository<SeminarPostHistoryVersion> { }
     public partial interface IPostMergeRequestRepository : IBaseRepository<PostMergeRequest> { }
     public partial interface IAdvertisementRepository : IBaseRepository<Advertisement> { }
+    public partial interface IVariablesRepository : IBaseRepository<Variables> { }
 }

+ 13 - 0
src/Masuit.MyBlogs.Core/Infrastructure/Repository/Repositories.cs

@@ -267,4 +267,17 @@ namespace Masuit.MyBlogs.Core.Infrastructure.Repository
             return t;
         }
     }
+    public partial class VariablesRepository : BaseRepository<Variables>, IVariablesRepository
+    {
+        /// <summary>
+        /// 添加实体
+        /// </summary>
+        /// <param name="t">需要添加的实体</param>
+        /// <returns>添加成功</returns>
+        public override Variables AddEntity(Variables t)
+        {
+            DataContext.Add(t);
+            return t;
+        }
+    }
 }

+ 1 - 1
src/Masuit.MyBlogs.Core/Infrastructure/Services/Interface/IServices.cs

@@ -25,5 +25,5 @@ namespace Masuit.MyBlogs.Core.Infrastructure.Services.Interface
     public partial interface ISeminarPostService : IBaseService<SeminarPost> { }
     public partial interface ISeminarPostHistoryVersionService : IBaseService<SeminarPostHistoryVersion> { }
     public partial interface IPostMergeRequestService : IBaseService<PostMergeRequest> { }
-
+    public partial interface IVariablesService : IBaseService<Variables> { }
 }

+ 6 - 0
src/Masuit.MyBlogs.Core/Infrastructure/Services/Services.cs

@@ -94,4 +94,10 @@ namespace Masuit.MyBlogs.Core.Infrastructure.Services
         {
         }
     }
+    public partial class VariablesService : BaseService<Variables>, IVariablesService
+    {
+        public VariablesService(IBaseRepository<Variables> repository, ISearchEngine<DataContext> searchEngine, ILuceneIndexSearcher searcher) : base(repository, searchEngine, searcher)
+        {
+        }
+    }
 }

+ 15 - 0
src/Masuit.MyBlogs.Core/Models/Entity/Variables.cs

@@ -0,0 +1,15 @@
+using Masuit.LuceneEFCore.SearchEngine;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace Masuit.MyBlogs.Core.Models.Entity
+{
+    [Table("Variables")]
+    public class Variables : LuceneIndexableBaseEntity
+    {
+        [Required(ErrorMessage = "变量名不能为空"), RegularExpression("[a-zA-Z]+", ErrorMessage = "变量名不规范")]
+        public string Key { get; set; }
+        [Required(ErrorMessage = "变量值不能为空")]
+        public string Value { get; set; }
+    }
+}

+ 14 - 0
src/Masuit.MyBlogs.Core/wwwroot/ng-views/app/route.config.js

@@ -435,6 +435,20 @@ myApp.config([
                     }
                 ]
             }
+        }).state("values", {
+            url: "/values",
+            templateUrl: vpath + "/values.html",
+            controller: "values as list",
+            resolve: {
+                deps: ["$ocLazyLoad", function($ocLazyLoad) {
+                        return $ocLazyLoad.load([
+                        {
+                            files: ["https://apps.bdimg.com/libs/ueditor/1.4.3.1/ueditor.all.js"],
+                            cache: true
+                        }, cpath + "/values.js"]);
+                    }
+                ]
+            }
         }).state("loginrecord", {
             url: "/loginrecord",
             templateUrl: vpath + "/loginrecord.html",

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 0 - 0
src/Masuit.MyBlogs.Core/wwwroot/ng-views/app/route.config.min.js


+ 59 - 0
src/Masuit.MyBlogs.Core/wwwroot/ng-views/controllers/values.js

@@ -0,0 +1,59 @@
+myApp.controller("values", ["$scope", "$http", "NgTableParams", function ($scope, $http, NgTableParams) {
+	UEDITOR_CONFIG.autoHeightEnabled=false;
+	window.hub.stop();
+	var self = this;
+	self.data = {};
+	this.load = function() {
+		$http.get("/values/list").then(function(res) {
+			self.tableParams = new NgTableParams({}, {
+				filterDelay: 0,
+				dataset:res.data.Data
+			});
+		});
+	}
+	self.load();
+	$scope.closeAll = function() {
+		layer.closeAll();
+		setTimeout(function() {
+			$("#modal").css("display", "none");
+		}, 500);
+	}
+	$scope.submit = function (values) {
+			$scope.request("/values", values, function (data) {
+				swal(data.Message, null, 'info');
+				$scope.values = {};
+				$scope.closeAll();
+				self.load();
+			});
+	}
+	self.edit = function (row) {
+		layer.open({
+			type: 1,
+			zIndex: 20,
+			title: '修改变量',
+			area: (window.screen.width > 800 ? 800 : window.screen.width) + 'px',
+			content: $("#modal"),
+			success: function(layero, index) {
+				$scope.values = row;
+			},
+			end: function() {
+				$("#modal").css("display", "none");
+			}
+		});
+	}
+	self.add = function() {
+		layer.open({
+			type: 1,
+			zIndex: 20,
+			title: '添加变量',
+			area: (window.screen.width > 800 ? 800 : window.screen.width) + 'px',
+			content: $("#modal"),
+			success: function(layero, index) {
+				$scope.values = {};
+			},
+			end: function() {
+				$("#modal").css("display", "none");
+			}
+		});
+	}
+}]);

+ 1 - 0
src/Masuit.MyBlogs.Core/wwwroot/ng-views/template/sidebar-left.html

@@ -88,6 +88,7 @@
                 <li><a data-ui-sref-active="active" data-ui-sref="links" data-ng-click="mactrl.sidebarStat($event)">友情链接管理</a></li>
                 <li><a data-ui-sref-active="active" data-ui-sref="email" data-ng-click="mactrl.sidebarStat($event)">邮件模版</a></li>
                 <li><a data-ui-sref-active="active" data-ui-sref="sendbox" data-ng-click="mactrl.sidebarStat($event)">邮件发送记录</a></li>
+                <li><a data-ui-sref-active="active" data-ui-sref="values" data-ng-click="mactrl.sidebarStat($event)">模板变量</a></li>
             </ul>
         </li>
         <li data-ui-sref-active="active">

+ 51 - 0
src/Masuit.MyBlogs.Core/wwwroot/ng-views/views/values.html

@@ -0,0 +1,51 @@
+<div>
+    <div class="btn-group">
+        <button class="btn btn-default waves-effect" ng-click="list.add()">
+            <span class="glyphicon glyphicon-plus"></span>
+        </button>
+        <button class="btn btn-info waves-effect" ng-click="list.load()">
+            <span class="glyphicon glyphicon-refresh"></span>
+        </button>
+    </div>
+    <table ng-table="list.tableParams" class="table table-bordered table-hover table-condensed" ng-form="list.tableForm" disable-filter="list.isAdding" tracked-table="list.tableTracker">
+        <tr ng-repeat="row in $data" ng-form="rowForm" tracked-table-row="row">
+            <td title="'变量名'" sortable="'Key'">
+                {{row.Key}}
+            </td>
+            <td title="'变量值'">
+                <div style="max-height: 200px;overflow-y: auto" ng-bind-html="row.Value|htmlString"></div>
+            </td>
+            <td title="'操作'">
+                <div class="btn-group">
+                    <button class="btn btn-success btn-sm waves-effect" ng-click="list.edit(row)">修改</button>
+                </div>
+            </td>
+        </tr>
+    </table>
+</div>
+
+<div id="modal" class="modal">
+    <div class="container-fluid" style="margin: 15px 0;">
+        <form class="bgm-white">
+            <div class="input-group">
+                <span class="input-group-addon">
+                    变量名:
+                </span>
+                <div class="fg-line">
+                    <input type="text" class="form-control" ng-model="values.Key" />
+                </div>
+            </div>
+            <div class="input-group">
+                <span class="input-group-addon">
+                    变量值:
+                </span>
+                <!--<div class="ueditor max-height400" ng-model="values.Value" type="text/plain"></div>-->
+                <div style="height: 300px;" class="ueditor" ng-model="values.Value" type="text/plain"></div>
+            </div>
+            <div class="btn-group">
+                <button type="button" class="btn btn-info waves-effect" ng-click="submit(values)">确认</button>
+                <button type="button" class="btn btn-danger waves-effect" ng-click="closeAll()">取消</button>
+            </div>
+        </form>
+    </div>
+</div>

Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott