Refactor cc.ryanc.halo.web.controller.admin.AdminController and AttachmentService

pull/137/head
johnniang 2019-03-01 22:21:24 +08:00
parent 7e3f584843
commit 568ea0827a
5 changed files with 138 additions and 83 deletions

View File

@ -1,6 +1,9 @@
package cc.ryanc.halo.model.domain; package cc.ryanc.halo.model.domain;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import io.undertow.util.DateUtils;
import lombok.Data; import lombok.Data;
import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.annotation.LastModifiedDate;
@ -154,4 +157,17 @@ public class Post implements Serializable {
public Date getPostUpdate() { public Date getPostUpdate() {
return postUpdate; return postUpdate;
} }
@PrePersist
public void prePersist() {
DateTime now = DateUtil.date();
postDate = now;
postUpdate = now;
postId = null;
}
@PreUpdate
public void preUpdate() {
postUpdate = DateUtil.date();
}
} }

View File

@ -1,9 +1,11 @@
package cc.ryanc.halo.model.dto; package cc.ryanc.halo.model.dto;
import cc.ryanc.halo.model.enums.ResultCodeEnum;
import lombok.Data; import lombok.Data;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.lang.NonNull; import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/** /**
* <pre> * <pre>
@ -112,4 +114,56 @@ public class JsonResult {
public static JsonResult ok(@Nullable String message) { public static JsonResult ok(@Nullable String message) {
return ok(message, null); return ok(message, null);
} }
/**
* Creates an fail result with message only.
*
* @param message message of result must not be blank
* @return fail result with message only
*/
public static JsonResult fail(@NonNull String message) {
Assert.hasText(message, "Message of result must not be blank");
return new JsonResult(ResultCodeEnum.FAIL.getCode(), message);
}
/**
* Creates an fail result.
*
* @param message message of result must not be blank
* @return fail result
*/
public static JsonResult fail(@NonNull String message, @NonNull Object data) {
Assert.notNull(data, "Data of result must not be null");
JsonResult failResult = fail(message);
failResult.setResult(data);
return failResult;
}
/**
* Creates an success result with message only.
*
* @param message message of result must not be blank
* @return success result with message only
*/
public static JsonResult success(@NonNull String message) {
Assert.hasText(message, "Message of result must not be blank");
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), message);
}
/**
* Creates an success result.
*
* @param message message of result must not be blank
* @return success result
*/
public static JsonResult success(@NonNull String message, @NonNull Object data) {
Assert.notNull(data, "Data of result must not be null");
JsonResult successResult = success(message);
successResult.setResult(data);
return successResult;
}
} }

View File

