cn.hutool.http.HtmlUtil Java Examples

The following examples show how to use cn.hutool.http.HtmlUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PostServiceImpl.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 批量更新文章摘要
 *
 * @param postSummary postSummary
 */
@Override
@CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public void updateAllSummary(Integer postSummary) {
    final List<Post> posts = this.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
    for (Post post : posts) {
        String text = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
        if (text.length() > postSummary) {
            post.setPostSummary(text.substring(0, postSummary));
        } else {
            post.setPostSummary(text);
        }
        postRepository.save(post);
    }
}
 
Example #2
Source File: UtilTest.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws UnsupportedEncodingException {
	String rs = "Webhook \u7684 payload POST \u65f6\u5fc5\u987b\u662f JSON \u5b57\u7b26\u4e32";
	System.out.println(EscapeUtil.unescapeHtml4(rs));
	System.out.println(HtmlUtil.escape("测试"));
	String s = "%5B%7B%22format%22:%22%22,%22fieldName%22:%22a.username%22,%22attrType%22:%22String%22,%22fieldNode%22:%22%22,%22operate%22:%22like%22,%22weight%22:0,%22value%22:%22%E5%86%9C%E4%BF%A1%22,%22endValue%22:%22%22%7D%5D";
	System.out.println(EscapeUtil.unescape(s));
	System.out.println(URLDecoder.decode(s, "utf-8"));
	System.out.println(Json.toJSONString("utf-8".split(StringUtil.SPLIT_DEFAULT)));
}
 
Example #3
Source File: PostServiceImpl.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 批量更新文章摘要
 *
 * @param postSummary postSummary
 */
@Override
@CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public void updateAllSummary(Integer postSummary) {
    List<Post> posts = this.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
    for (Post post : posts) {
        String text = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
        if (text.length() > postSummary) {
            post.setPostSummary(text.substring(0, postSummary));
        } else {
            post.setPostSummary(text);
        }
        postRepository.save(post);
    }
}
 
Example #4
Source File: ScriptController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "save.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String save(ScriptModel scriptModel, String type) {
    if (scriptModel == null) {
        return JsonMessage.getString(405, "没有数据");
    }
    if (StrUtil.isEmpty(scriptModel.getContext())) {
        return JsonMessage.getString(405, "内容为空");
    }
    //
    scriptModel.setContext(HtmlUtil.unescape(scriptModel.getContext()));
    ScriptModel eModel = scriptServer.getItem(scriptModel.getId());
    if ("add".equalsIgnoreCase(type)) {
        if (eModel != null) {
            return JsonMessage.getString(405, "id已经存在啦");
        }
        scriptModel.setId(IdUtil.fastSimpleUUID());
        File file = scriptModel.getFile(true);
        if (file.exists() || file.isDirectory()) {
            return JsonMessage.getString(405, "当地id路径文件已经存在来,请修改");
        }
        scriptServer.addItem(scriptModel);
        return JsonMessage.getString(200, "添加成功");
    }
    if (eModel == null) {
        return JsonMessage.getString(405, "对应数据不存在");
    }
    eModel.setName(scriptModel.getName());
    eModel.setContext(scriptModel.getContext());
    scriptServer.updateItem(eModel);
    return JsonMessage.getString(200, "修改成功");
}
 
Example #5
Source File: TagHttpServletRequestWrapper.java    From v-mock with MIT License 5 votes vote down vote up
@Override
public String[] getParameterValues(String name) {
    String[] values = super.getParameterValues(name);
    if (values != null) {
        int length = values.length;
        String[] escapseValues = new String[length];
        for (int i = 0; i < length; i++) {
            // 防xss攻击和过滤前后空格
            escapseValues[i] = HtmlUtil.escape(values[i]).trim();
        }
        return escapseValues;
    }
    return super.getParameterValues(name);
}
 
Example #6
Source File: PostController.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 更新
 *
 * @param post     post
 * @param cateList 分类目录
 * @param tagList  标签
 * @param session  session
 * @return JsonResult
 */
@PostMapping(value = "/update")
@ResponseBody
public JsonResult update(@ModelAttribute Post post,
                         @RequestParam("cateList") List<String> cateList,
                         @RequestParam("tagList") String tagList) {
    //old data
    final Post oldPost = postService.findByPostId(post.getPostId()).orElse(new Post());
    post.setPostUpdate(new Date());
    post.setPostViews(oldPost.getPostViews());
    post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd()));
    post.setUser(oldPost.getUser());
    if (null == post.getPostDate()) {
        post.setPostDate(new Date());
    }
    //摘要字数
    int postSummary = 50;
    if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
        postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
    }
    //设置文章摘要
    final String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
    if (summaryText.length() > postSummary) {
        final String summary = summaryText.substring(0, postSummary);
        post.setPostSummary(summary);
    } else {
        post.setPostSummary(summaryText);
    }
    post = postService.buildCategoriesAndTags(post, cateList, tagList);
    //当没有选择文章缩略图的时候,自动分配一张内置的缩略图
    if (StrUtil.equals(post.getPostThumbnail(), BlogPropertiesEnum.DEFAULT_THUMBNAIL.getProp())) {
        post.setPostThumbnail("/static/halo-frontend/images/thumbnail/thumbnail-" + RandomUtil.randomInt(1, 10) + ".jpg");
    }
    post = postService.save(post);
    if (null != post) {
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.update-success"));
    } else {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.update-failed"));
    }
}
 
