Esempio n. 1
0
 public SearchController(BlogContext db, ISearchProvider searchProvider, BlogUtil blogUtil, IOptions <AppSettingsModel> harmonySettings)
 {
     db_              = db;
     searchProvider_  = searchProvider;
     blogUtil_        = blogUtil;
     harmonySettings_ = harmonySettings.Value.HarmonySettings ?? new HarmonySettingsModel();
 }
Esempio n. 2
0
        /// <summary>
        /// Updates an existing published post.
        /// </summary>
        /// <returns>
        /// Absolute URL to the post.
        /// </returns>
        public async Task <IActionResult> OnPostUpdateAsync([FromBody] PageIM pageIM)
        {
            try
            {
                var page = new Blog.Models.Page
                {
                    Id         = pageIM.Id,
                    UserId     = Convert.ToInt32(userManager.GetUserId(HttpContext.User)),
                    ParentId   = pageIM.ParentId,
                    CreatedOn  = BlogUtil.GetCreatedOn(pageIM.PostDate),
                    Title      = pageIM.Title,
                    Body       = pageIM.Body,
                    BodyMark   = pageIM.BodyMark,
                    Excerpt    = pageIM.Excerpt,
                    Status     = EPostStatus.Published,
                    PageLayout = (byte)pageIM.PageLayout,
                };

                page = await pageService.UpdateAsync(page);

                return(new JsonResult(GetPostAbsoluteUrl(page)));
            }
            catch (FanException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a new <see cref="Tag"/>.
        /// </summary>
        /// <param name="tag">The tag with data to be created.</param>
        /// <exception cref="MokException">If tag is empty or title exists already.</exception>
        /// <returns>Created tag.</returns>
        public async Task <Tag> CreateAsync(Tag tag)
        {
            if (tag == null || tag.Title.IsNullOrEmpty())
            {
                throw new MokException($"Invalid tag to create.");
            }

            // prep title
            tag.Title = PrepareTitle(tag.Title);

            // make sure it is unique
            var allTags = await GetAllAsync();

            if (allTags.Any(t => t.Title.Equals(tag.Title, StringComparison.CurrentCultureIgnoreCase)))
            {
                throw new MokException($"'{tag.Title}' already exists.");
            }

            // prep slug, description and count
            tag.Slug        = BlogUtil.SlugifyTaxonomy(tag.Title, SLUG_MAXLEN, allTags.Select(c => c.Slug)); // slug is based on title
            tag.Description = Util.CleanHtml(tag.Description);
            tag.Count       = tag.Count;

            // create
            tag = await tagRepository.CreateAsync(tag);

            // remove cache
            await cache.RemoveAsync(BlogCache.KEY_ALL_TAGS);

            await cache.RemoveAsync(BlogCache.KEY_POSTS_INDEX);

            logger.LogDebug("Created {@Tag}", tag);
            return(tag);
        }
Esempio n. 4
0
 public ReplyController(
     IOptions <AppSettingsModel> appSettings,
     BlogContext db,
     UsersContext udb,
     AdminUtil adminUtil,
     BlogUtil blogUtil,
     ExpUtil expUtil,
     MessageUtil msgUtil,
     RatingUtil ratingUtil,
     IWebHostEnvironment env,
     IMemoryCache cache,
     ICompositeViewEngine viewEngine,
     IActionContextAccessor actionAccessor,
     HtmlSanitizerService sanitizerService)
 {
     _appSettings      = appSettings.Value;
     _db               = db;
     _udb              = udb;
     _adminUtil        = adminUtil;
     _blogUtil         = blogUtil;
     _cache            = cache;
     _env              = env;
     _expUtil          = expUtil;
     _ratingUtil       = ratingUtil;
     _msgUtil          = msgUtil;
     _viewEngine       = viewEngine;
     _actionAccessor   = actionAccessor;
     _sanitizerService = sanitizerService;
 }
Esempio n. 5
0
 public AccountController(
     IOptionsSnapshot <RegisterSettingsModel> registerSettings,
     BlogContext bdb,
     UsersContext udb,
     UserManager <UserProfile> userManager,
     SignInManager <UserProfile> signInManager,
     RoleManager <AspNetCore.Identity.EntityFramework6.IdentityRole> roleManager,
     IMemoryCache cache,
     ExpUtil expUtil,
     ImageUtil imgUtil,
     BlogUtil blogUtil,
     CategoryUtil catUtil,
     EmailSender emailSender)
 {
     _registerSettings = registerSettings.Value ?? new RegisterSettingsModel();
     _db            = udb;
     _bdb           = bdb;
     _userManager   = userManager;
     _signInManager = signInManager;
     _roleManager   = roleManager;
     _expUtil       = expUtil;
     _imgUtil       = imgUtil;
     _blogUtil      = blogUtil;
     _catUtil       = catUtil;
     _cache         = cache;
     _emailSender   = emailSender;
 }
Esempio n. 6
0
        public void SlugifyTaxonomy_trucates_long_slug_and_keeps_only_24_chars()
        {
            var expected = "this-is-a-really-long-ca";
            var actual   = BlogUtil.SlugifyTaxonomy("this is a really long category title", CategoryService.SLUG_MAXLEN);

            Assert.Equal(expected, actual);
        }
Esempio n. 7
0
        public void SlugifyTaxonomy_replaces_hashtag_with_letter_s()
        {
            var expected = "cs";
            var actual   = BlogUtil.SlugifyTaxonomy("c#", CategoryService.SLUG_MAXLEN);

            Assert.Equal(expected, actual);
        }
Esempio n. 8
0
        /// <summary>
        /// Preview
        /// </summary>
        /// <param name="postIM"></param>
        /// <returns></returns>
        public async Task <JsonResult> OnPostPreviewAsync([FromBody] BlogPostIM postIM)
        {
            // prep blog post
            List <Tag> tags = new List <Tag>();

            foreach (var title in postIM.Tags) // titles
            {
                tags.Add(await _tagSvc.GetByTitleAsync(title));
            }

            var blogPost = new BlogPost
            {
                User      = await _userManager.GetUserAsync(HttpContext.User),
                UserId    = Convert.ToInt32(_userManager.GetUserId(HttpContext.User)),
                Category  = await _catSvc.GetAsync(postIM.CategoryId),
                CreatedOn = BlogUtil.GetCreatedOn(postIM.PostDate),
                Tags      = tags,
                Slug      = postIM.Slug.IsNullOrEmpty() ? "untitled" : postIM.Slug,
                Excerpt   = postIM.Excerpt,
                Title     = postIM.Title.IsNullOrEmpty() ? "Untitled" : postIM.Title,
                Body      = postIM.Body,
            };

            // prep TempData
            var prevRelLink = BlogRoutes.GetPostPreviewRelativeLink(blogPost.CreatedOn, blogPost.Slug);

            TempData.Put(prevRelLink, blogPost);

            // return preview url
            return(new JsonResult($"{Request.Scheme}://{Request.Host}{prevRelLink}"));
        }
Esempio n. 9
0
 public BlogController(
     IOptions <AppSettingsModel> appSettings,
     IOptionsSnapshot <DataSettingsModel> dataSettings,
     BlogContext db,
     UsersContext udb,
     AdminUtil adminUtil,
     BlogUtil blogUtil,
     CategoryUtil catUtil,
     MessageUtil msgUtil,
     TagUtil tagUtil,
     UserManager <UserProfile> userManager,
     UploadUtil uploadUtil,
     RatingUtil ratingUtil,
     IRecommendationProvider recommendationProvider,
     CacheService cacheService,
     IMemoryCache cache)
 {
     _db                     = db;
     _udb                    = udb;
     _adminUtil              = adminUtil;
     _catUtil                = catUtil;
     _blogUtil               = blogUtil;
     _msgUtil                = msgUtil;
     _appSettings            = appSettings.Value;
     _dataSettings           = dataSettings.Value;
     _userManager            = userManager;
     _cache                  = cache;
     _uploadUtil             = uploadUtil;
     _tagUtil                = tagUtil;
     _ratingUtil             = ratingUtil;
     _recommendationProvider = recommendationProvider;
     _cacheService           = cacheService;
 }
Esempio n. 10
0
        /// <summary>
        /// Ajax POST to publish a post.
        /// </summary>
        /// <returns>
        /// Absolute URL to the post.
        /// </returns>
        /// <remarks>
        /// The post could be new or previously published.
        /// </remarks>
        public async Task <JsonResult> OnPostPublishAsync([FromBody] BlogPostIM postIM)
        {
            var blogPost = new BlogPost
            {
                UserId     = Convert.ToInt32(_userManager.GetUserId(HttpContext.User)),
                CategoryId = postIM.CategoryId,
                CreatedOn  = BlogUtil.GetCreatedOn(postIM.PostDate),
                TagTitles  = postIM.Tags,
                Slug       = postIM.Slug,
                Excerpt    = postIM.Excerpt,
                Title      = postIM.Title,
                Body       = postIM.Body,
                Status     = EPostStatus.Published,
            };

            if (postIM.Id <= 0)
            {
                blogPost = await _blogSvc.CreateAsync(blogPost);
            }
            else
            {
                blogPost.Id = postIM.Id;
                blogPost    = await _blogSvc.UpdateAsync(blogPost);
            }

            return(new JsonResult(GetPostAbsoluteUrl(blogPost)));
        }
Esempio n. 11
0
 public RankingSidebar(BlogContext db, BlogUtil blogUtil, IMemoryCache cache, IVisitCounter visitCounter, IOptions <AppSettingsModel> appsetting)
 {
     _db            = db;
     _blogUtil      = blogUtil;
     _cache         = cache;
     _visitCounter  = visitCounter;
     _cacheInterval = TimeSpan.FromMinutes(appsetting.Value.UpdateInterval > 0 ? appsetting.Value.UpdateInterval : 10);
 }
Esempio n. 12
0
 public static BlogOption OverrideOption(this BlogOption self, BlogUtil util)
 {
     self.LockTags  = self.LockTags && util.CheckAdmin(true); // Admin and writer
     self.NoRate    = self.NoRate && util.CheckAdmin();       // Only admin
     self.NoComment = self.NoComment && util.CheckAdmin();    // Only admin
     self.NoApprove = self.NoApprove && util.CheckAdmin();
     return(self);
 }
Esempio n. 13
0
 public RankingController(
     BlogContext db,
     BlogUtil blogUtil,
     IMemoryCache cache)
 {
     _db = db;
     _blogUtil = blogUtil;
     _cache = cache;
 }
Esempio n. 14
0
 public EditTagModel(BlogUtil util, BlogContext db, int id, string author, IEnumerable <int> BlackListTags)
 {
     BlogID          = id;
     Author          = author;
     TagsInBlog      = db.TagsInBlogs.Include("tag").Where(tib => tib.BlogID == id);
     TagHistories    = db.TagHistories.Where(th => th.BlogID == id);
     NickNames       = util.GetNickNames(TagsInBlog.Select(tib => tib.AddBy).Where(b => b != null));
     BlackListTagIDs = BlackListTags;
 }
Esempio n. 15
0
        public async Task <JsonResult> Login([FromServices] BlogUtil util, [FromBody] LoginModel model)
        {
            if (util.CheckCaptchaError(model.Captcha, ""))
            {
                ModelState.AddModelError("Captcha", "验证码计算错误,请重试。");
            }
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.UserName);

                if (user != null)
                {
                    if (await _userManager.IsInRoleAsync(user, "Banned"))
                    {
                        return(Json(new
                        {
                            success = false,
                            errors = new[] { "此账户已被封禁,如有疑问请联系管理员邮箱。" },
                        }));
                    }
                    var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false);

                    if (result.Succeeded)
                    {
                        user.LastLoginDate = DateTime.Now;
                        user.LastLoginIP   = ExpUtil.GetIPAddress(HttpContext);
                        await _userManager.UpdateAsync(user);

                        return(Json(new { success = true }));
                    }
                    if (result.IsLockedOut)
                    {
                        return(Json(new
                        {
                            success = false,
                            errors = new[] { "此账户由于登陆尝试次数过多已被暂时锁定,请稍后再试。" },
                        }));
                    }
                    else if (result.RequiresTwoFactor)
                    {
                        return(Json(new
                        {
                            success = true,
                            require2fa = true,
                        }));
                    }
                }
                // 如果我们进行到这一步时某个地方出代楷则重新显示表单
                ModelState.AddModelError("", "提供的用户名或密码不正确");
            }

            return(Json(new {
                success = false,
                errors = ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToList()
            }));
        }