@ -1,5 +1,6 @@
package cc.ryanc.halo.service.impl; package cc.ryanc.halo.service.impl;
import cc.ryanc.halo.logging.Logger;
import cc.ryanc.halo.model.domain.Attachment; import cc.ryanc.halo.model.domain.Attachment;
import cc.ryanc.halo.model.dto.QiNiuPutSet; import cc.ryanc.halo.model.dto.QiNiuPutSet;
import cc.ryanc.halo.model.enums.AttachLocationEnum; import cc.ryanc.halo.model.enums.AttachLocationEnum;
@ -31,6 +32,7 @@ import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
@ -54,6 +56,8 @@ import static cc.ryanc.halo.model.dto.HaloConst.OPTIONS;
@Service @Service
public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Long> implements AttachmentService { public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Long> implements AttachmentService {
private final Logger log = Logger.getLogger(getClass());
private static final String ATTACHMENTS_CACHE_NAME = "attachments"; private static final String ATTACHMENTS_CACHE_NAME = "attachments";
private final AttachmentRepository attachmentRepository; private final AttachmentRepository attachmentRepository;
@ -160,6 +164,9 @@ public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Long>
*/ */
@Override @Override
public Map<String, String> attachUpload(MultipartFile file, HttpServletRequest request) { public Map<String, String> attachUpload(MultipartFile file, HttpServletRequest request) {
Assert.notNull(file, "MultipartFile must not be null");
Assert.notNull(request, "Http servlet request must not be null");
final Map<String, String> resultMap = new HashMap<>(6); final Map<String, String> resultMap = new HashMap<>(6);
final String dateString = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss"); final String dateString = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
try { try {
@ -277,17 +284,11 @@ public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Long>
putSet = new Gson().fromJson(response.bodyString(), QiNiuPutSet.class); putSet = new Gson().fromJson(response.bodyString(), QiNiuPutSet.class);
} catch (QiniuException e) { } catch (QiniuException e) {
final Response r = e.response; final Response r = e.response;
System.err.println(r.toString()); log.error("Qiniu error response: [{}]", r);
try { } catch (JsonSyntaxException | IOException e) {
System.err.println(r.bodyString()); log.error("Failed to attach QiNiu resource", e);
} catch (QiniuException ex2) {
//ignore
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
final String filePath = domain.trim() + "/" + key; final String filePath = domain.trim() + "/" + key;
resultMap.put("fileName", file.getOriginalFilename()); resultMap.put("fileName", file.getOriginalFilename());
resultMap.put("filePath", filePath.trim()); resultMap.put("filePath", filePath.trim());
@ -297,7 +298,7 @@ public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Long>
resultMap.put("wh", putSet.getW() + "x" + putSet.getH()); resultMap.put("wh", putSet.getW() + "x" + putSet.getH());
resultMap.put("location", AttachLocationEnum.QINIU.getDesc()); resultMap.put("location", AttachLocationEnum.QINIU.getDesc());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.debug("Failed to generate md5 check sum", e);
} }
return resultMap; return resultMap;
} }
@ -347,7 +348,7 @@ public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Long>
resultMap.put("location", AttachLocationEnum.UPYUN.getDesc()); resultMap.put("location", AttachLocationEnum.UPYUN.getDesc());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Failed to attach UpYun resource", e);
} }
return resultMap; return resultMap;
} }
@ -400,10 +401,8 @@ public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Long>
upYun.setApiDomain(UpYun.ED_AUTO); upYun.setApiDomain(UpYun.ED_AUTO);
try { try {
flag = upYun.deleteFile(ossSrc + fileName); flag = upYun.deleteFile(ossSrc + fileName);
} catch (IOException e) { } catch (IOException | UpException e) {
e.printStackTrace(); log.error("Failed to delete UpYun attachment", e);
} catch (UpException e) {
e.printStackTrace();
} }
return flag; return flag;
} }

View File