Example #7
Source File: FrontIndexController.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 搜索文章
 *
 * @param keyword keyword
 * @param model   model
 * @return 模板路径/themes/{theme}/index
 */
@GetMapping(value = "/search")
public String search(
        @RequestParam(value = "size", defaultValue = "15") Integer pageSize,
        @RequestParam(value = "sort", defaultValue = "createTime") String sort,
        @RequestParam(value = "order", defaultValue = "desc") String order,
        @RequestParam("keyword") String keyword,
        Model model) {
    return this.searchPage(model, 1, pageSize, sort, order, HtmlUtil.escape(keyword));
}
 
Example #8
Source File: PostServiceImpl.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Async
public void updateAllSummary(Integer postSummary) {
    Map<String, Object> map = new HashMap<>();
    map.put("post_type", PostTypeEnum.POST_TYPE_POST.getValue());
    List<Post> posts = postMapper.selectByMap(map);
    for (Post post : posts) {
        String text = HtmlUtil.cleanHtmlTag(post.getPostContent());
        if (text.length() > postSummary) {
            postMapper.updatePostSummary(post.getId(), text.substring(0, postSummary));
        } else {
            postMapper.updatePostSummary(post.getId(), text);
        }
    }
}
 
Example #9
Source File: FrontIndexController.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 搜索文章
 *
 * @param userName userName
 * @param model    model
 * @return 模板路径/themes/{theme}/index
 */
@GetMapping(value = "/author/{userName}")
public String postsByUserName(Model model,
                              @PathVariable(value = "userName") String userName,
                              @RequestParam(value = "size", defaultValue = "15") Integer pageSize,
                              @RequestParam(value = "sort", defaultValue = "createTime") String sort,
                              @RequestParam(value = "order", defaultValue = "desc") String order) {

    return this.postsByUserName(model, HtmlUtil.escape(userName), 1, pageSize, sort, order);
}
 
Example #10
Source File: DocumentBrowser.java    From book118-downloader with MIT License 4 votes vote down vote up
/**
 * 获取文档的预览地址
 *
 * @param documentId 文档的编号
 * @return 预览地址
 */
private PdfInfo getPdfInfo(String documentId) {
    String url = Constants.OPEN_FULL_URL + documentId;
    String pdfPageUrlStr = HttpUtil.get(url);

    if (StrUtil.isNotBlank(pdfPageUrlStr)) {
        pdfPageUrlStr = "https:" + pdfPageUrlStr;
    } else {
        StaticLog.error("获取失败!");
        return null;
    }

    int endOfHost = pdfPageUrlStr.indexOf("?");
    String viewHost = pdfPageUrlStr.substring(0, endOfHost);
    String redirectPage = HttpUtil.get(pdfPageUrlStr);
    String href = ReUtil.get(Constants.HREF_PATTERN, redirectPage, 1);
    String fullUrl;
    if(href != null){
        fullUrl = viewHost.substring(0, viewHost.length()-1) + HtmlUtil.unescape(href);
    }else {
        fullUrl = pdfPageUrlStr;
    }


    String pdfPageHtml = HttpUtil.get(fullUrl);
    if (pdfPageHtml.contains(Constants.FILE_NOT_EXIST)) {
        StaticLog.error("获取预览地址失败,请稍后再试!");
        return null;
    }

    List<String> result = ReUtil.findAllGroup0(Constants.INPUT_PATTERN, pdfPageHtml);
    Map<String, String> pdfInfoMap = new HashMap<>(6);
    pdfInfoMap.put("host", viewHost);
    for (String inputStr : result) {
        String id = ReUtil.get(Constants.ID_PATTERN, inputStr, 1);
        String value = ReUtil.get(Constants.VALUE_PATTERN, inputStr, 1);
        if (StrUtil.isNotBlank(id) && StrUtil.isNotBlank(value)) {
            id = id.toLowerCase();
            try {
                value = URLEncoder.encode(value, "utf8");
            } catch (Exception e) {
                StaticLog.error("URLEncoder Error", e);
            }
            pdfInfoMap.put(id, value);
        }
    }
    return BeanUtil.mapToBean(pdfInfoMap, PdfInfo.class, true);
}
 
Example #11
Source File: CommentController.java    From SENS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 管理员回复评论,并通过评论
 *
 * @param commentId      被回复的评论
 * @param commentContent 回复的内容
 * @return 重定向到/admin/comment
 */
