package com.kwan.springbootkwan.service.impl; import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kwan.springbootkwan.entity.CsdnTripletDayInfo; import com.kwan.springbootkwan.entity.CsdnUserInfo; import com.kwan.springbootkwan.entity.resp.LikeResponse; import com.kwan.springbootkwan.enums.LikeStatus; import com.kwan.springbootkwan.service.CsdnLikeService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Slf4j @Service public class CsdnLikeServiceImpl implements CsdnLikeService { @Value("${csdn.cookie}") private String csdnCookie; @Value("${csdn.url.like_url}") private String url; @Override public Boolean isLike(String articleId, CsdnUserInfo csdnUserInfo) { final String userName = csdnUserInfo.getUserName(); final Integer likeStatus = csdnUserInfo.getLikeStatus(); if (LikeStatus.HAVE_ALREADY_LIKED.getCode().equals(likeStatus) || LikeStatus.LIKE_IS_FULL.getCode().equals(likeStatus)) { return true; } String url = "https://blog.csdn.net/" + userName + "/article/details/" + articleId; HttpResponse response = HttpUtil.createGet(url) .header("Cookie", csdnCookie) .form("articleId", articleId) .execute(); final String body = response.body(); if (body.contains("isLikeStatus = true")) { log.info("文章{}已经点过赞", articleId); csdnUserInfo.setLikeStatus(LikeStatus.HAVE_ALREADY_LIKED.getCode()); return true; } else { log.info("文章{}未点过赞", articleId); csdnUserInfo.setLikeStatus(LikeStatus.UN_PROCESSED.getCode()); return false; } } @Override public Boolean like(String articleId, CsdnUserInfo csdnUserInfo, CsdnTripletDayInfo csdnTripletDayInfo) { final Integer likeStatus = csdnUserInfo.getLikeStatus(); if (LikeStatus.HAVE_ALREADY_LIKED.getCode().equals(likeStatus) || LikeStatus.LIKE_IS_FULL.getCode().equals(likeStatus)) { return true; } HttpResponse response = HttpUtil.createPost(url) .header("Cookie", csdnCookie) .form("articleId", articleId) .execute(); final String body = response.body(); ObjectMapper objectMapper = new ObjectMapper(); try { final int code = objectMapper.readValue(body, LikeResponse.class).code; final LikeResponse.LikeDataDetail data = objectMapper.readValue(body, LikeResponse.class).getData(); if (code == 200) { final boolean status = data.status; if (status) { log.info("文章{}点赞成功", articleId); csdnUserInfo.setLikeStatus(LikeStatus.LIKE_SUCCESSFUL.getCode()); csdnTripletDayInfo.setLikeNum(csdnTripletDayInfo.getLikeNum() + 1); } else { log.info("文章{}点赞取消", articleId); csdnUserInfo.setLikeStatus(LikeStatus.CANCEL_LIKES.getCode()); } return status; } else if (code == 400) { log.info("今日点赞次数已达上限!"); csdnUserInfo.setLikeStatus(LikeStatus.LIKE_IS_FULL.getCode()); } } catch (JsonProcessingException e) { e.printStackTrace(); } return true; } }