@ -1,5 +1,6 @@
package cc.ryanc.halo.web.controller.admin; package cc.ryanc.halo.web.controller.admin;
import cc.ryanc.halo.logging.Logger;
import cc.ryanc.halo.model.domain.*; import cc.ryanc.halo.model.domain.*;
import cc.ryanc.halo.model.dto.JsonResult; import cc.ryanc.halo.model.dto.JsonResult;
import cc.ryanc.halo.model.dto.LogsRecord; import cc.ryanc.halo.model.dto.LogsRecord;
@ -12,11 +13,10 @@ import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Validator; import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HtmlUtil; import cn.hutool.http.HtmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
@ -24,6 +24,7 @@ import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@ -43,11 +44,12 @@ import static cc.ryanc.halo.model.dto.HaloConst.USER_SESSION_KEY;
* @author : RYAN0UP * @author : RYAN0UP
* @date : 2017/12/5 * @date : 2017/12/5
*/ */
@Slf4j
@Controller @Controller
@RequestMapping(value = "/admin") @RequestMapping(value = "/admin")
public class AdminController extends BaseController { public class AdminController extends BaseController {
private final Logger log = Logger.getLogger(getClass());
@Autowired @Autowired
private PostService postService; private PostService postService;
@ -79,7 +81,6 @@ public class AdminController extends BaseController {
* *
* *
* @param model model * @param model model
*
* @return admin/admin_index * @return admin/admin_index
*/ */
@GetMapping(value = {"", "/index"}) @GetMapping(value = {"", "/index"})
@ -119,17 +120,13 @@ public class AdminController extends BaseController {
* *
* *
* @param session session * @param session session
*
* @return admin/admin_login * @return admin/admin_login
*/ */
@GetMapping(value = "/login") @GetMapping(value = "/login")
public String login(HttpSession session) { public String login(HttpSession session) {
final User user = (User) session.getAttribute(USER_SESSION_KEY); final User user = (User) session.getAttribute(USER_SESSION_KEY);
//如果session存在跳转到后台首页 //如果session存在跳转到后台首页
if (null != user) { return user != null ? "redirect:/admin" : "admin/admin_login";
return "redirect:/admin";
}
return "admin/admin_login";
} }
/** /**
@ -138,7 +135,6 @@ public class AdminController extends BaseController {
* @param loginName * @param loginName
* @param loginPwd loginPwd * @param loginPwd loginPwd
* @param session session session * @param session session session
*
* @return JsonResult JsonResult * @return JsonResult JsonResult
*/ */
@PostMapping(value = "/getLogin") @PostMapping(value = "/getLogin")
@ -148,6 +144,7 @@ public class AdminController extends BaseController {
HttpSession session) { HttpSession session) {
//已注册账号,单用户,只有一个 //已注册账号,单用户,只有一个
final User aUser = userService.findUser(); final User aUser = userService.findUser();
//首先判断是否已经被禁用已经是否已经过了10分钟 //首先判断是否已经被禁用已经是否已经过了10分钟
Date loginLast = DateUtil.date(); Date loginLast = DateUtil.date();
if (null != aUser.getLoginLast()) { if (null != aUser.getLoginLast()) {
@ -155,24 +152,26 @@ public class AdminController extends BaseController {
} }
final Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE); final Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) { if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled")); return JsonResult.fail(localeMessageUtil.getMessage("code.admin.login.disabled"));
} }
//验证用户名和密码 //验证用户名和密码
User user = null; User user;
if (Validator.isEmail(loginName)) { if (Validator.isEmail(loginName)) {
user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd)); user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd));
} else { } else {
user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd)); user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd));
} }
userService.updateUserLoginLast(DateUtil.date()); userService.updateUserLoginLast(DateUtil.date());
//判断User对象是否相等 //判断User对象是否相等
if (ObjectUtil.equal(aUser, user)) { if (Objects.equals(aUser, user)) {
session.setAttribute(USER_SESSION_KEY, aUser); session.setAttribute(USER_SESSION_KEY, aUser);
//重置用户的登录状态为正常 //重置用户的登录状态为正常
userService.updateUserNormal(); userService.updateUserNormal();
logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request); logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request);
log.info("User {} login succeeded.", aUser.getUserDisplayName()); log.info("User {} login succeeded.", aUser.getUserDisplayName());
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success")); return JsonResult.success(localeMessageUtil.getMessage("code.admin.login.success"));
} else { } else {
//更新失败次数 //更新失败次数
final Integer errorCount = userService.updateUserLoginError(); final Integer errorCount = userService.updateUserLoginError();
@ -181,8 +180,7 @@ public class AdminController extends BaseController {
userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc()); userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
} }
logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request); logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
final Object[] args = {(5 - errorCount)}; return JsonResult.fail(localeMessageUtil.getMessage("code.admin.login.failed", new Integer[]{5 - errorCount}));
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
} }
} }
@ -190,7 +188,6 @@ public class AdminController extends BaseController {
* 退 session * 退 session
* *
* @param session session * @param session session
*
* @return /admin/login * @return /admin/login
*/ */
@GetMapping(value = "/logOut") @GetMapping(value = "/logOut")
@ -206,7 +203,6 @@ public class AdminController extends BaseController {
* *
* *
* @param model model model * @param model model model
*
* @return admin/widget/_logs-all * @return admin/widget/_logs-all
*/ */
@GetMapping(value = "/logs") @GetMapping(value = "/logs")
@ -226,7 +222,7 @@ public class AdminController extends BaseController {
try { try {
logsService.removeAll(); logsService.removeAll();
} catch (Exception e) { } catch (Exception e) {
log.error("Clear log failed:{}" + e.getMessage()); log.error("Clear log failed", e);
} }
return "redirect:/admin"; return "redirect:/admin";
} }
@ -249,8 +245,8 @@ public class AdminController extends BaseController {
@GetMapping(value = "/getToken") @GetMapping(value = "/getToken")
@ResponseBody @ResponseBody
public JsonResult getToken() { public JsonResult getToken() {
final String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + ""; final String token = String.valueOf(System.currentTimeMillis() + RandomUtil.randomInt(Integer.MAX_VALUE));
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), HttpStatus.OK.getReasonPhrase(), SecureUtil.md5(token)); return JsonResult.success(HttpStatus.OK.getReasonPhrase(), SecureUtil.md5(token));
} }
/** /**
@ -278,7 +274,6 @@ public class AdminController extends BaseController {
* *
* @param file file * @param file file
* @param request request * @param request request
*
* @return JsonResult * @return JsonResult
*/ */
@PostMapping(value = "/tools/markdownImport") @PostMapping(value = "/tools/markdownImport")
@ -291,15 +286,12 @@ public class AdminController extends BaseController {
final String content = MarkdownUtils.renderMarkdown(markdown); final String content = MarkdownUtils.renderMarkdown(markdown);
final Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown); final Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown);
final Post post = new Post(); final Post post = new Post();
List<String> elementValue = null; final List<Tag> tags = new LinkedList<>();
final List<Tag> tags = new ArrayList<>(); final List<Category> categories = new LinkedList<>();
final List<Category> categories = new ArrayList<>();
Tag tag = null; if (!CollectionUtils.isEmpty(frontMatters)) {
Category category = null; // Iterate the map and inner list
if (frontMatters.size() > 0) { frontMatters.forEach((key, elementValue) -> elementValue.forEach(ele -> {
for (String key : frontMatters.keySet()) {
elementValue = frontMatters.get(key);
for (String ele : elementValue) {
if ("title".equals(key)) { if ("title".equals(key)) {
post.setPostTitle(ele); post.setPostTitle(ele);
} else if ("date".equals(key)) { } else if ("date".equals(key)) {
@ -307,32 +299,31 @@ public class AdminController extends BaseController {
} else if ("updated".equals(key)) { } else if ("updated".equals(key)) {
post.setPostUpdate(DateUtil.parse(ele)); post.setPostUpdate(DateUtil.parse(ele));
} else if ("tags".equals(key)) { } else if ("tags".equals(key)) {
tag = tagService.findTagByTagName(ele); Tag tag = Optional.ofNullable(tagService.findTagByTagName(ele)).orElseGet(() -> {
if (null == tag) { Tag aTag = new Tag();
tag = new Tag(); aTag.setTagName(ele);
tag.setTagName(ele); aTag.setTagUrl(ele);
tag.setTagUrl(ele); return tagService.create(aTag);
tag = tagService.create(tag); });
}
tags.add(tag); tags.add(tag);
} else if ("categories".equals(key)) { } else if ("categories".equals(key)) {
category = categoryService.findByCateName(ele); Category category = Optional.ofNullable(categoryService.findByCateName(ele)).orElseGet(() -> {
if (null == category) { Category catg = new Category();
category = new Category(); catg.setCateName(ele);
category.setCateName(ele); catg.setCateUrl(ele);
category.setCateUrl(ele); catg.setCateDesc(ele);
category.setCateDesc(ele); return categoryService.create(catg);
category = categoryService.create(category); });
}
categories.add(category); categories.add(category);
} }
}));
} }
}
} else { if (StrUtil.isBlank(post.getPostTitle())) {
post.setPostDate(new Date());
post.setPostUpdate(new Date());
post.setPostTitle(file.getOriginalFilename()); post.setPostTitle(file.getOriginalFilename());
} }
post.setPostContentMd(markdown); post.setPostContentMd(markdown);
post.setPostContent(content); post.setPostContent(content);
post.setPostType(PostTypeEnum.POST_TYPE_POST.getDesc()); post.setPostType(PostTypeEnum.POST_TYPE_POST.getDesc());
@ -341,12 +332,6 @@ public class AdminController extends BaseController {
post.setTags(tags); post.setTags(tags);
post.setCategories(categories); post.setCategories(categories);
post.setPostUrl(StrUtil.removeSuffix(file.getOriginalFilename(), ".md")); post.setPostUrl(StrUtil.removeSuffix(file.getOriginalFilename(), ".md"));
if (null == post.getPostDate()) {
post.setPostDate(new Date());
}
if (null == post.getPostUpdate()) {
post.setPostUpdate(new Date());
}
postService.create(post); postService.create(post);
return new JsonResult(ResultCodeEnum.SUCCESS.getCode()); return new JsonResult(ResultCodeEnum.SUCCESS.getCode());
} }

View File

@ -38,6 +38,7 @@ spring:
hibernate: hibernate:
ddl-auto: update ddl-auto: update
show-sql: false show-sql: false
open-in-view: false
freemarker: freemarker:
allow-request-override: false allow-request-override: false
cache: false cache: false