@PostMapping(value = "/reply")
@ResponseBody
@SystemLog(description = "回复评论", type = LogTypeEnum.OPERATION)
public JsonResult replyComment(@RequestParam("id") Long commentId,
                               @RequestParam("commentContent") String commentContent,
                               @RequestParam("userAgent") String userAgent,
                               HttpServletRequest request) {
    //博主信息
    User loginUser = getLoginUser();
    //被回复的评论
    Comment lastComment = commentService.get(commentId);
    if (lastComment == null) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.comment-not-exist"));
    }

    Post post = postService.get(lastComment.getPostId());
    if (post == null) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.post-not-exist"));
    }
    //修改被回复的评论的状态
    if (Objects.equals(lastComment.getCommentStatus(), CommentStatusEnum.CHECKING.getCode())) {
        lastComment.setCommentStatus(CommentStatusEnum.PUBLISHED.getCode());
        commentService.insertOrUpdate(lastComment);
    }

    //保存评论
    Comment comment = new Comment();
    comment.setUserId(loginUser.getId());
    comment.setPostId(lastComment.getPostId());
    comment.setCommentAuthor(loginUser.getUserDisplayName());
    comment.setCommentAuthorEmail(loginUser.getUserEmail());
    comment.setCommentAuthorUrl(SensConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()));
    comment.setCommentAuthorIp(ServletUtil.getClientIP(request));
    comment.setCommentAuthorAvatar(loginUser.getUserAvatar());
    String lastContent = "<a href='#comment-id-" + lastComment.getId() + "'>@" + lastComment.getCommentAuthor() + "</a> ";
    comment.setCommentContent(lastContent + OwoUtil.markToImg(HtmlUtil.escape(commentContent)));
    comment.setCommentAgent(userAgent);
    comment.setCommentParent(commentId);
    comment.setCommentStatus(CommentStatusEnum.PUBLISHED.getCode());
    //判断是否是博主
    if (Objects.equals(loginUser.getId(), post.getUserId())) {
        comment.setIsAdmin(1);
    } else {
        comment.setIsAdmin(0);
    }
    comment.setAcceptUserId(lastComment.getUserId());
    comment.setPathTrace(lastComment.getPathTrace() + lastComment.getId() + "/");
    commentService.insertOrUpdate(comment);
    //邮件通知
    new EmailToAuthor(comment, lastComment, post, loginUser, commentContent).start();
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.reply-success"));

}
 
Example #12
Source File: FrontCommentController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * 提交新评论
 *
 * @param comment comment实体
 * @param post    post实体
 * @param request request
 * @return JsonResult
 */
@PostMapping(value = "/newComment")
@ResponseBody
public JsonResult newComment(@Valid @ModelAttribute("comment") Comment comment,
                             BindingResult result,
                             @ModelAttribute("post") Post post,
                             HttpServletRequest request) {
    if (result.hasErrors()) {
        for (ObjectError error : result.getAllErrors()) {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), error.getDefaultMessage());
        }
    }
    try {
        Comment lastComment = null;
        post = postService.findByPostId(post.getPostId()).get();
        comment.setCommentAuthorEmail(HtmlUtil.escape(comment.getCommentAuthorEmail()).toLowerCase());
        comment.setPost(post);
        comment.setCommentDate(DateUtil.date());
        comment.setCommentAuthorIp(ServletUtil.getClientIP(request));
        comment.setIsAdmin(0);
        comment.setCommentAuthor(HtmlUtil.escape(comment.getCommentAuthor()));
        if (StrUtil.isNotBlank(comment.getCommentAuthorEmail())) {
            comment.setCommentAuthorAvatarMd5(SecureUtil.md5(comment.getCommentAuthorEmail()));
        }
        if (comment.getCommentParent() > 0) {
            lastComment = commentService.findCommentById(comment.getCommentParent()).get();
            StrBuilder buildContent = new StrBuilder("<a href='#comment-id-");
            buildContent.append(lastComment.getCommentId());
            buildContent.append("'>@");
            buildContent.append(lastComment.getCommentAuthor());
            buildContent.append("</a> ");
            buildContent.append(OwoUtil.markToImg(HtmlUtil.escape(comment.getCommentContent()).replace("&lt;br/&gt;", "<br/>")));
            comment.setCommentContent(buildContent.toString());
        } else {
            //将评论内容的字符专为安全字符
            comment.setCommentContent(OwoUtil.markToImg(HtmlUtil.escape(comment.getCommentContent()).replace("&lt;br/&gt;", "<br/>")));
        }
        if (StrUtil.isNotEmpty(comment.getCommentAuthorUrl())) {
            comment.setCommentAuthorUrl(URLUtil.formatUrl(comment.getCommentAuthorUrl()));
        }
        commentService.save(comment);
        if (comment.getCommentParent() > 0) {
            new EmailToParent(comment, lastComment, post).start();
            new EmailToAdmin(comment, post).start();
        } else {
            new EmailToAdmin(comment, post).start();
        }
        if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NEED_CHECK.getProp()), TrueFalseEnum.TRUE.getDesc()) || HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NEED_CHECK.getProp()) == null) {
            return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), "你的评论已经提交,待博主审核之后可显示。");
        } else {
            return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), "你的评论已经提交,刷新后即可显示。");
        }
    } catch (Exception e) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), "评论失败!");
    }
}
 