Esempio n. 16
0
        /// <summary>
        /// Saves a page as draft.
        /// </summary>
        /// <returns>
        /// The updated <see cref="BlogPost"/>.
        /// </returns>
        /// <remarks>
        /// This is called by either Auto Save or user clicking on Save.
        /// </remarks>
        public async Task <IActionResult> OnPostSaveAsync([FromBody] PageIM pageIM)
        {
            try
            {
                // get page
                var page = new Blog.Models.Page
                {
                    UserId     = Convert.ToInt32(userManager.GetUserId(HttpContext.User)),
                    ParentId   = pageIM.ParentId,
                    CreatedOn  = BlogUtil.GetCreatedOn(pageIM.PostDate),
                    Title      = pageIM.Title,
                    Body       = pageIM.Body,
                    BodyMark   = pageIM.BodyMark,
                    Excerpt    = pageIM.Excerpt,
                    Status     = EPostStatus.Draft,
                    PageLayout = (byte)pageIM.PageLayout,
                };

                // create or update page
                if (pageIM.Id <= 0)
                {
                    page = await pageService.CreateAsync(page);
                }
                else
                {
                    page.Id = pageIM.Id;
                    page    = await pageService.UpdateAsync(page);
                }

                // return page
                var coreSettings = await settingService.GetSettingsAsync <CoreSettings>();

                pageIM = new PageIM
                {
                    Id         = page.Id,
                    Title      = page.Title,
                    BodyMark   = page.BodyMark,
                    Excerpt    = page.Excerpt,
                    PostDate   = page.CreatedOn.ToString(DATE_FORMAT),
                    ParentId   = page.ParentId,
                    Published  = page.Status == EPostStatus.Published,
                    IsDraft    = page.Status == EPostStatus.Draft,
                    DraftDate  = page.UpdatedOn.HasValue ? page.UpdatedOn.Value.ToDisplayString(coreSettings.TimeZoneId) : "",
                    PageLayout = (EPageLayout)page.PageLayout,
                };

                return(new JsonResult(pageIM));
            }
            catch (FanException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 17
0
 public ReplyController(
     BlogContext db,
     AdminUtil adminUtil,
     BlogUtil blogUtil,
     RatingUtil ratingUtil,
     HtmlSanitizerService sanitizerService)
 {
     _db               = db;
     _adminUtil        = adminUtil;
     _blogUtil         = blogUtil;
     _ratingUtil       = ratingUtil;
     _sanitizerService = sanitizerService;
 }
Esempio n. 18
0
 public MessageController(
     IOptions <AppSettingsModel> appSettings,
     BlogContext db,
     UsersContext udb,
     BlogUtil blogUtil,
     MessageUtil msgUtil,
     IMemoryCache cache)
 {
     _db          = db;
     _udb         = udb;
     _blogUtil    = blogUtil;
     _msgUtil     = msgUtil;
     _appSettings = appSettings.Value;
     _cache       = cache;
 }
Esempio n. 19
0
 public static BlogOption MergeWith(this BlogOption self, BlogUtil util, BlogOption modified)
 {
     if (modified == null)
     {
         return(self);
     }
     if (util.CheckAdmin(true))
     {
         self.LockTags = modified.LockTags;
     }
     if (util.CheckAdmin())
     {
         self.NoRate    = modified.NoRate;
         self.NoApprove = modified.NoApprove;
     }
     self.LockDesc = modified.LockDesc;
     return(self);
 }
Esempio n. 20
0
        /// <summary>
        /// Ajax POST to save a post as draft.
        /// </summary>
        /// <returns>
        /// The updated <see cref="BlogPost"/>.
        /// </returns>
        /// <remarks>
        /// This is called by either auto save or user clicking on Save.
        /// </remarks>
        public async Task <JsonResult> OnPostSaveAsync([FromBody] BlogPostIM postIM)
        {
            var blogPost = new BlogPost
            {
                UserId     = Convert.ToInt32(_userManager.GetUserId(HttpContext.User)),
                CategoryId = postIM.CategoryId,
                CreatedOn  = BlogUtil.GetCreatedOn(postIM.PostDate),
                TagTitles  = postIM.Tags,
                Slug       = postIM.Slug,
                Excerpt    = postIM.Excerpt,
                Title      = postIM.Title,
                Body       = postIM.Body,
                Status     = EPostStatus.Draft,
            };

            if (postIM.Id <= 0)
            {
                blogPost = await _blogSvc.CreateAsync(blogPost);
            }
            else
            {
                blogPost.Id = postIM.Id;
                blogPost    = await _blogSvc.UpdateAsync(blogPost);
            }

            var coreSettings = await _settingSvc.GetSettingsAsync <CoreSettings>();

            var postVM = new BlogPostIM
            {
                Id         = blogPost.Id,
                Title      = blogPost.Title,
                Body       = blogPost.Body,
                PostDate   = blogPost.CreatedOn.ToString(DATE_FORMAT),
                Slug       = blogPost.Slug,
                Excerpt    = blogPost.Excerpt,
                CategoryId = blogPost.CategoryId ?? 1,
                Tags       = blogPost.TagTitles,
                Published  = blogPost.Status == EPostStatus.Published,
                IsDraft    = blogPost.Status == EPostStatus.Draft,
                DraftDate  = blogPost.UpdatedOn.HasValue ? blogPost.UpdatedOn.Value.ToDisplayString(coreSettings.TimeZoneId) : "",
            };

            return(new JsonResult(postVM));
        }
Esempio n. 21
0
 public BlogController(
     IOptions <AppSettingsModel> appSettings,
     BlogContext db,
     UsersContext udb,
     CategoryUtil catUtil,
     BlogUtil blogUtil,
     RatingUtil ratingUtil,
     DbBlogSearchProvider dbBlogSearchProvider,
     INickNameProvider nickNameProvider)
 {
     db_                   = db;
     udb_                  = udb;
     blogUtil_             = blogUtil;
     ratingUtil_           = ratingUtil;
     appSettings_          = appSettings.Value;
     dbBlogSearchProvider_ = dbBlogSearchProvider;
     nickNameProvider_     = nickNameProvider;
     categoryUtil_         = catUtil;
 }
Esempio n. 22
0
        private void Setup_Item(JGN_Blogs blg)
        {
            blg.files = new List <FileEntity>();

            if (blg.cover_url == null)
            {
                blg.cover_url = "";
            }

            if (blg.picture_url == null)
            {
                blg.picture_url = "";
            }

            if (blg.cover_url != "")
            {
                blg.cover_url = BlogUtil.Return_Blog_Cover(blg.cover_url);
            }

            if (blg.picture_url != "")
            {
                var _pics = blg.picture_url.Split(char.Parse(","));
                foreach (var pic in _pics)
                {
                    string imgUrl = BlogUtil.Return_Blog_Image(pic, Jugnoon.Blogs.Configs.BlogSettings.default_path);

                    blg.files.Add(new FileEntity()
                    {
                        filename = pic,
                        img_url  = imgUrl
                    });
                }
            }
            if (blg.created_at == null)
            {
                blg.created_at = DateTime.Now;
            }
            blg.url        = BlogUrlConfig.Generate_Post_Url(blg);
            blg.author_url = UserUrlConfig.ProfileUrl(blg.author, Jugnoon.Settings.Configs.RegistrationSettings.uniqueFieldOption);
            // process content
            blg.description = UtilityBLL.Process_Content_Text(blg.description);
        }
Esempio n. 23
0
        /// <summary>
        /// Updates an existing <see cref="Category"/>.
        /// </summary>
        /// <param name="category">The category with data to be updated.</param>
        /// <exception cref="MokException">If category is invalid or title exists.</exception>
        /// <returns>Updated category.</returns>
        public async Task <Category> UpdateAsync(Category category)
        {
            if (category == null || category.Id <= 0 || category.Title.IsNullOrEmpty())
            {
                throw new MokException($"Invalid category to update.");
            }

            // prep title
            category.Title = PrepareTitle(category.Title);

            // make sure it is unique
            var allCats = await GetAllAsync();

            allCats.RemoveAll(c => c.Id == category.Id); // remove selft
            if (allCats.Any(c => c.Title.Equals(category.Title, StringComparison.CurrentCultureIgnoreCase)))
            {
                throw new MokException($"'{category.Title}' already exists.");
            }

            // prep slug, description and count
            var entity = await categoryRepository.GetAsync(category.Id);

            entity.Title       = category.Title;                                                                     // assign new title
            entity.Slug        = BlogUtil.SlugifyTaxonomy(category.Title, SLUG_MAXLEN, allCats.Select(c => c.Slug)); // slug is based on title
            entity.Description = Util.CleanHtml(category.Description);
            entity.Count       = category.Count;

            // update
            await categoryRepository.UpdateAsync(category);

            // remove cache
            await cache.RemoveAsync(BlogCache.KEY_ALL_CATS);

            await cache.RemoveAsync(BlogCache.KEY_POSTS_INDEX);

            // raise nav updated event
            await mediator.Publish(new NavUpdated { Id = category.Id, Type = ENavType.BlogCategory });

            // return entity
            logger.LogDebug("Updated {@Category}", entity);
            return(entity);
        }
Esempio n. 24
0
 public ReplyController(
     IOptions <AppSettingsModel> appSettings,
     BlogContext db,
     UsersContext udb,
     AdminUtil adminUtil,
     BlogUtil blogUtil,
     ExpUtil expUtil,
     MessageUtil msgUtil,
     RatingUtil ratingUtil,
     HtmlSanitizerService sanitizerService)
 {
     _appSettings      = appSettings.Value;
     _db               = db;
     _udb              = udb;
     _adminUtil        = adminUtil;
     _blogUtil         = blogUtil;
     _expUtil          = expUtil;
     _ratingUtil       = ratingUtil;
     _msgUtil          = msgUtil;
     _sanitizerService = sanitizerService;
 }
Esempio n. 25
0
 public AuditController(
     IOptions <AppSettingsModel> appSettings,
     IOptionsSnapshot <DataSettingsModel> dataSettings,
     BlogContext db,
     UsersContext udb,
     AdminUtil adminUtil,
     BlogUtil blogUtil,
     MessageUtil msgUtil,
     UserManager <UserProfile> userManager,
     IMemoryCache cache)
 {
     _db           = db;
     _udb          = udb;
     _adminUtil    = adminUtil;
     _blogUtil     = blogUtil;
     _msgUtil      = msgUtil;
     _appSettings  = appSettings.Value;
     _dataSettings = dataSettings.Value;
     _userManager  = userManager;
     _cache        = cache;
 }
Esempio n. 26
0
        /// <summary>
        /// Updates an existing <see cref="Tag"/>.
        /// </summary>
        /// <param name="tag">The tag with data to be updated.</param>
        /// <exception cref="FanException">If tag is invalid or title exists already.</exception>
        /// <returns>Updated tag.</returns>
        public async Task <Tag> UpdateAsync(Tag tag)
        {
            if (tag == null || tag.Id <= 0 || tag.Title.IsNullOrEmpty())
            {
                throw new FanException($"Invalid tag to update.");
            }

            // prep title
            tag.Title = PrepareTitle(tag.Title);

            // make sure it is unique
            var allTags = await GetAllAsync();

            allTags.RemoveAll(t => t.Id == tag.Id); // remove self
            if (allTags.Any(t => t.Title.Equals(tag.Title, StringComparison.CurrentCultureIgnoreCase)))
            {
                throw new FanException($"'{tag.Title}' already exists.");
            }

            // prep slug, description and count
            var entity = await _tagRepo.GetAsync(tag.Id);

            entity.Title       = tag.Title;                                                                     // assign new title
            entity.Slug        = BlogUtil.SlugifyTaxonomy(tag.Title, SLUG_MAXLEN, allTags.Select(c => c.Slug)); // slug is based on title
            entity.Description = Util.CleanHtml(tag.Description);
            entity.Count       = tag.Count;

            // update
            await _tagRepo.UpdateAsync(entity);

            // remove cache
            await _cache.RemoveAsync(BlogCache.KEY_ALL_TAGS);

            await _cache.RemoveAsync(BlogCache.KEY_POSTS_INDEX);

            // return entity
            _logger.LogDebug("Updated {@Tag}", entity);
            return(entity);
        }
Esempio n. 27
0
        /// <summary>
        /// Creates a new <see cref="Category"/>.
        /// </summary>
        /// <param name="category">The category with data to be created.</param>
        /// <exception cref="MokException">If title is empty or exists already.</exception>
        /// <returns>Created category.</returns>
        public async Task <Category> CreateAsync(string title, string description = null)
        {
            if (title.IsNullOrEmpty())
            {
                throw new MokException($"Category title cannot be empty.");
            }

            // prep title
            title = PrepareTitle(title);

            // make sure unique
            var allCats = await GetAllAsync();

            if (allCats.Any(t => t.Title.Equals(title, StringComparison.CurrentCultureIgnoreCase)))
            {
                throw new MokException($"'{title}' already exists.");
            }

            // prep slug, desc and count
            var category = new Category
            {
                Title       = title,
                Slug        = BlogUtil.SlugifyTaxonomy(title, SLUG_MAXLEN, allCats.Select(c => c.Slug)),
                Description = Util.CleanHtml(description),
                Count       = 0,
            };

            // create
            category = await categoryRepository.CreateAsync(category);

            // remove cache
            await cache.RemoveAsync(BlogCache.KEY_ALL_CATS);

            await cache.RemoveAsync(BlogCache.KEY_POSTS_INDEX);

            logger.LogDebug("Created {@Category}", category);
            return(category);
        }
Esempio n. 28
0
 public HomeController(
     IOptions <AppSettingsModel> appSettings,
     IOptionsSnapshot <DataSettingsModel> dataSettings,
     BlogContext db,
     UsersContext udb,
     AdminUtil adminUtil,
     BlogUtil blogUtil,
     CategoryUtil catUtil,
     ExpUtil expUtil,
     MessageUtil msgUtil,
     TagUtil tagUtil,
     UserManager <UserProfile> userManager,
     UploadUtil uploadUtil,
     RatingUtil ratingUtil,
     CacheService cacheService,
     IMemoryCache cache,
     IWebHostEnvironment env,
     ISearchProvider searchProvider)
 {
     _db             = db;
     _udb            = udb;
     _adminUtil      = adminUtil;
     _catUtil        = catUtil;
     _blogUtil       = blogUtil;
     _expUtil        = expUtil;
     _msgUtil        = msgUtil;
     _appSettings    = appSettings.Value;
     _dataSettings   = dataSettings.Value;
     _userManager    = userManager;
     _cache          = cache;
     _uploadUtil     = uploadUtil;
     _tagUtil        = tagUtil;
     _ratingUtil     = ratingUtil;
     _cacheService   = cacheService;
     _env            = env;
     _searchProvider = searchProvider;
 }
Esempio n. 29
0
        public void SlugifyTaxonomy_produces_8chars_string_when_input_is_non_english()
        {
            var actual = BlogUtil.SlugifyTaxonomy("你好", CategoryService.SLUG_MAXLEN);

            Assert.True(actual.Length == 6);
        }
Esempio n. 30
0
 public void SlugifyTaxonomy_returns_unique_slug_by_append_counter_to_duplicate(string input, string expected, IEnumerable <string> existing = null)
 {
     Assert.Equal(expected, BlogUtil.SlugifyTaxonomy(input, CategoryService.SLUG_MAXLEN, existing));
 }