diff --git a/luoo_comment/src/main/java/com/luoo/comment/config/BaseExceptionHandler.java b/luoo_comment/src/main/java/com/luoo/comment/config/BaseExceptionHandler.java deleted file mode 100644 index 0036d98..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/config/BaseExceptionHandler.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.luoo.comment.config; - -import api.Result; -import api.StatusCode; -import com.luoo.comment.exception.AuthorityLoginException; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; - -/** - * 统一异常处理类 - */ -@Slf4j -@ControllerAdvice -public class BaseExceptionHandler { - @ExceptionHandler(value = Exception.class) - @ResponseBody - public Result error(Exception e) { - log.error("执行出错", e); - return Result.failed(StatusCode.MUSIC_COMMON_FAILED); - } - - @ExceptionHandler(value = AuthorityLoginException.class) - @ResponseBody - public Result error(AuthorityLoginException e) { - return Result.unauthorized(null); - } -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/config/TokenInterceptor.java b/luoo_comment/src/main/java/com/luoo/comment/config/TokenInterceptor.java deleted file mode 100644 index b99ac02..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/config/TokenInterceptor.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.luoo.comment.config; - -import com.luoo.comment.constant.GlobalConstant; -import com.luoo.comment.utils.ThreadLocalMap; -import dto.UserLoginDto; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; -import util.JwtUtil; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@Slf4j -@Component -public class TokenInterceptor implements HandlerInterceptor { - - @Autowired - private JwtUtil jwtUtil; - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - return HandlerInterceptor.super.preHandle(request, response, handler); - } - - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { - - String token = request.getHeader("token"); - UserLoginDto loginUser = jwtUtil.getUserLoginDto(token); - if (loginUser == null) { - log.error("获取用户信息失败, 不允许操作,需重新登录"); - throw new RuntimeException("获取用户信息失败, 不允许操作,需重新登录"); - } - log.info("请求uri => {} method => {} userId => {} token => {}", - request.getRequestURI(), request.getMethod(), loginUser.getUserId(),token); - ThreadLocalMap.put(GlobalConstant.TOKEN_AUTH_DTO, loginUser); - } - - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { - ThreadLocalMap.remove(GlobalConstant.TOKEN_AUTH_DTO); - } - - - -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/constant/GlobalConstant.java b/luoo_comment/src/main/java/com/luoo/comment/constant/GlobalConstant.java deleted file mode 100644 index 12f2ed3..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/constant/GlobalConstant.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.luoo.comment.constant; - -public class GlobalConstant { - - /** - * 全局用户名 - */ - public static final String TOKEN_AUTH_DTO = "CURRENT_USER_DTO"; -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/controller/BaseController.java b/luoo_comment/src/main/java/com/luoo/comment/controller/BaseController.java deleted file mode 100644 index 640cb99..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/controller/BaseController.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.luoo.comment.controller; - -import cn.hutool.core.util.ObjectUtil; -import com.luoo.comment.exception.AuthorityLoginException; -import com.luoo.comment.utils.ThreadLocalMap; -import dto.UserLoginDto; - -public class BaseController { - - /** - * 全局用户名 - */ - public static final String TOKEN_AUTH_DTO = "CURRENT_USER_DTO"; - - protected UserLoginDto getLoginAuthDto() { - UserLoginDto loginAuthDto = (UserLoginDto) ThreadLocalMap.get(TOKEN_AUTH_DTO); - if (ObjectUtil.isEmpty(loginAuthDto)) { - throw new AuthorityLoginException("登录信息已失效,请重新登录"); - } - return loginAuthDto; - } -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/controller/CommentController.java b/luoo_comment/src/main/java/com/luoo/comment/controller/CommentController.java index 31eb020..1a5bd82 100644 --- a/luoo_comment/src/main/java/com/luoo/comment/controller/CommentController.java +++ b/luoo_comment/src/main/java/com/luoo/comment/controller/CommentController.java @@ -6,70 +6,120 @@ import api.Result; import api.StatusCode; import com.luoo.comment.pojo.*; import com.luoo.comment.service.CommentService; +import controller.BaseController; import dto.UserLoginDto; -import io.swagger.models.auth.In; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.*; -import java.util.List; +import java.util.concurrent.TimeUnit; @RestController @CrossOrigin @RequestMapping("/comment") -public class CommentController extends BaseController{ +public class CommentController extends BaseController { + + @Autowired private CommentService commentService; - @GetMapping("/findByVolid/{volid}") - public Result> findByVolid(@PathVariable String volid){ - return Result.success(commentService.findByVolid(volid)); + + @Autowired + private RedisTemplate redisTemplate; + + @GetMapping + public Result findAll(){ + return Result.success(commentService.findAll()); } - @GetMapping("/{commentId}") - public Result findById(@PathVariable String commentId) { - return Result.success(commentService.findById(commentId)); + /** + * 根据期刊ID获取根节点评论分页列表 ,数据库中保存的有期刊号的都是根节点,期刊号为空的代表有父评论且parentID一定有值 + * + * 拿到当然根节点评论列表,每个根评论有 commentCount字段,页面可以显示有 280个回复,然后根据 @GetMapping("/comment/{parentId}/{page}/{size}") 接口,分页拿到该评论下的子评论列表 + * + * ,页面在请求添加评论的时候,当给评论添加子评论的时候,父评论parentID有值,就无法添加子评论并且不显示回复2字,控制到两级 + * @return + */ + @GetMapping("/{journalId}/{page}/{size}") + public Result findAllByJournalId(@PathVariable String journalId,@PathVariable int page,@PathVariable int size) { + Page pageData = commentService.findByJournalId(journalId,page,size); + return Result.success(new PageResult(pageData.getTotalElements(),pageData.getContent())); } - @PostMapping("/save") - public Result save(@RequestBody CommentDto commentDto){ - UserLoginDto loginAuthDto = getLoginAuthDto(); - commentDto.setUserId(loginAuthDto.getUserId()); - commentService.save(commentDto); + @GetMapping("/{commentId}") + public Result findById(@PathVariable String commentId){ + return Result.success(commentService.findById(commentId)); + } + + + @PostMapping + public Result save(@RequestBody CommentVo commentVo, @RequestHeader(value = "Authorization", required = true) String authorization){ + //验证是否登录,并且拿到ID + UserLoginDto userLoginDto = getUserLoginDto(authorization); + if (null == userLoginDto) { + return Result.unauthorized(null); + } + String userId = userLoginDto.getUserId(); + Comment comment = new Comment(); + BeanUtils.copyProperties(commentVo, comment); + comment.setUserId(userId); + comment.setNickName(userLoginDto.getNickName()); + commentService.save(comment); return Result.success(); + } + + + @PutMapping("/{commentId}") + public Result update(@PathVariable String commentId,@RequestBody Comment comment) { + comment.set_id(commentId); + commentService.update(comment); + return Result.success(); } @DeleteMapping("/{commentId}") - public Result delete(@PathVariable String commentId){ + public Result delete(@PathVariable String commentId) { commentService.deleteById(commentId); return Result.success(); } - @GetMapping("/findByParentId") - public Result> findByParentId(@RequestParam String parentId, - @RequestParam int page, - @RequestParam int size){ - Page pageData = commentService.findByParentId(parentId,page,size); - return Result.success(new PageResult<>(pageData.getTotalElements(),pageData.getContent())); + + + @GetMapping("/comment/{parentId}/{page}/{size}") + public Result findByParentId(@PathVariable String parentId,@PathVariable int page,@PathVariable int size) { + + Page pageData = commentService.findByParentId(parentId,page,size); + + return Result.success(new PageResult(pageData.getTotalElements(),pageData.getContent())); } - @PutMapping("/thumbup") - public Result thumbup(@RequestBody CommentThumbupDto commentThumbupDto){ - UserLoginDto loginAuthDto = getLoginAuthDto(); - String userId = loginAuthDto.getUserId(); - commentThumbupDto.setUserId(userId); - commentService.thumbup(commentThumbupDto); + + @PutMapping("/thumbup/{commentId}") + public Result thumbup(@PathVariable String commentId,@RequestHeader(value = "Authorization", required = true) String authorization) { + + // 判断当前用户是否已经点赞 + //验证是否登录,并且拿到ID + UserLoginDto userLoginDto = getUserLoginDto(authorization); + if (null == userLoginDto) { + return Result.unauthorized(null); + } + String userId = userLoginDto.getUserId(); + + if(redisTemplate.opsForValue().get("thumbup_"+commentId+"_"+userId)!=null){ + + return Result.failed(StatusCode.COMMENT_REPEAT_THUMBUP); + } + + commentService.thumbup(commentId); + + redisTemplate.opsForValue().set("thumbup_"+commentId+"_"+userId,1,10, TimeUnit.SECONDS); return Result.success(); - } - @GetMapping("/getUserCommentInfo") - public Result getUserCommentInfo(@RequestParam String userId){ - CommentThumbupVo userCommentInfo = commentService.getUserCommentInfo(userId); - return Result.success(userCommentInfo); } + } diff --git a/luoo_comment/src/main/java/com/luoo/comment/dao/CommentDao.java b/luoo_comment/src/main/java/com/luoo/comment/dao/CommentDao.java index 9adfced..ad90c5e 100644 --- a/luoo_comment/src/main/java/com/luoo/comment/dao/CommentDao.java +++ b/luoo_comment/src/main/java/com/luoo/comment/dao/CommentDao.java @@ -5,12 +5,8 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; -import java.util.List; - public interface CommentDao extends MongoRepository { - Page findByParentId(String parentId, Pageable pageable); - - List findByArticleId(String articleId); - + public Page findByParentId(String parentId, Pageable pageable); + public Page findByJournalId(String journalId, Pageable pageable); } diff --git a/luoo_comment/src/main/java/com/luoo/comment/enums/CommentStatusEnum.java b/luoo_comment/src/main/java/com/luoo/comment/enums/CommentStatusEnum.java deleted file mode 100644 index 274389a..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/enums/CommentStatusEnum.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.luoo.comment.enums; - -public enum CommentStatusEnum { - - /** - * 正常 - */ - NORMAL(1), - - /** - * 删除 - */ - DELETE(2), - - /** - * 审核中 - */ - AUDITING(3); - - private final int value; - - CommentStatusEnum(int value) { - this.value = value; - } - - public int getValue() { - return value; - } -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/enums/Province.java b/luoo_comment/src/main/java/com/luoo/comment/enums/Province.java deleted file mode 100644 index 5f8c5ba..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/enums/Province.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.luoo.comment.enums; - -import cn.hutool.core.util.ObjectUtil; - -public enum Province { - BEIJING("Beijing", "北京"), - TIANJIN("Tianjin", "天津"), - SHANGHAI("Shanghai", "上海"), - CHONGQING("Chongqing", "重庆"), - HEBEI("Hebei", "河北"), - SHANXI("Shanxi", "山西"), - LIAONING("Liaoning", "辽宁"), - JILIN("Jilin", "吉林"), - HEILONGJIANG("Heilongjiang", "黑龙江"), - JIANGSU("Jiangsu", "江苏"), - ZHEJIANG("Zhejiang", "浙江"), - ANHUI("Anhui", "安徽"), - FUJIAN("Fujian", "福建"), - JIANGXI("Jiangxi", "江西"), - SHANDONG("Shandong", "山东"), - HENAN("Henan", "河南"), - HUBEI("Hubei", "湖北"), - HUNAN("Hunan", "湖南"), - GUANGDONG("Guangdong", "广东"), - GUANGXI("Guangxi", "广西"), - HAINAN("Hainan", "海南"), - SICHUAN("Sichuan", "四川"), - GUIZHOU("Guizhou", "贵州"), - YUNNAN("Yunnan", "云南"), - TIBET("Tibet", "西藏"), - SHAANXI("Shaanxi", "陕西"), - GANSU("Gansu", "甘肃"), - QINGHAI("Qinghai", "青海"), - NINGXIA("Ningxia", "宁夏"), - XINJIANG("Xinjiang", "新疆"); - - private final String englishName; - private final String chineseName; - - Province(String englishName, String chineseName) { - this.englishName = englishName; - this.chineseName = chineseName; - } - - public String getEnglishName() { - return englishName; - } - - public String getChineseName() { - return chineseName; - } - - public static String getCityName(String englishName) { - if (ObjectUtil.isEmpty(englishName)) { - return "未知IP"; - } - for (Province province : Province.values()) { - if (englishName.equalsIgnoreCase(province.englishName)) { - return province.chineseName; - } - } - return "未知IP"; - } -} \ No newline at end of file diff --git a/luoo_comment/src/main/java/com/luoo/comment/enums/ThumbupActionEnum.java b/luoo_comment/src/main/java/com/luoo/comment/enums/ThumbupActionEnum.java deleted file mode 100644 index 1cdf844..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/enums/ThumbupActionEnum.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.luoo.comment.enums; - -public enum ThumbupActionEnum { - - /** - * 确认 - */ - CONFIRM(1), - - /** - * 取消 - */ - CANCEL(0); - - private final int value; - - ThumbupActionEnum(int value) { - this.value = value; - } - - public int getValue() { - return value; - } -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/exception/AuthorityLoginException.java b/luoo_comment/src/main/java/com/luoo/comment/exception/AuthorityLoginException.java deleted file mode 100644 index 751426f..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/exception/AuthorityLoginException.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.luoo.comment.exception; - -import api.StatusCode; - -public class AuthorityLoginException extends RuntimeException { - private static final long serialVersionUID = 2466145171145432619L; - private StatusCode codeEnum; - private Integer code = 401; - - public AuthorityLoginException(String message) { - super(message); - } - - public AuthorityLoginException(String message, Integer code) { - super(message); - this.code = code; - } - - public StatusCode getCodeEnum() { - return codeEnum; - } - - public Integer getCode() { - return this.code; - } - - public AuthorityLoginException(StatusCode codeEnum) { - super(codeEnum.getMessage()); - this.codeEnum = codeEnum; - this.code = codeEnum.getCode(); - } - - /** - * 重写fillInStackTrace 业务异常不需要堆栈信息,提高效率. - */ - @Override - public Throwable fillInStackTrace() { - return this; - } -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/pojo/Comment.java b/luoo_comment/src/main/java/com/luoo/comment/pojo/Comment.java index 314fd22..4ae28fb 100644 --- a/luoo_comment/src/main/java/com/luoo/comment/pojo/Comment.java +++ b/luoo_comment/src/main/java/com/luoo/comment/pojo/Comment.java @@ -1,17 +1,17 @@ package com.luoo.comment.pojo; import lombok.Data; -import org.springframework.beans.BeanUtils; import org.springframework.data.annotation.Id; import java.io.Serializable; import java.util.Date; + @Data public class Comment implements Serializable { @Id - private String id; + private String _id; // 评论内容 private String content; // 发布时间 @@ -19,12 +19,14 @@ public class Comment implements Serializable { private String userId; + private String nickName; + // 点赞数 - private Integer thumbup; + private Integer thumbupCount; // 转发数 - private Integer share; +// private Integer share; // 评论数量 - private Integer comment; + private Integer commentCount; // 状态 private Integer state; @@ -34,23 +36,5 @@ public class Comment implements Serializable { */ private String parentId; - private String articleId; - - private Integer level; - - private String targetId; - - /** - * 评论类型 - */ - private Integer type; - - private String city; - - public CommentVo convertVo () { - CommentVo commentVo = new CommentVo(); - BeanUtils.copyProperties(this, commentVo); - return commentVo; - } - + private String journalId; } diff --git a/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentDto.java b/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentDto.java deleted file mode 100644 index edd315b..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentDto.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.luoo.comment.pojo; - -import lombok.Data; - -import java.io.Serializable; - -@Data -public class CommentDto implements Serializable { - - /** - * 文章 ID - */ - private String articleId; - - /** - * 评论内容 - */ - private String content; - - /** - * 父节点 ID - */ - private String parentId; - - /** - * 目标 ID - */ - private String targetId; - - /** - * IP 地址 - */ - private String ipAddress; - - private String userId; - -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentThumbupDto.java b/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentThumbupDto.java deleted file mode 100644 index 13eee6d..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentThumbupDto.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.luoo.comment.pojo; - -import lombok.Data; - -import javax.validation.constraints.NotNull; - -/** - * 点赞 DTO - */ -@Data -public class CommentThumbupDto { - - @NotNull - private String commentId; - - private Integer action; - - private String userId; -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentThumbupVo.java b/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentThumbupVo.java deleted file mode 100644 index ce529ff..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentThumbupVo.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.luoo.comment.pojo; - -import lombok.Data; - -@Data -public class CommentThumbupVo { - - /** - * 点赞数量 - */ - private Long thumbupNum; - - - /** - * 评论数量 - */ - private Long commentNum; - - /** - * 用户 ID - */ - private String userId; -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentVo.java b/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentVo.java index ec880bf..53b9f90 100644 --- a/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentVo.java +++ b/luoo_comment/src/main/java/com/luoo/comment/pojo/CommentVo.java @@ -2,77 +2,16 @@ package com.luoo.comment.pojo; import lombok.Data; -import java.util.Date; - @Data public class CommentVo { - - private String id; - /** - * 评论内容 - */ + // 评论内容 private String content; - /** - * 发布时间 - */ - private Date publishTime; - /** - * 用户 ID - */ - private String userId; - /** - * 昵称 - */ - private String nickName; - /** - * 点赞数 - */ - private Integer thumbup; - /** - * 转发数 - */ - private Integer share; - /** - * 评论数量 - */ - private Integer comment; - /** - * 状态 - */ - private String state; + /** * 父节点 ID */ private String parentId; - /** - * 文章 - */ - private String articleId; - - /** - * 层级 - */ - private Integer level; - - /** - * 目标ID - */ - private String targetId; - - /** - * 目标对象 - */ - private CommentVo targetComment; - - /** - * 评论类型 - */ - private String type; - - /** - * 城市 - */ - private String city; + private String journalId; } diff --git a/luoo_comment/src/main/java/com/luoo/comment/service/CommentService.java b/luoo_comment/src/main/java/com/luoo/comment/service/CommentService.java index 3f0fc99..771fb02 100644 --- a/luoo_comment/src/main/java/com/luoo/comment/service/CommentService.java +++ b/luoo_comment/src/main/java/com/luoo/comment/service/CommentService.java @@ -1,29 +1,96 @@ package com.luoo.comment.service; -import com.luoo.comment.pojo.*; +import com.luoo.comment.dao.CommentDao; +import com.luoo.comment.pojo.Comment; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import util.IdWorker; +import java.util.Date; import java.util.List; -public interface CommentService { +@Service +@Transactional +public class CommentService { - Comment findById(String id); + @Autowired + private CommentDao commentDao; - void save(CommentDto commentDto); + @Autowired + private IdWorker idWorker; - void update(Comment comment); + @Autowired + private MongoTemplate mongoTemplate; - void deleteById(String id); + @Autowired - Page findByParentId(String parentId, int page, int size); + public List findAll(){ + return commentDao.findAll(); + } - void thumbup(CommentThumbupDto commentThumbupDto); + public Comment findById(String id) { + return commentDao.findById(id).get(); + } - List findByVolid(String volid); + public void save(Comment comment) { + comment.set_id(idWorker.nextId()+""); + comment.setPublishTime(new Date()); + comment.setThumbupCount(0); //点赞数 + comment.setCommentCount(0); //回复数 + comment.setState(1); - /** - * 获取用户评论信息 - */ - CommentThumbupVo getUserCommentInfo(String userId); + // 如果当前添加的评论,有父节点,那么父节点的评论回复数要加一 + if (comment.getParentId()!=null && !"".equals(comment.getParentId())){ + + comment.setJournalId("");//如果有父节点,将期刊号置为空 + Query query = new Query(); + query.addCriteria(Criteria.where("_id").is(comment.getParentId())); + Update update = new Update(); + update.inc("commentCount",1); + mongoTemplate.updateFirst(query,update,"comment"); + } + + commentDao.save(comment); + } + + public void update (Comment comment) { + commentDao.save(comment); + } + + + public void deleteById(String id) { + commentDao.deleteById(id); + } + + public Page findByParentId(String parentId, int page, int size) { + + Pageable pageable = PageRequest.of(page-1,size); + return commentDao.findByParentId(parentId,pageable); + + } + + + public Page findByJournalId(String journalId, int page, int size) { + + Pageable pageable = PageRequest.of(page-1,size); + return commentDao.findByJournalId(journalId,pageable); + } + + public void thumbup(String commentId) { + + Query query = new Query(); + query.addCriteria(Criteria.where("_id").is(commentId)); + Update update = new Update(); + update.inc("thumbupCount",1); + mongoTemplate.updateFirst(query,update,"comment"); + } } diff --git a/luoo_comment/src/main/java/com/luoo/comment/service/impl/CommentServiceImpl.java b/luoo_comment/src/main/java/com/luoo/comment/service/impl/CommentServiceImpl.java deleted file mode 100644 index 7a59c69..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/service/impl/CommentServiceImpl.java +++ /dev/null @@ -1,233 +0,0 @@ -package com.luoo.comment.service.impl; - - -import api.Result; -import client.vo.SimpleUser; -import cn.hutool.core.util.ObjectUtil; -import com.luoo.comment.dao.CommentDao; -import com.luoo.comment.enums.CommentStatusEnum; -import com.luoo.comment.enums.Province; -import com.luoo.comment.enums.ThumbupActionEnum; -import com.luoo.comment.pojo.*; -import com.luoo.comment.service.CommentService; -import lombok.extern.slf4j.Slf4j; -import net.renfei.ip2location.IP2Location; -import net.renfei.ip2location.IPResult; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.*; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.core.query.Criteria; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.data.mongodb.core.query.Update; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import util.IdWorker; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - -@Service -@Transactional -@Slf4j -public class CommentServiceImpl implements CommentService { - -// @Autowired -// private UserClient userClient; - - @Autowired - private CommentDao commentDao; - - @Autowired - private IdWorker idWorker; - - @Autowired - private MongoTemplate mongoTemplate; - - @Autowired - private RedisTemplate redisTemplate; - - - public Comment findById(String id) { - return commentDao.findById(id).get(); - } - - public String getCityNameByIp(String ip) { - IP2Location loc = new IP2Location(); - String binFile = "classpath:/IP2LOCATION-LITE-DB11.BIN"; - try { - loc.Open(binFile, true); - IPResult rec = loc.IPQuery(ip); - String city = rec.getCity(); - return Province.getCityName(city); - } catch (IOException e) { - log.info("getCityNameByIp error {}",ip,e); - return "未知 IP"; - } - } - - public void save(CommentDto commentDto){ - Comment comment = new Comment(); - comment.setContent(commentDto.getContent()); - comment.setPublishTime(new Date()); - comment.setUserId(commentDto.getUserId()); - comment.setComment(0); - comment.setParentId(commentDto.getParentId()); - comment.setArticleId(commentDto.getArticleId()); - comment.setLevel(1); - comment.setTargetId(commentDto.getTargetId()); - comment.setType(0); - comment.setCity(getCityNameByIp(commentDto.getIpAddress())); - comment.setId(String.valueOf(idWorker.nextId())); - comment.setShare(0); - comment.setThumbup(0); - comment.setComment(0); - comment.setState(CommentStatusEnum.NORMAL.getValue()); - // 如果当前添加的吐槽,有父节点,那么父节点的吐槽回复数要加一 - if (ObjectUtil.isNotEmpty(comment.getParentId())) { - // 更新父节点的评论回复数 - Query query = new Query(); - query.addCriteria(Criteria.where("_id").is(comment.getParentId())); - Update update = new Update(); - update.inc("comment",1); - mongoTemplate.updateFirst(query,update,Comment.class); - } - - if (ObjectUtil.isNotEmpty(comment.getTargetId())) { - Comment parentIdComment = mongoTemplate.findById(comment.getTargetId(), Comment.class); - comment.setLevel(parentIdComment.getLevel()+1); - Query query = new Query(); - query.addCriteria(Criteria.where("_id").is(comment.getTargetId())); - Update update = new Update(); - update.inc("comment",1); - mongoTemplate.updateFirst(query,update,Comment.class); - } - commentDao.save(comment); - } - - public void update(Comment comment) { - commentDao.save(comment); - } - - public void deleteById(String id) { - commentDao.deleteById(id); - } - - - public Page findByParentId(String parentId,int page,int size){ - Pageable pageable = PageRequest.of(page, size); - Query query = new Query(); - Criteria criteria = Criteria.where("parentId").is(parentId); - query.addCriteria(criteria); - Sort sort = Sort.by(Sort.Direction.ASC, "age"); - query.with(sort); - query.with(pageable); - List comments = mongoTemplate.find(query, Comment.class); - - List userIds = comments.stream().map(Comment::getUserId).collect(Collectors.toList()); - -// Result> userByIds = userClient.findUserByIds(userIds); - Result> userByIds = Result.success(null); - - Map userIdAndInfoMap = userByIds.getData().stream().collect(Collectors.toMap(SimpleUser::getUserId, Function.identity())); - - List commentVos = comments.stream().map(Comment::convertVo).collect(Collectors.toList()); - -// List targetComments = comments.stream().map(Comment::getTargetId).collect(Collectors.toList()); - - Map idCommentMap = commentVos.stream().collect(Collectors.toMap(CommentVo::getId, Function.identity())); - - long total = mongoTemplate.count(query, Comment.class); - -// boolean isChange = targetComments.removeAll(idCommentMap.keySet()); - - for (CommentVo commentVo : commentVos) { - - // 处理昵称 - SimpleUser simpleUser = userIdAndInfoMap.get(commentVo.getUserId()); - - if (ObjectUtil.isNotEmpty(simpleUser)) { - commentVo.setNickName(simpleUser.getNickName()); - } - // 处理叠楼评论回复 - if (commentVo.getLevel() > 2 && ObjectUtil.isNotEmpty(commentVo.getTargetId())) { - CommentVo targetCommentVo = idCommentMap.get(commentVo.getTargetId()); - if (targetCommentVo != null) { - commentVo.setTargetComment(targetCommentVo); - } - } - } - return new PageImpl<>(commentVos, pageable, total); - } - - public void thumbup(CommentThumbupDto commentThumbupDto) { - String userId = commentThumbupDto.getUserId(); - - Long count = (Long)redisTemplate.opsForValue().get("thumbup_" + userId); - Query query = new Query(); - query.addCriteria(Criteria.where("_id").is(commentThumbupDto.getCommentId())); - Update update = new Update(); - if (commentThumbupDto.getAction().equals(ThumbupActionEnum.CONFIRM.getValue())) { - update.inc("thumbup",1); - if (ObjectUtil.isNotEmpty(count)) { - redisTemplate.opsForValue().set("thumbup_"+userId,++count); - } else { - redisTemplate.opsForValue().set("thumbup_"+userId,1L); - } - } else { - update.inc("thumbup",-1); - } - mongoTemplate.updateFirst(query,update,Comment.class); - } - - public List findByVolid(String volid) { - List byArticleId = commentDao.findByArticleId(volid); - - if (ObjectUtil.isEmpty(byArticleId)) { - return new ArrayList<>(); - } - - List commentVos = byArticleId.stream().map(Comment::convertVo).collect(Collectors.toList()); - - List userIds = byArticleId.stream().map(Comment::getUserId).collect(Collectors.toList()); -// Result> userByIds = userClient.findUserByIds(userIds); - Result> userByIds = Result.success(null); - Map userIdAndInfoMap = userByIds.getData().stream().collect(Collectors.toMap(SimpleUser::getUserId, Function.identity())); - - for (CommentVo commentVo : commentVos) { - // 处理昵称 - SimpleUser simpleUser = userIdAndInfoMap.get(commentVo.getUserId()); - - if (ObjectUtil.isNotEmpty(simpleUser)) { - commentVo.setNickName(simpleUser.getNickName()); - } - } - return commentVos; - } - - @Override - public CommentThumbupVo getUserCommentInfo(String userId) { - // 获取用户点赞数量 - CommentThumbupVo commentThumbupVo = new CommentThumbupVo(); - Long count = (Long)redisTemplate.opsForValue().get("thumbup_" + userId); - if (ObjectUtil.isEmpty(count)) { - count = 0L; - } - commentThumbupVo.setThumbupNum(count); - - // 获取评论数量 - Query query = new Query(); - query.addCriteria(Criteria.where("userId").is(userId)); - long commentCount = mongoTemplate.count(query, Comment.class); - commentThumbupVo.setCommentNum(commentCount); - return commentThumbupVo; - } - - -} diff --git a/luoo_comment/src/main/java/com/luoo/comment/utils/ThreadLocalMap.java b/luoo_comment/src/main/java/com/luoo/comment/utils/ThreadLocalMap.java deleted file mode 100644 index 92bccf6..0000000 --- a/luoo_comment/src/main/java/com/luoo/comment/utils/ThreadLocalMap.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.luoo.comment.utils; - -import lombok.AccessLevel; -import lombok.NoArgsConstructor; - -import java.util.HashMap; -import java.util.Map; - - -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public class ThreadLocalMap { - /** - * The constant threadContext. - */ - private final static ThreadLocal> THREAD_CONTEXT = new MapThreadLocal(); - - /** - * Put. - * - * @param key the key - * @param value the value - */ - public static void put(String key, Object value) { - getContextMap().put(key, value); - } - - /** - * Remove object. - * - * @param key the key - * - * @return the object - */ - public static Object remove(String key) { - return getContextMap().remove(key); - } - - /** - * Get object. - * - * @param key the key - * - * @return the object - */ - public static Object get(String key) { - return getContextMap().get(key); - } - - private static class MapThreadLocal extends ThreadLocal> { - /** - * Initial value map. - * - * @return the map - */ - @Override - protected Map initialValue() { - return new HashMap(8) { - - private static final long serialVersionUID = 3637958959138295593L; - - @Override - public Object put(String key, Object value) { - return super.put(key, value); - } - }; - } - } - - /** - * 取得thread context Map的实例。 - * - * @return thread context Map的实例 - */ - private static Map getContextMap() { - return THREAD_CONTEXT.get(); - } - - /** - * 清理线程所有被hold住的对象。以便重用! - */ - public static void remove() { - getContextMap().clear(); - } -} \ No newline at end of file diff --git a/luoo_common/src/main/java/api/StatusCode.java b/luoo_common/src/main/java/api/StatusCode.java index e70e7e5..c8a0e61 100644 --- a/luoo_common/src/main/java/api/StatusCode.java +++ b/luoo_common/src/main/java/api/StatusCode.java @@ -26,6 +26,7 @@ public enum StatusCode implements IErrorCode { // comment 模块错误码以30XXX,不足5位补0; COMMENT_COMMON_FAILED(30000, "评论模块错误"), COMMENT_REPEAT_SUBMIT(30001, "评论重复提交"), + COMMENT_REPEAT_THUMBUP(30002,"不能重复点赞"), // friend 模块错误码以40XXX,不足5位补0; FRIEND_COMMON_FAILED(40000, "交友模块错误"),