Example #13
Source File: AdminController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * Markdown 导入
 *
 * @param file    file
 * @param request request
 * @return JsonResult
 */
@PostMapping(value = "/tools/markdownImport")
@ResponseBody
public JsonResult markdownImport(@RequestParam("file") MultipartFile file,
                                 HttpServletRequest request,
                                 HttpSession session) throws IOException {
    User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
    String markdown = IoUtil.read(file.getInputStream(), "UTF-8");
    String content = MarkdownUtils.renderMarkdown(markdown);
    Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown);
    Post post = new Post();
    List<String> elementValue = null;
    List<Tag> tags = new ArrayList<>();
    List<Category> categories = new ArrayList<>();
    Tag tag = null;
    Category category = null;
    if (frontMatters.size() > 0) {
        for (String key : frontMatters.keySet()) {
            elementValue = frontMatters.get(key);
            for (String ele : elementValue) {
                if ("title".equals(key)) {
                    post.setPostTitle(ele);
                } else if ("date".equals(key)) {
                    post.setPostDate(DateUtil.parse(ele));
                } else if ("updated".equals(key)) {
                    post.setPostUpdate(DateUtil.parse(ele));
                } else if ("tags".equals(key)) {
                    tag = tagService.findTagByTagName(ele);
                    if (null == tag) {
                        tag = new Tag();
                        tag.setTagName(ele);
                        tag.setTagUrl(ele);
                        tag = tagService.save(tag);
                    }
                    tags.add(tag);
                } else if ("categories".equals(key)) {
                    category = categoryService.findByCateName(ele);
                    if (null == category) {
                        category = new Category();
                        category.setCateName(ele);
                        category.setCateUrl(ele);
                        category.setCateDesc(ele);
                        category = categoryService.save(category);
                    }
                    categories.add(category);
                }
            }
        }
    } else {
        post.setPostDate(new Date());
        post.setPostUpdate(new Date());
        post.setPostTitle(file.getOriginalFilename());
    }
    post.setPostContentMd(markdown);
    post.setPostContent(content);
    post.setPostType(PostTypeEnum.POST_TYPE_POST.getDesc());
    post.setAllowComment(AllowCommentEnum.ALLOW.getCode());
    post.setUser(user);
    post.setTags(tags);
    post.setCategories(categories);
    post.setPostUrl(StrUtil.removeSuffix(file.getOriginalFilename(), ".md"));
    int postSummary = 50;
    if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
        postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
    }
    String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
    if (summaryText.length() > postSummary) {
        String summary = summaryText.substring(0, postSummary);
        post.setPostSummary(summary);
    } else {
        post.setPostSummary(summaryText);
    }
    if (null == post.getPostDate()) {
        post.setPostDate(new Date());
    }
    if (null == post.getPostUpdate()) {
        post.setPostUpdate(new Date());
    }
    postService.save(post);
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode());
}
 
Example #14
Source File: AdminController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * 验证登录信息
 *
 * @param loginName 登录名:邮箱/用户名
 * @param loginPwd  loginPwd 密码
 * @param session   session session
 * @return JsonResult JsonResult
 */
@PostMapping(value = "/getLogin")
@ResponseBody
public JsonResult getLogin(@ModelAttribute("loginName") String loginName,
                           @ModelAttribute("loginPwd") String loginPwd,
                           HttpSession session) {
    //已注册账号,单用户,只有一个
    User aUser = userService.findUser();
    //首先判断是否已经被禁用已经是否已经过了10分钟
    Date loginLast = DateUtil.date();
    if (null != aUser.getLoginLast()) {
        loginLast = aUser.getLoginLast();
    }
    Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
    if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled"));
    }
    //验证用户名和密码
    User user = null;
    if (Validator.isEmail(loginName)) {
        user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd));
    } else {
        user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd));
    }
    userService.updateUserLoginLast(DateUtil.date());
    //判断User对象是否相等
    if (ObjectUtil.equal(aUser, user)) {
        session.setAttribute(HaloConst.USER_SESSION_KEY, aUser);
        //重置用户的登录状态为正常
        userService.updateUserNormal();
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request);
        log.info("User {} login succeeded.", aUser.getUserDisplayName());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success"));
    } else {
        //更新失败次数
        Integer errorCount = userService.updateUserLoginError();
        //超过五次禁用账户
        if (errorCount >= CommonParamsEnum.FIVE.getValue()) {
            userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
        }
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
        Object[] args = {(5 - errorCount)};
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
    }
}
 
Example #15
Source File: CommentController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * 管理员回复评论
 *
 * @param commentId      被回复的评论
 * @param commentContent 回复的内容
 * @return JsonResult
 */
