package com.kwan.springbootkwan.service.impl; import cn.hutool.core.collection.CollectionUtil; 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.CsdnUserInfo; import com.kwan.springbootkwan.entity.resp.BusinessInfoResponse; import com.kwan.springbootkwan.service.CsdnCollectService; import com.kwan.springbootkwan.service.CsdnCommentService; import com.kwan.springbootkwan.service.CsdnService; import com.kwan.springbootkwan.service.CsdnUserInfoService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.List; @Slf4j @Service public class CsdnServiceImpl implements CsdnService { @Value("${csdn.cookie}") private String csdnCookie; @Value("${csdn.num_of_articles_per_person}") private Integer numOfArticlesPerPerson; @Value("${csdn.url.user_article_url}") private String url; @Autowired private CsdnUserInfoService csdnUserInfoService; @Autowired private CsdnCollectService csdnCollectService; @Autowired private CsdnCommentService csdnCommentService; @Override public void singleArticle(String username) { HttpResponse response = HttpUtil.createGet(url) .header("Cookie", csdnCookie) .form("page", 1) .form("size", 5) .form("businessType", "lately") .form("noMore", false) .form("username", username) .execute(); final String body = response.body(); ObjectMapper objectMapper = new ObjectMapper(); BusinessInfoResponse businessInfoResponse; try { businessInfoResponse = objectMapper.readValue(body, BusinessInfoResponse.class); final BusinessInfoResponse.ArticleData data = businessInfoResponse.getData(); final List list = data.getList(); if (CollectionUtil.isNotEmpty(list)) { final int size = list.size(); if (size < numOfArticlesPerPerson) { numOfArticlesPerPerson = size; } for (int i = 0; i < numOfArticlesPerPerson; i++) { final BusinessInfoResponse.ArticleData.Article article = list.get(i); final String type = article.getType(); if (!StringUtils.equals("blog", type)) { continue; } final String urlInfo = article.getUrl(); String articleId = urlInfo.substring(urlInfo.lastIndexOf("/") + 1); //评论 final Boolean comment = csdnCommentService.isComment(article); if (!comment) { csdnCommentService.comment(articleId); } //收藏 final Boolean collect = csdnCollectService.isCollect(articleId); if (!collect) { csdnCollectService.collect(article, username); } } } } catch (JsonProcessingException e) { e.printStackTrace(); } } @Override public void multiTriplet() { final List list = csdnUserInfoService.list(); if (CollectionUtil.isNotEmpty(list)) { for (CsdnUserInfo csdnUserInfo : list) { singleArticle(csdnUserInfo.getUserName()); } } log.info("全部三连完成"); } }