@PostMapping(value = "/reply")
@ResponseBody
public JsonResult replyComment(@RequestParam("commentId") Long commentId,
                               @RequestParam("postId") Long postId,
                               @RequestParam("commentContent") String commentContent,
                               @RequestParam("userAgent") String userAgent,
                               HttpServletRequest request,
                               HttpSession session) {
    try {
        Post post = postService.findByPostId(postId).orElse(new Post());

        //博主信息
        User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);

        //被回复的评论
        Comment lastComment = commentService.findCommentById(commentId).orElse(new Comment());

        //修改被回复的评论的状态
        lastComment.setCommentStatus(CommentStatusEnum.PUBLISHED.getCode());
        commentService.save(lastComment);

        //保存评论
        Comment comment = new Comment();
        comment.setPost(post);
        comment.setCommentAuthor(user.getUserDisplayName());
        comment.setCommentAuthorEmail(user.getUserEmail());
        comment.setCommentAuthorUrl(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()));
        comment.setCommentAuthorIp(ServletUtil.getClientIP(request));
        comment.setCommentAuthorAvatarMd5(SecureUtil.md5(user.getUserEmail()));
        comment.setCommentDate(DateUtil.date());

        StrBuilder buildContent = new StrBuilder("<a href='#comment-id-");
        buildContent.append(lastComment.getCommentId());
        buildContent.append("'>@");
        buildContent.append(lastComment.getCommentAuthor());
        buildContent.append("</a> ");
        buildContent.append(OwoUtil.markToImg(HtmlUtil.escape(commentContent).replace("&lt;br/&gt;", "<br/>")));

        comment.setCommentContent(buildContent.toString());
        comment.setCommentAgent(userAgent);
        comment.setCommentParent(commentId);
        comment.setCommentStatus(CommentStatusEnum.PUBLISHED.getCode());
        comment.setIsAdmin(1);
        commentService.save(comment);

        //邮件通知
        new EmailToAuthor(comment, lastComment, post, user, commentContent).start();
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode());
    } catch (Exception e) {
        log.error("Reply to comment failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode());
    }
}
 
Example #16
Source File: PostController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * 更新
 *
 * @param post     post
 * @param cateList 分类目录
 * @param tagList  标签
 * @param session  session
 * @return JsonResult
 */
@PostMapping(value = "/update")
@ResponseBody
public JsonResult update(@ModelAttribute Post post,
                         @RequestParam("cateList") List<String> cateList,
                         @RequestParam("tagList") String tagList) {
    //old data
    Post oldPost = postService.findByPostId(post.getPostId()).orElse(new Post());
    post.setPostUpdate(new Date());
    post.setPostViews(oldPost.getPostViews());
    post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd()));
    post.setUser(oldPost.getUser());
    if (null == post.getPostDate()) {
        post.setPostDate(new Date());
    }
    //摘要字数
    int postSummary = 50;
    if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
        postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
    }
    //设置文章摘要
    String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
    if (summaryText.length() > postSummary) {
        String summary = summaryText.substring(0, postSummary);
        post.setPostSummary(summary);
    } else {
        post.setPostSummary(summaryText);
    }
    post = postService.buildCategoriesAndTags(post, cateList, tagList);
    //当没有选择文章缩略图的时候,自动分配一张内置的缩略图
    if (StrUtil.equals(post.getPostThumbnail(), BlogPropertiesEnum.DEFAULT_THUMBNAIL.getProp())) {
        post.setPostThumbnail("/static/halo-frontend/images/thumbnail/thumbnail-" + RandomUtil.randomInt(1, 10) + ".jpg");
    }

    post = postService.save(post);
    if (null != post) {
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.update-success"));
    } else {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.update-failed"));
    }
}
 
Example #17
Source File: PostController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * 添加文章
 *
 * @param post     post
 * @param cateList 分类列表
 * @param tagList  标签
 * @param session  session
 */
@PostMapping(value = "/save")
@ResponseBody
public JsonResult save(@ModelAttribute Post post,
                       @RequestParam("cateList") List<String> cateList,
                       @RequestParam("tagList") String tagList,
                       HttpSession session) {
    User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
    try {
        post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd()));
        //摘要字数
        int postSummary = 80;
        if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
            postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
        }
        //设置文章摘要
        String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
        if (summaryText.length() > postSummary) {
            String summary = summaryText.substring(0, postSummary);
            post.setPostSummary(summary);
        } else {
            post.setPostSummary(summaryText);
        }
        post.setPostDate(DateUtil.date());
        post.setPostUpdate(DateUtil.date());
        post.setUser(user);

        post = postService.buildCategoriesAndTags(post, cateList, tagList);
        post.setPostUrl(urlFilter(post.getPostUrl()));
        //当没有选择文章缩略图的时候,自动分配一张内置的缩略图
        if (StrUtil.equals(post.getPostThumbnail(), BlogPropertiesEnum.DEFAULT_THUMBNAIL.getProp())) {
            post.setPostThumbnail("/static/halo-frontend/images/thumbnail/thumbnail-" + RandomUtil.randomInt(1, 10) + ".jpg");
        }
        postService.save(post);
        logsService.save(LogsRecord.PUSH_POST, post.getPostTitle(), request);
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.save-success"));
    } catch (Exception e) {
        log.error("Save article failed: {}", e.getMessage());
        e.printStackTrace();
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.save-failed"));
    }
}
 
Example #18
Source File: PostController.java    From stone with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 添加文章
 *
 * @param post     post
 * @param cateList 分类列表
 * @param tagList  标签
 * @param session  session
 */
@PostMapping(value = "/save")
@ResponseBody
public JsonResult save(@ModelAttribute Post post,
                       @RequestParam("cateList") List<String> cateList,
                       @RequestParam("tagList") String tagList,
                       HttpSession session) {
    final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
    try {
        post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd()));
        //摘要字数
        int postSummary = 50;
        if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
            postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
        }
        //设置文章摘要
        final String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
        if (summaryText.length() > postSummary) {
            final String summary = summaryText.substring(0, postSummary);
            post.setPostSummary(summary);
        } else {
            post.setPostSummary(summaryText);
        }
        post.setPostDate(DateUtil.date());
        post.setPostUpdate(DateUtil.date());
        post.setUser(user);

        post = postService.buildCategoriesAndTags(post, cateList, tagList);
        post.setPostUrl(urlFilter(post.getPostUrl()));
        //当没有选择文章缩略图的时候,自动分配一张内置的缩略图
        if (StrUtil.equals(post.getPostThumbnail(), BlogPropertiesEnum.DEFAULT_THUMBNAIL.getProp())) {
            post.setPostThumbnail("/static/halo-frontend/images/thumbnail/thumbnail-" + RandomUtil.randomInt(1, 10) + ".jpg");
        }
        postService.save(post);
        logsService.save(LogsRecord.PUSH_POST, post.getPostTitle(), request);
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.save-success"));
    } catch (Exception e) {
        log.error("Save article failed: {}", e.getMessage());
        e.printStackTrace();
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.save-failed"));
    }
}
 
Example #19
Source File: PostController.java    From SENS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 添加/更新文章
 *
 * @param post    Post实体
 * @param cateIds 分类列表
 * @param tagList 标签列表
 */
@PostMapping(value = "/save")
@ResponseBody
@SystemLog(description = "保存文章", type = LogTypeEnum.OPERATION)
public JsonResult pushPost(@ModelAttribute Post post,
                           @RequestParam("cateList") List<Long> cateIds,
                           @RequestParam("tagList") String tagList) {

    checkCategoryAndTag(cateIds, tagList);
    User user = getLoginUser();
    Boolean isAdmin = loginUserIsAdmin();
    //1、如果开启了文章审核,非管理员文章默认状态为审核
    Boolean isOpenCheck = StringUtils.equals(SensConst.OPTIONS.get(BlogPropertiesEnum.OPEN_POST_CHECK.getProp()), TrueFalseEnum.TRUE.getValue());
    if (isOpenCheck && !isAdmin) {
        post.setPostStatus(PostStatusEnum.CHECKING.getCode());
    }
    post.setUserId(getLoginUserId());

    //2、非管理员只能修改自己的文章,管理员都可以修改
    Post originPost = null;
    if (post.getId() != null) {
        originPost = postService.get(post.getId());
        if (!Objects.equals(originPost.getUserId(), user.getId()) && !isAdmin) {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.permission-denied"));
        }
        //以下属性不能修改
        post.setUserId(originPost.getUserId());
        post.setPostViews(originPost.getPostViews());
        post.setCommentSize(originPost.getCommentSize());
        post.setPostLikes(originPost.getPostLikes());
        post.setCommentSize(originPost.getCommentSize());
        post.setDelFlag(originPost.getDelFlag());
    }
    //3、提取摘要
    int postSummary = 100;
    if (StringUtils.isNotEmpty(SensConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
        postSummary = Integer.parseInt(SensConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
    }
    //文章摘要
    String summaryText = HtmlUtil.cleanHtmlTag(post.getPostContent());
    if (summaryText.length() > postSummary) {
        String summary = summaryText.substring(0, postSummary);
        post.setPostSummary(summary);
    } else {
        post.setPostSummary(summaryText);
    }

    //4、分类标签
    List<Category> categories = categoryService.cateIdsToCateList(cateIds, user.getId());
    post.setCategories(categories);
    if (StringUtils.isNotEmpty(tagList)) {
        List<Tag> tags = tagService.strListToTagList(user.getId(), StringUtils.deleteWhitespace(tagList));
        post.setTags(tags);
    }
    //当没有选择文章缩略图的时候,自动分配一张内置的缩略图
    if (StringUtils.equals(post.getPostThumbnail(), BlogPropertiesEnum.DEFAULT_THUMBNAIL.getProp())) {
        String staticUrl = SensConst.OPTIONS.get(BlogPropertiesEnum.BLOG_STATIC_URL.getProp());
        if (!Strings.isNullOrEmpty(staticUrl)) {
            post.setPostThumbnail(staticUrl + "/static/images/thumbnail/img_" + RandomUtil.randomInt(0, 14) + ".jpg");
        } else {
            post.setPostThumbnail("/static/images/thumbnail/img_" + RandomUtil.randomInt(0, 14) + ".jpg");
        }
    }
    post.setPostType(PostTypeEnum.POST_TYPE_POST.getValue());
    postService.insertOrUpdate(post);
    if (isOpenCheck && !isAdmin) {
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), "文章已提交审核");
    }
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.operation-success"));
}
 
Example #20
Source File: FrontCommentController.java    From stone with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 提交新评论
 *
 * @param comment comment实体
 * @param post    post实体
 * @param request request
 *
 * @return JsonResult
 */
@PostMapping(value = "/newComment")
@ResponseBody
public JsonResult newComment(@Valid @ModelAttribute("comment") Comment comment,
                             BindingResult result,
                             @ModelAttribute("post") Post post,
                             HttpServletRequest request) {
    if (result.hasErrors()) {
        for (ObjectError error : result.getAllErrors()) {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), error.getDefaultMessage());
        }
    }
    try {
        Comment lastComment = null;
        post = postService.findByPostId(post.getPostId()).orElse(new Post());
        comment.setCommentAuthorEmail(HtmlUtil.escape(comment.getCommentAuthorEmail()).toLowerCase());
        comment.setPost(post);
        comment.setCommentDate(DateUtil.date());
        comment.setCommentAuthorIp(ServletUtil.getClientIP(request));
        comment.setIsAdmin(0);
        comment.setCommentAuthor(HtmlUtil.escape(comment.getCommentAuthor()));
        if (StrUtil.isNotBlank(comment.getCommentAuthorEmail())) {
            comment.setCommentAuthorAvatarMd5(SecureUtil.md5(comment.getCommentAuthorEmail()));
        }
        comment.setCommentContentText(comment.getCommentContent());
        if (comment.getCommentParent() > 0) {
            lastComment = commentService.findCommentById(comment.getCommentParent()).orElse(new Comment());
            final StrBuilder buildContent = new StrBuilder("<a href='#comment-id-");
            buildContent.append(lastComment.getCommentId());
            buildContent.append("'>@");
            buildContent.append(lastComment.getCommentAuthor());
            buildContent.append("</a> ");
            buildContent.append(OwoUtil.markToImg(HtmlUtil.escape(comment.getCommentContent()).replace("&lt;br/&gt;", "<br/>")));
            comment.setCommentContent(buildContent.toString());
        } else {
            //将评论内容的字符专为安全字符
            comment.setCommentContent(OwoUtil.markToImg(HtmlUtil.escape(comment.getCommentContent()).replace("&lt;br/&gt;", "<br/>")));
        }
        if (StrUtil.isNotEmpty(comment.getCommentAuthorUrl())) {
            comment.setCommentAuthorUrl(URLUtil.formatUrl(comment.getCommentAuthorUrl()));
        }
        commentService.save(comment);
        if (comment.getCommentParent() > 0) {
            new EmailToParent(comment, lastComment, post).start();
            new EmailToAdmin(comment, post).start();
        } else {
            new EmailToAdmin(comment, post).start();
        }
        if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NEED_CHECK.getProp()), TrueFalseEnum.TRUE.getDesc()) || HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NEED_CHECK.getProp()) == null) {
            return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), "你的评论已经提交,待博主审核之后可显示。");
        } else {
            return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), "你的评论已经提交,刷新后即可显示。");
        }
    } catch (Exception e) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), "评论失败!");
    }
}
 
Example #21
Source File: AdminController.java    From stone with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Markdown 导入
 *
 * @param file    file
 * @param request request
 *
 * @return JsonResult
 */
@PostMapping(value = "/tools/markdownImport")
@ResponseBody
public JsonResult markdownImport(@RequestParam("file") MultipartFile file,
                                 HttpServletRequest request,
                                 HttpSession session) throws IOException {
    final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
    final String markdown = IoUtil.read(file.getInputStream(), "UTF-8");
    final String content = MarkdownUtils.renderMarkdown(markdown);
    final Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown);
    final Post post = new Post();
    List<String> elementValue = null;
    final List<Tag> tags = new ArrayList<>();
    final List<Category> categories = new ArrayList<>();
    Tag tag = null;
    Category category = null;
    if (frontMatters.size() > 0) {
        for (String key : frontMatters.keySet()) {
            elementValue = frontMatters.get(key);
            for (String ele : elementValue) {
                if ("title".equals(key)) {
                    post.setPostTitle(ele);
                } else if ("date".equals(key)) {
                    post.setPostDate(DateUtil.parse(ele));
                } else if ("updated".equals(key)) {
                    post.setPostUpdate(DateUtil.parse(ele));
                } else if ("tags".equals(key)) {
                    tag = tagService.findTagByTagName(ele);
                    if (null == tag) {
                        tag = new Tag();
                        tag.setTagName(ele);
                        tag.setTagUrl(ele);
                        tag = tagService.save(tag);
                    }
                    tags.add(tag);
                } else if ("categories".equals(key)) {
                    category = categoryService.findByCateName(ele);
                    if (null == category) {
                        category = new Category();
                        category.setCateName(ele);
                        category.setCateUrl(ele);
                        category.setCateDesc(ele);
                        category = categoryService.save(category);
                    }
                    categories.add(category);
                }
            }
        }
    } else {
        post.setPostDate(new Date());
        post.setPostUpdate(new Date());
        post.setPostTitle(file.getOriginalFilename());
    }
    post.setPostContentMd(markdown);
    post.setPostContent(content);
    post.setPostType(PostTypeEnum.POST_TYPE_POST.getDesc());
    post.setAllowComment(AllowCommentEnum.ALLOW.getCode());
    post.setUser(user);
    post.setTags(tags);
    post.setCategories(categories);
    post.setPostUrl(StrUtil.removeSuffix(file.getOriginalFilename(), ".md"));
    int postSummary = 50;
    if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
        postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
    }
    final String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
    if (summaryText.length() > postSummary) {
        final String summary = summaryText.substring(0, postSummary);
        post.setPostSummary(summary);
    } else {
        post.setPostSummary(summaryText);
    }
    if (null == post.getPostDate()) {
        post.setPostDate(new Date());
    }
    if (null == post.getPostUpdate()) {
        post.setPostUpdate(new Date());
    }
    postService.save(post);
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode());
}
 
Example #22
Source File: AdminController.java    From stone with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 验证登录信息
 *
 * @param loginName 登录名:邮箱/用户名
 * @param loginPwd  loginPwd 密码
 * @param session   session session
 *
 * @return JsonResult JsonResult
 */
@PostMapping(value = "/getLogin")
@ResponseBody
public JsonResult getLogin(@ModelAttribute("loginName") String loginName,
                           @ModelAttribute("loginPwd") String loginPwd,
                           HttpSession session) {
    //已注册账号,单用户,只有一个
    final User aUser = userService.findUser();
    //首先判断是否已经被禁用已经是否已经过了10分钟
    Date loginLast = DateUtil.date();
    if (null != aUser.getLoginLast()) {
        loginLast = aUser.getLoginLast();
    }
    final Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
    if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled"));
    }
    //验证用户名和密码
    User user = null;
    if (Validator.isEmail(loginName)) {
        user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd));
    } else {
        user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd));
    }
    userService.updateUserLoginLast(DateUtil.date());
    //判断User对象是否相等
    if (ObjectUtil.equal(aUser, user)) {
        session.setAttribute(HaloConst.USER_SESSION_KEY, aUser);
        //重置用户的登录状态为正常
        userService.updateUserNormal();
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request);
        log.info("User {} login succeeded.", aUser.getUserDisplayName());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success"));
    } else {
        //更新失败次数
        final Integer errorCount = userService.updateUserLoginError();
        //超过五次禁用账户
        if (errorCount >= CommonParamsEnum.FIVE.getValue()) {
            userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
        }
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
        final Object[] args = {(5 - errorCount)};
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
    }
}
 
Example #23
Source File: CommentController.java    From stone with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 管理员回复评论
 *
 * @param commentId      被回复的评论
 * @param commentContent 回复的内容
 *
 * @return JsonResult
 */
@PostMapping(value = "/reply")
@ResponseBody
public JsonResult replyComment(@RequestParam("commentId") Long commentId,
                               @RequestParam("postId") Long postId,
                               @RequestParam("commentContent") String commentContent,
                               @RequestParam("userAgent") String userAgent,
                               HttpServletRequest request,
                               HttpSession session) {
    try {
        final Post post = postService.findByPostId(postId).orElse(new Post());

        //博主信息
        final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);

        //被回复的评论
        final Comment lastComment = commentService.findCommentById(commentId).orElse(new Comment());

        //修改被回复的评论的状态
        lastComment.setCommentStatus(CommentStatusEnum.PUBLISHED.getCode());
        commentService.save(lastComment);

        //保存评论
        final Comment comment = new Comment();
        comment.setPost(post);
        comment.setCommentAuthor(user.getUserDisplayName());
        comment.setCommentAuthorEmail(user.getUserEmail());
        comment.setCommentAuthorUrl(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()));
        comment.setCommentAuthorIp(ServletUtil.getClientIP(request));
        comment.setCommentAuthorAvatarMd5(SecureUtil.md5(user.getUserEmail()));
        comment.setCommentDate(DateUtil.date());

        final StrBuilder buildContent = new StrBuilder("<a href='#comment-id-");
        buildContent.append(lastComment.getCommentId());
        buildContent.append("'>@");
        buildContent.append(lastComment.getCommentAuthor());
        buildContent.append("</a> ");
        buildContent.append(OwoUtil.markToImg(HtmlUtil.escape(commentContent).replace("&lt;br/&gt;", "<br/>")));

        comment.setCommentContent(buildContent.toString());
        comment.setCommentAgent(userAgent);
        comment.setCommentParent(commentId);
        comment.setCommentStatus(CommentStatusEnum.PUBLISHED.getCode());
        comment.setIsAdmin(1);
        commentService.save(comment);

        //邮件通知
        new EmailToAuthor(comment, lastComment, post, user, commentContent).start();
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode());
    } catch (Exception e) {
        log.error("Reply to comment failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode());
    }
}