Продолжаю дорабатывать бота

This commit is contained in:
upagge 2020-09-09 19:47:24 +03:00
parent 7839fceaa4
commit f4993776a0
No known key found for this signature in database
GPG Key ID: 15CD012E46F6BA34
22 changed files with 470 additions and 402 deletions

View File

@ -9,7 +9,7 @@ import org.springframework.stereotype.Component;
@Setter
@Component
@ConfigurationProperties(prefix = "bitbucketbot.init")
public class InitConfig {
public class InitProperty {
private Long startCommentId;

View File

@ -1,19 +0,0 @@
package org.sadtech.bot.bitbucketbot.domain;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Pagination {
private Integer page;
private Integer size;
public static Pagination of(Integer page, Integer size) {
return new Pagination(page, size);
}
}

View File

@ -1,6 +1,5 @@
package org.sadtech.bot.bitbucketbot.domain.change.task;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.sadtech.bot.bitbucketbot.domain.change.Change;
@ -10,13 +9,12 @@ import java.util.Set;
@Getter
@EqualsAndHashCode(callSuper = true)
public class TaskChange extends Change {
public abstract class TaskChange extends Change {
protected final String authorName;
protected final String url;
protected final String messageTask;
@Builder
protected TaskChange(
ChangeType type,
Set<Long> telegramIds,
@ -29,4 +27,5 @@ public class TaskChange extends Change {
this.url = url;
this.messageTask = messageTask;
}
}

View File

@ -9,8 +9,6 @@ import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
@ -20,7 +18,7 @@ import java.util.Set;
@Getter
@Setter
@Entity
@Table(name = "pull_request_comment")
@Table(name = "comment")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Comment {
@ -29,7 +27,6 @@ public class Comment {
*/
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@EqualsAndHashCode.Include
private Long id;

View File

@ -26,7 +26,7 @@ import javax.persistence.Table;
@Entity
@Getter
@Setter
@Table(name = "pull_request_reviewer")
@Table(name = "reviewer")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Reviewer {
@ -42,8 +42,8 @@ public class Reviewer {
/**
* Пользователь
*/
@Column(name = "user_login")
private String userLogin;
@Column(name = "person_login")
private String personLogin;
/**
* Статус

View File

@ -5,6 +5,7 @@ import lombok.Getter;
import lombok.Setter;
import org.sadtech.bot.bitbucketbot.domain.TaskStatus;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
@ -12,13 +13,16 @@ import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Getter
@Setter
@Table(name = "pull_request_task")
@Table(name = "task")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Task {
@ -62,4 +66,8 @@ public class Task {
@Column(name = "author_login")
private String author;
@JoinTable
@OneToMany(cascade = CascadeType.ALL)
private List<Comment> comments;
}

View File

@ -0,0 +1,25 @@
package org.sadtech.bot.bitbucketbot.repository;
import lombok.NonNull;
import org.sadtech.basic.context.repository.SimpleManagerRepository;
import org.sadtech.bot.bitbucketbot.domain.entity.Comment;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* // TODO: 08.09.2020 Добавить описание.
*
* @author upagge 08.09.2020
*/
public interface CommentRepository extends SimpleManagerRepository<Comment, Long> {
Optional<Comment> findFirstByOrderByIdDesc();
List<Comment> findByCreateDateBetween(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo);
List<Comment> findAllById(@NonNull Set<Long> ids);
}

View File

@ -11,7 +11,7 @@ import java.util.List;
@Repository
public class ChangeRepositoryImpl implements ChangeRepository {
private List<Change> list = new ArrayList<>();
private final List<Change> list = new ArrayList<>();
private long count = 0;
@Override
@ -23,8 +23,7 @@ public class ChangeRepositoryImpl implements ChangeRepository {
@Override
public List<Change> getAll() {
final ArrayList<Change> changes = new ArrayList<>(list);
return changes;
return new ArrayList<>(list);
}
@Override

View File

@ -0,0 +1,45 @@
package org.sadtech.bot.bitbucketbot.repository.impl;
import lombok.NonNull;
import org.sadtech.basic.database.repository.manager.AbstractSimpleManagerRepository;
import org.sadtech.bot.bitbucketbot.domain.entity.Comment;
import org.sadtech.bot.bitbucketbot.repository.CommentRepository;
import org.sadtech.bot.bitbucketbot.repository.jpa.CommentRepositoryJpa;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* // TODO: 08.09.2020 Добавить описание.
*
* @author upagge 08.09.2020
*/
@Repository
public class CommentRepositoryImpl extends AbstractSimpleManagerRepository<Comment, Long> implements CommentRepository {
private final CommentRepositoryJpa repositoryJpa;
public CommentRepositoryImpl(CommentRepositoryJpa repositoryJpa) {
super(repositoryJpa);
this.repositoryJpa = repositoryJpa;
}
@Override
public Optional<Comment> findFirstByOrderByIdDesc() {
return repositoryJpa.findFirstByOrderByIdDesc();
}
@Override
public List<Comment> findByCreateDateBetween(LocalDateTime dateFrom, LocalDateTime dateTo) {
return repositoryJpa.findByCreateDateBetween(dateFrom, dateTo);
}
@Override
public List<Comment> findAllById(@NonNull Set<Long> ids) {
return repositoryJpa.findAllById(ids);
}
}

View File

@ -1,5 +1,6 @@
package org.sadtech.bot.bitbucketbot.repository.jpa;
import lombok.NonNull;
import org.sadtech.bot.bitbucketbot.domain.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
@ -7,10 +8,10 @@ import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public interface CommentRepository extends JpaRepository<Comment, Long> {
public interface CommentRepositoryJpa extends JpaRepository<Comment, Long> {
Optional<Comment> findFirstByOrderByIdDesc();
List<Comment> findByCreateDateBetween(LocalDateTime dateFrom, LocalDateTime dateTo);
List<Comment> findByCreateDateBetween(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo);
}

View File

@ -27,7 +27,7 @@ public interface PullRequestsRepositoryJpa extends JpaRepositoryImplementation<P
void deleteAllByIdIn(Collection<Long> id);
@Query("SELECT p FROM PullRequest p LEFT JOIN p.reviewers r WHERE r.userLogin=:reviewer AND r.status =:reviewerStatus AND p.status IN :pullRequestStatus")
@Query("SELECT p FROM PullRequest p LEFT JOIN p.reviewers r WHERE r.personLogin=:reviewer AND r.status =:reviewerStatus AND p.status IN :pullRequestStatus")
List<PullRequest> findAllByReviewerAndStatuses(@Param("reviewer") String reviewer, @Param("reviewerStatus") ReviewerStatus reviewerStatus, @Param("pullRequestStatus") Set<PullRequestStatus> pullRequestStatus);
@Query("SELECT p FROM PullRequest p LEFT JOIN p.reviewers r WHERE p.authorLogin=:author AND r.status=:reviewerStatus")

View File

@ -1,22 +1,24 @@
package org.sadtech.bot.bitbucketbot.scheduler.parser;
import lombok.RequiredArgsConstructor;
import org.sadtech.bot.bitbucketbot.service.parser.CommentAndTaskParser;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class CommentAndTaskScheduler {
// private final CommentAndTaskParser commentAndTaskParser;
//
// @Scheduled(cron = "")
// public void scanNewCommentAndTask() {
// commentAndTaskParser.scanNewCommentAndTask();
// }
//
// @Scheduled(cron = "")
// public void scanOldComment() {
// commentAndTaskParser.scanOldComment();
// }
private final CommentAndTaskParser commentAndTaskParser;
@Scheduled(cron = "0 */1 * * * *")
public void scanNewCommentAndTask() {
commentAndTaskParser.scanNewCommentAndTask();
}
// @Scheduled(cron = "0 */1 * * * *")
public void scanOldComment() {
commentAndTaskParser.scanOldComment();
}
}

View File

@ -1,11 +1,6 @@
package org.sadtech.bot.bitbucketbot.service;
import lombok.NonNull;
import org.sadtech.bot.bitbucketbot.domain.change.Change;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.NewPrChange;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.UpdatePrChange;
import org.sadtech.bot.bitbucketbot.domain.entity.PullRequest;
import org.sadtech.bot.bitbucketbot.domain.util.ReviewerChange;
import java.util.List;
@ -17,11 +12,7 @@ import java.util.List;
*/
public interface ChangeService {
NewPrChange create(@NonNull PullRequest newPullRequest);
UpdatePrChange createUpdatePr(@NonNull PullRequest oldPullRequest, @NonNull PullRequest newPullRequest);
Change createReviewersPr(String prName, String prUrl, String authorLogin, List<ReviewerChange> reviewerChanges);
<T extends Change> void save(T task);
/**
* Позволяет получить новые изменения.

View File

@ -1,33 +1,19 @@
package org.sadtech.bot.bitbucketbot.service;
import lombok.NonNull;
import org.sadtech.bot.bitbucketbot.domain.Pagination;
import org.sadtech.basic.context.service.SimpleManagerService;
import org.sadtech.bot.bitbucketbot.domain.entity.Comment;
import org.springframework.data.domain.Page;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public interface CommentService {
public interface CommentService extends SimpleManagerService<Comment, Long> {
Long getLastCommentId();
Page<Comment> getAll(@NonNull Pagination pagination);
@NonNull
List<Comment> getAllBetweenDate(LocalDateTime dateFrom, LocalDateTime dateTo);
Comment create(@NonNull Comment comment);
void delete(@NonNull Long id);
Optional<Comment> getProxyById(@NonNull Long id);
List<Comment> createAll(List<Comment> newComments);
Comment update(Comment comment);
List<Comment> getAllBetweenDate(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo);
List<Comment> getAllById(@NonNull Set<Long> ids);
}

View File

@ -73,7 +73,7 @@ public class PullRequestJsonConverter implements Converter<PullRequestJson, Pull
.map(
jsonReviewer -> {
final Reviewer reviewer = new Reviewer();
reviewer.setUserLogin(jsonReviewer.getUser().getName());
reviewer.setPersonLogin(jsonReviewer.getUser().getName());
reviewer.setStatus(convertStatusReviewer(jsonReviewer.getStatus()));
return reviewer;
}

View File

@ -16,6 +16,7 @@ public class ResultScanToComment implements Converter<ResultScan, Comment> {
public Comment convert(ResultScan resultScan) {
final CommentJson commentJson = resultScan.getCommentJson();
final Comment comment = new Comment();
comment.setId(commentJson.getId());
comment.setCreateDate(commentJson.getCreatedDate());
comment.setAuthor(commentJson.getAuthor().getName());
comment.setPullRequestId(resultScan.getPullRequestId());

View File

@ -1,76 +1,22 @@
package org.sadtech.bot.bitbucketbot.service.impl;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.sadtech.bot.bitbucketbot.domain.change.Change;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.NewPrChange;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.ReviewersPrChange;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.UpdatePrChange;
import org.sadtech.bot.bitbucketbot.domain.entity.PullRequest;
import org.sadtech.bot.bitbucketbot.domain.entity.Reviewer;
import org.sadtech.bot.bitbucketbot.domain.util.ReviewerChange;
import org.sadtech.bot.bitbucketbot.repository.ChangeRepository;
import org.sadtech.bot.bitbucketbot.service.ChangeService;
import org.sadtech.bot.bitbucketbot.service.PersonService;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class ChangeServiceImpl implements ChangeService {
private final ChangeRepository changeRepository;
private final PersonService personService;
@Override
public NewPrChange create(@NonNull PullRequest newPullRequest) {
return changeRepository.add(
NewPrChange.builder()
.author(newPullRequest.getAuthorLogin())
.description(newPullRequest.getDescription())
.title(newPullRequest.getTitle())
.url(newPullRequest.getUrl())
.telegramIds(getReviewerTelegrams(newPullRequest.getReviewers()))
.build()
);
}
@Override
public UpdatePrChange createUpdatePr(@NonNull PullRequest oldPullRequest, @NonNull PullRequest newPullRequest) {
return changeRepository.add(
UpdatePrChange.builder()
.author(oldPullRequest.getAuthorLogin())
.name(newPullRequest.getTitle())
.telegramIds(getReviewerTelegrams(newPullRequest.getReviewers()))
.url(newPullRequest.getUrl())
.build()
);
}
@Override
public Change createReviewersPr(String prName, String prUrl, String authorLogin, List<ReviewerChange> reviewerChanges) {
return changeRepository.add(
ReviewersPrChange.builder()
.title(prName)
.url(prUrl)
.telegramIds(
personService.getAllTelegramIdByLogin(Collections.singleton(authorLogin))
)
.reviewerChanges(reviewerChanges)
.build()
);
}
private Set<Long> getReviewerTelegrams(@NonNull List<Reviewer> reviewers) {
return personService.getAllTelegramIdByLogin(
reviewers.stream()
.map(Reviewer::getUserLogin)
.collect(Collectors.toSet())
);
public <T extends Change> void save(T change) {
changeRepository.add(change);
}
@Override
@ -80,5 +26,4 @@ public class ChangeServiceImpl implements ChangeService {
return changes;
}
}

View File

@ -1,79 +1,72 @@
package org.sadtech.bot.bitbucketbot.service.impl;
//@Service
//@RequiredArgsConstructor
//public class CommentServiceImpl implements CommentService {
//
// private final PersonService personService;
// private final CommentRepository commentRepository;
// private final PullRequestsService pullRequestsService;
// private final InitConfig initConfig;
//
// @Override
// public Long getLastCommentId() {
// return commentRepository.findFirstByOrderByIdDesc().map(Comment::getId).orElse(getInitCommentId());
// }
//
// private Long getInitCommentId() {
// return initConfig.getStartCommentId() != null ? initConfig.getStartCommentId() : 0L;
// }
//
// @Override
// public Page<Comment> getAll(@NonNull Pagination pagination) {
// return commentRepository.findAll(PageRequest.of(pagination.getPage(), pagination.getSize()));
// }
//
// @Override
// public @NonNull List<Comment> getAllBetweenDate(LocalDateTime dateFrom, LocalDateTime dateTo) {
// return commentRepository.findByDateBetween(dateFrom, dateTo);
// }
//
// @Override
// public Comment create(@NonNull Comment comment) {
// comment.setAuthor(personService.getProxyByLogin(
// comment.getAuthor().getLogin()).orElseThrow(() -> new NotFoundException(""))
// );
// comment.setPullRequest(
// pullRequestsService.getProxyById(comment.getPullRequest().getId()).orElseThrow(() -> new NotFoundException(""))
// );
// return commentRepository.save(comment);
// }
//
// @Override
// public void delete(@NonNull Long id) {
// commentRepository.deleteById(id);
// }
//
// @Override
// public Optional<Comment> getProxyById(@NonNull Long id) {
// return Optional.ofNullable(commentRepository.getOne(id));
// }
//
// @Override
// @Transactional
// public List<Comment> createAll(List<Comment> newComments) {
// return newComments.stream()
// .map(this::create)
// .collect(Collectors.toList());
// }
//
// @Override
// public Comment update(Comment comment) {
// final Comment oldComment = commentRepository.findById(comment.getId())
// .orElseThrow(() -> new NotFoundException("Комментарий не найден"));
//
// if (oldComment.getBitbucketVersion().equals(comment.getBitbucketVersion())) {
// oldComment.setBitbucketVersion(comment.getBitbucketVersion());
// oldComment.setMessage(oldComment.getMessage());
// return commentRepository.save(oldComment);
// }
//
// return oldComment;
// }
//
// @Override
// public List<Comment> getAllById(@NonNull Set<Long> ids) {
// return commentRepository.findAllById(ids);
// }
//
//}
import lombok.NonNull;
import org.sadtech.basic.core.service.AbstractSimpleManagerService;
import org.sadtech.bot.bitbucketbot.config.InitProperty;
import org.sadtech.bot.bitbucketbot.domain.entity.Comment;
import org.sadtech.bot.bitbucketbot.exception.NotFoundException;
import org.sadtech.bot.bitbucketbot.repository.CommentRepository;
import org.sadtech.bot.bitbucketbot.service.CommentService;
import org.sadtech.bot.bitbucketbot.service.PersonService;
import org.sadtech.bot.bitbucketbot.service.PullRequestsService;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
@Service
public class CommentServiceImpl extends AbstractSimpleManagerService<Comment, Long> implements CommentService {
private final CommentRepository commentRepository;
private final PersonService personService;
private final PullRequestsService pullRequestsService;
private final InitProperty initProperty;
public CommentServiceImpl(CommentRepository commentRepository, PersonService personService, PullRequestsService pullRequestsService, InitProperty initProperty) {
super(commentRepository);
this.personService = personService;
this.commentRepository = commentRepository;
this.pullRequestsService = pullRequestsService;
this.initProperty = initProperty;
}
@Override
public Long getLastCommentId() {
return commentRepository.findFirstByOrderByIdDesc().map(Comment::getId).orElse(getInitCommentId());
}
private Long getInitCommentId() {
return initProperty.getStartCommentId() != null ? initProperty.getStartCommentId() : 0L;
}
@Override
public List<Comment> getAllBetweenDate(@NonNull LocalDateTime dateFrom, LocalDateTime dateTo) {
return commentRepository.findByCreateDateBetween(dateFrom, dateTo);
}
@Override
public Comment create(@NonNull Comment comment) {
return commentRepository.save(comment);
}
@Override
public Comment update(Comment comment) {
final Comment oldComment = commentRepository.findById(comment.getId())
.orElseThrow(() -> new NotFoundException("Комментарий не найден"));
if (oldComment.getBitbucketVersion().equals(comment.getBitbucketVersion())) {
oldComment.setBitbucketVersion(comment.getBitbucketVersion());
oldComment.setMessage(oldComment.getMessage());
return commentRepository.save(oldComment);
}
return oldComment;
}
@Override
public List<Comment> getAllById(@NonNull Set<Long> ids) {
return commentRepository.findAllById(ids);
}
}

View File

@ -11,6 +11,10 @@ import org.sadtech.basic.filter.criteria.CriteriaQuery;
import org.sadtech.bot.bitbucketbot.domain.IdAndStatusPr;
import org.sadtech.bot.bitbucketbot.domain.PullRequestStatus;
import org.sadtech.bot.bitbucketbot.domain.ReviewerStatus;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.ConflictPrChange;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.NewPrChange;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.ReviewersPrChange;
import org.sadtech.bot.bitbucketbot.domain.change.pullrequest.UpdatePrChange;
import org.sadtech.bot.bitbucketbot.domain.entity.PullRequest;
import org.sadtech.bot.bitbucketbot.domain.entity.PullRequest_;
import org.sadtech.bot.bitbucketbot.domain.entity.Reviewer;
@ -19,11 +23,13 @@ import org.sadtech.bot.bitbucketbot.domain.util.ReviewerChange;
import org.sadtech.bot.bitbucketbot.exception.UpdateException;
import org.sadtech.bot.bitbucketbot.repository.PullRequestsRepository;
import org.sadtech.bot.bitbucketbot.service.ChangeService;
import org.sadtech.bot.bitbucketbot.service.PersonService;
import org.sadtech.bot.bitbucketbot.service.PullRequestsService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@ -35,16 +41,18 @@ public class PullRequestsServiceImpl extends AbstractSimpleManagerService<PullRe
private final ChangeService changeService;
private final PullRequestsRepository pullRequestsRepository;
private final PersonService personService;
private final FilterService<PullRequest, PullRequestFilter> filterService;
protected PullRequestsServiceImpl(
PullRequestsRepository pullRequestsRepository,
ChangeService changeService,
@Qualifier("pullRequestFilterService") FilterService<PullRequest, PullRequestFilter> pullRequestsFilterService
PersonService personService, @Qualifier("pullRequestFilterService") FilterService<PullRequest, PullRequestFilter> pullRequestsFilterService
) {
super(pullRequestsRepository);
this.changeService = changeService;
this.pullRequestsRepository = pullRequestsRepository;
this.personService = personService;
this.filterService = pullRequestsFilterService;
}
@ -54,14 +62,43 @@ public class PullRequestsServiceImpl extends AbstractSimpleManagerService<PullRe
final PullRequest newPullRequest = pullRequestsRepository.save(pullRequest);
changeService.create(newPullRequest);
changeService.save(
NewPrChange.builder()
.author(newPullRequest.getAuthorLogin())
.description(newPullRequest.getDescription())
.title(newPullRequest.getTitle())
.url(newPullRequest.getUrl())
.telegramIds(getReviewerTelegrams(newPullRequest.getReviewers()))
.build()
);
return newPullRequest;
}
private Set<Long> getReviewerTelegrams(@NonNull List<Reviewer> reviewers) {
return personService.getAllTelegramIdByLogin(
reviewers.stream()
.map(Reviewer::getPersonLogin)
.collect(Collectors.toSet())
);
}
@Override
public PullRequest update(@NonNull PullRequest pullRequest) {
final PullRequest oldPullRequest = findAndFillId(pullRequest);
if (!oldPullRequest.isConflict() && pullRequest.isConflict()) {
changeService.save(
ConflictPrChange.builder()
.name(pullRequest.getTitle())
.url(pullRequest.getUrl())
.telegramIds(
personService.getAllTelegramIdByLogin(Collections.singleton(pullRequest.getAuthorLogin()))
)
.build()
);
}
oldPullRequest.setBitbucketVersion(pullRequest.getBitbucketVersion());
oldPullRequest.setConflict(pullRequest.isConflict());
oldPullRequest.setTitle(pullRequest.getTitle());
@ -71,7 +108,14 @@ public class PullRequestsServiceImpl extends AbstractSimpleManagerService<PullRe
final PullRequest newPullRequest = pullRequestsRepository.save(oldPullRequest);
if (!pullRequest.getBitbucketVersion().equals(newPullRequest.getBitbucketVersion())) {
changeService.createUpdatePr(pullRequest, newPullRequest);
changeService.save(
UpdatePrChange.builder()
.author(oldPullRequest.getAuthorLogin())
.name(newPullRequest.getTitle())
.telegramIds(getReviewerTelegrams(newPullRequest.getReviewers()))
.url(newPullRequest.getUrl())
.build()
);
}
return newPullRequest;
@ -79,21 +123,21 @@ public class PullRequestsServiceImpl extends AbstractSimpleManagerService<PullRe
private void updateReviewers(PullRequest oldPullRequest, PullRequest newPullRequest) {
final Map<String, Reviewer> oldReviewers = oldPullRequest.getReviewers().stream()
.collect(Collectors.toMap(Reviewer::getUserLogin, reviewer -> reviewer));
.collect(Collectors.toMap(Reviewer::getPersonLogin, reviewer -> reviewer));
final Map<String, Reviewer> newReviewers = newPullRequest.getReviewers().stream()
.collect(Collectors.toMap(Reviewer::getUserLogin, reviewer -> reviewer));
.collect(Collectors.toMap(Reviewer::getPersonLogin, reviewer -> reviewer));
final List<ReviewerChange> reviewerChanges = new ArrayList<>();
for (Reviewer newReviewer : newReviewers.values()) {
if (oldReviewers.containsKey(newReviewer.getUserLogin())) {
final Reviewer oldReviewer = oldReviewers.get(newReviewer.getUserLogin());
if (oldReviewers.containsKey(newReviewer.getPersonLogin())) {
final Reviewer oldReviewer = oldReviewers.get(newReviewer.getPersonLogin());
final ReviewerStatus oldStatus = oldReviewer.getStatus();
final ReviewerStatus newStatus = newReviewer.getStatus();
if (!oldStatus.equals(newStatus)) {
reviewerChanges.add(ReviewerChange.ofOld(oldReviewer.getUserLogin(), oldStatus, newStatus));
reviewerChanges.add(ReviewerChange.ofOld(oldReviewer.getPersonLogin(), oldStatus, newStatus));
oldReviewer.setStatus(newStatus);
}
} else {
reviewerChanges.add(ReviewerChange.ofNew(newReviewer.getUserLogin(), newReviewer.getStatus()));
reviewerChanges.add(ReviewerChange.ofNew(newReviewer.getPersonLogin(), newReviewer.getStatus()));
newReviewer.setPullRequest(oldPullRequest);
oldPullRequest.getReviewers().add(newReviewer);
}
@ -103,13 +147,22 @@ public class PullRequestsServiceImpl extends AbstractSimpleManagerService<PullRe
reviewerChanges.addAll(
oldReviewers.entrySet().stream()
.filter(e -> oldIds.contains(e.getKey()))
.map(e -> ReviewerChange.ofDeleted(e.getValue().getUserLogin()))
.map(e -> ReviewerChange.ofDeleted(e.getValue().getPersonLogin()))
.collect(Collectors.toList())
);
oldPullRequest.getReviewers()
.removeIf(reviewer -> oldIds.contains(reviewer.getUserLogin()));
.removeIf(reviewer -> oldIds.contains(reviewer.getPersonLogin()));
if (!reviewerChanges.isEmpty()) {
changeService.createReviewersPr(newPullRequest.getTitle(), newPullRequest.getUrl(), newPullRequest.getAuthorLogin(), reviewerChanges);
changeService.save(
ReviewersPrChange.builder()
.title(newPullRequest.getTitle())
.url(newPullRequest.getUrl())
.telegramIds(
personService.getAllTelegramIdByLogin(Collections.singleton(newPullRequest.getAuthorLogin()))
)
.reviewerChanges(reviewerChanges)
.build()
);
}
}

View File

@ -1,8 +1,43 @@
package org.sadtech.bot.bitbucketbot.service.parser;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.sadtech.basic.context.page.Sheet;
import org.sadtech.basic.core.page.PaginationImpl;
import org.sadtech.bot.bitbucketbot.config.InitProperty;
import org.sadtech.bot.bitbucketbot.config.properties.BitbucketProperty;
import org.sadtech.bot.bitbucketbot.config.properties.CommentSchedulerProperty;
import org.sadtech.bot.bitbucketbot.domain.Answer;
import org.sadtech.bot.bitbucketbot.domain.change.comment.AnswerCommentChange;
import org.sadtech.bot.bitbucketbot.domain.change.comment.CommentChange;
import org.sadtech.bot.bitbucketbot.domain.entity.Comment;
import org.sadtech.bot.bitbucketbot.domain.entity.PullRequest;
import org.sadtech.bot.bitbucketbot.domain.entity.Task;
import org.sadtech.bot.bitbucketbot.dto.bitbucket.CommentJson;
import org.sadtech.bot.bitbucketbot.dto.bitbucket.Severity;
import org.sadtech.bot.bitbucketbot.service.ChangeService;
import org.sadtech.bot.bitbucketbot.service.CommentService;
import org.sadtech.bot.bitbucketbot.service.PersonService;
import org.sadtech.bot.bitbucketbot.service.PullRequestsService;
import org.sadtech.bot.bitbucketbot.service.TaskService;
import org.sadtech.bot.bitbucketbot.service.Utils;
import org.sadtech.bot.bitbucketbot.service.executor.DataScan;
import org.sadtech.bot.bitbucketbot.service.executor.ResultScan;
import org.sadtech.bot.bitbucketbot.service.impl.ExecutorScanner;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* <p>Поиск новых комментариев и задач.</p>
* <p>К несчастью, у битбакета не очень удобный API, и у них таска это то же самое что и комментарий, только с флагом</p>
@ -10,168 +45,161 @@ import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class CommentAndTaskParser {
//
// private static final Pattern PATTERN = Pattern.compile("@[\\w]+");
//
// private final CommentService commentService;
// private final PullRequestsService pullRequestsService;
// private final PersonService personService;
// private final ChangeService changeService;
// private final ExecutorScanner executorScanner;
// private final TaskService taskService;
// private final ConversionService conversionService;
//
// private final BitbucketProperty bitbucketProperty;
// private final CommentSchedulerProperty commentSchedulerProperty;
//
// public void scanNewCommentAndTask() {
// long commentId = getLastIdCommentOrTask() + 1;
// int count = 0;
// do {
// final List<DataScan> dataScans = generatingLinksToPossibleComments(commentId);
// executorScanner.registration(dataScans);
// final List<ResultScan> resultScans = executorScanner.getResult();
// if (!resultScans.isEmpty()) {
// processingComments(resultScans);
// processingTasks(resultScans);
// count = 0;
// }
// } while (count++ < commentSchedulerProperty.getNoCommentCount());
// }
//
// private long getLastIdCommentOrTask() {
// return Long.max(commentService.getLastCommentId(), taskService.getLastTaskId());
// }
//
// private void processingComments(List<ResultScan> resultScans) {
// final List<Comment> newComments = commentService.createAll(getCommentsByResultScan(resultScans));
// newComments.forEach(this::notificationPersonal);
// }
//
// private void processingTasks(List<ResultScan> resultScans) {
// final List<Task> newTasks = taskService.createAll(getTaskByResultScan(resultScans));
// newTasks.forEach(this::notificationNewTask);
// }
//
// private List<DataScan> generatingLinksToPossibleComments(@NonNull Long commentId) {
// List<DataScan> commentUrls = new ArrayList<>();
// for (int i = 0; i < 5; i++) {
// int page = 0;
// Page<PullRequest> pullRequestPage = pullRequestsService.getAll(
// Pagination.of(page, commentSchedulerProperty.getCommentCount())
// );
// while (pullRequestPage.hasContent()) {
// long finalCommentId = commentId;
// commentUrls.addAll(pullRequestPage.getContent().stream()
// .map(
// pullRequest -> new DataScan(
// getCommentUrl(finalCommentId, pullRequest),
// pullRequest.getId()
// )
// )
// .collect(Collectors.toList()));
// pullRequestPage = pullRequestsService.getAll(
// Pagination.of(++page, commentSchedulerProperty.getCommentCount())
// );
// }
// commentId++;
// }
// return commentUrls;
// }
//
// private List<Comment> getCommentsByResultScan(List<ResultScan> resultScans) {
// return resultScans.stream()
// .filter(resultScan -> Severity.NORMAL.equals(resultScan.getCommentJson().getSeverity()))
// .map(resultScan -> conversionService.convert(resultScan, Comment.class))
// .collect(Collectors.toList());
// }
//
// private List<Task> getTaskByResultScan(List<ResultScan> resultScans) {
// return resultScans.stream()
// .filter(commentJson -> Severity.BLOCKER.equals(commentJson.getCommentJson().getSeverity()))
// .map(resultScan -> conversionService.convert(resultScan, Task.class))
// .collect(Collectors.toList());
// }
//
// private String getCommentUrl(long commentId, PullRequest pullRequest) {
// return bitbucketProperty.getUrlPullRequestComment()
// .replace("{projectKey}", pullRequest.getProjectKey())
// .replace("{repositorySlug}", pullRequest.getRepositorySlug())
// .replace("{pullRequestId}", pullRequest.getBitbucketId().toString())
// .replace("{commentId}", String.valueOf(commentId));
// }
//
// private void notificationPersonal(@NonNull Comment comment) {
// Matcher matcher = PATTERN.matcher(comment.getMessage());
// Set<String> recipientsLogins = new HashSet<>();
// while (matcher.find()) {
// final String login = matcher.group(0).replace("@", "");
// recipientsLogins.add(login);
// }
// final Set<Long> recipientsIds = personService.getAllTelegramIdByLogin(recipientsLogins);
// changeService.add(
// CommentChange.builder()
// .authorName(comment.getAuthor().getLogin())
// .url(comment.getUrl())
// .telegramIds(recipientsIds)
// .message(comment.getMessage())
// .build()
// );
// }
//
// private void notificationNewTask(@NonNull Task task) {
// changeService.add(
// TaskChange.builder()
// .authorName(task.getAuthor().getFullName())
// .messageTask(task.getDescription())
// .type(ChangeType.NEW_TASK)
// .url(task.getUrl())
// .telegramIds(Collections.singleton(task.getPullRequest().getAuthor().getTelegramId()))
// .build()
// );
// }
//
// public void scanOldComment() {
// @NonNull final List<Comment> comments = commentService.getAllBetweenDate(
// LocalDateTime.now().minusDays(10), LocalDateTime.now()
// );
// for (Comment oldComment : comments) {
// final Optional<CommentJson> optCommentJson = Utils.urlToJson(
// oldComment.getUrl(),
// bitbucketProperty.getToken(),
// CommentJson.class
// );
// final Comment newComment = commentService.update(conversionService.convert(oldComment, Comment.class));
//
// if (optCommentJson.isPresent()) {
// final CommentJson commentJson = optCommentJson.get();
// notifyNewCommentAnswers(oldComment, newComment);
// }
// }
// }
//
// private void notifyNewCommentAnswers(Comment oldComment, Comment newComment) {
// final Set<Long> oldAnswerIds = oldComment.getAnswers();
// final Set<Long> newAnswerIds = newComment.getAnswers();
// if (!newAnswerIds.isEmpty()) {
// final List<Comment> newAnswers = commentService.getAllById(newAnswerIds).stream()
// .filter(comment -> !oldAnswerIds.contains(comment.getId()))
// .collect(Collectors.toList());
// changeService.add(
// AnswerCommentChange.builder()
// .telegramIds(
// Collections.singleton(newComment.getAuthor().getTelegramId())
// )
// .url(newComment.getPullRequest().getUrl())
// .youMessage(newComment.getMessage())
// .answers(
// newAnswers.stream()
// .map(comment -> Answer.of(comment.getAuthor().getFullName(), comment.getMessage()))
// .collect(Collectors.toList())
// )
// .build()
// );
// }
// }
private static final Pattern PATTERN = Pattern.compile("@[\\w]+");
private final CommentService commentService;
private final PullRequestsService pullRequestsService;
private final PersonService personService;
private final ChangeService changeService;
private final ExecutorScanner executorScanner;
private final TaskService taskService;
private final ConversionService conversionService;
private final BitbucketProperty bitbucketProperty;
private final CommentSchedulerProperty commentSchedulerProperty;
private final InitProperty initProperty;
public void scanNewCommentAndTask() {
long commentId = getLastIdCommentOrTask() + 1;
int count = 0;
do {
final List<DataScan> dataScans = generatingLinksToPossibleComments(commentId);
executorScanner.registration(dataScans);
final List<ResultScan> resultScans = executorScanner.getResult();
if (!resultScans.isEmpty()) {
processingComments(resultScans);
processingTasks(resultScans);
count = 0;
}
} while (count++ < commentSchedulerProperty.getNoCommentCount());
}
private long getLastIdCommentOrTask() {
Long commentStartId = Long.max(commentService.getLastCommentId(), taskService.getLastTaskId());
if (commentStartId == 0L && initProperty != null) {
commentStartId = initProperty.getStartCommentId();
}
return commentStartId;
}
private void processingComments(List<ResultScan> resultScans) {
final List<Comment> newComments = commentService.createAll(getCommentsByResultScan(resultScans));
newComments.forEach(this::notificationPersonal);
}
private void processingTasks(List<ResultScan> resultScans) {
final List<Task> newTasks = taskService.createAll(getTaskByResultScan(resultScans));
newTasks.forEach(changeService::createTask);
}
private List<DataScan> generatingLinksToPossibleComments(@NonNull Long commentId) {
List<DataScan> commentUrls = new ArrayList<>();
for (int i = 0; i < 5; i++) {
int page = 0;
Sheet<PullRequest> pullRequestPage = pullRequestsService.getAll(
PaginationImpl.of(page, commentSchedulerProperty.getCommentCount())
);
while (pullRequestPage.hasContent()) {
long finalCommentId = commentId;
commentUrls.addAll(pullRequestPage.getContent().stream()
.map(
pullRequest -> new DataScan(
getCommentUrl(finalCommentId, pullRequest),
pullRequest.getId()
)
)
.collect(Collectors.toList()));
pullRequestPage = pullRequestsService.getAll(
PaginationImpl.of(++page, commentSchedulerProperty.getCommentCount())
);
}
commentId++;
}
return commentUrls;
}
private List<Comment> getCommentsByResultScan(List<ResultScan> resultScans) {
return resultScans.stream()
.filter(resultScan -> Severity.NORMAL.equals(resultScan.getCommentJson().getSeverity()))
.map(resultScan -> conversionService.convert(resultScan, Comment.class))
.collect(Collectors.toList());
}
private List<Task> getTaskByResultScan(List<ResultScan> resultScans) {
return resultScans.stream()
.filter(commentJson -> Severity.BLOCKER.equals(commentJson.getCommentJson().getSeverity()))
.map(resultScan -> conversionService.convert(resultScan, Task.class))
.collect(Collectors.toList());
}
private String getCommentUrl(long commentId, PullRequest pullRequest) {
return bitbucketProperty.getUrlPullRequestComment()
.replace("{projectKey}", pullRequest.getProjectKey())
.replace("{repositorySlug}", pullRequest.getRepositorySlug())
.replace("{pullRequestId}", pullRequest.getBitbucketId().toString())
.replace("{commentId}", String.valueOf(commentId));
}
private void notificationPersonal(@NonNull Comment comment) {
Matcher matcher = PATTERN.matcher(comment.getMessage());
Set<String> recipientsLogins = new HashSet<>();
while (matcher.find()) {
final String login = matcher.group(0).replace("@", "");
recipientsLogins.add(login);
}
final Set<Long> recipientsIds = personService.getAllTelegramIdByLogin(recipientsLogins);
changeService.createCommentChange(
CommentChange.builder()
.authorName(comment.getAuthor())
.url(comment.getUrl())
.telegramIds(recipientsIds)
.message(comment.getMessage())
.build()
);
}
public void scanOldComment() {
@NonNull final List<Comment> comments = commentService.getAllBetweenDate(
LocalDateTime.now().minusDays(10), LocalDateTime.now()
);
for (Comment oldComment : comments) {
final Optional<CommentJson> optCommentJson = Utils.urlToJson(
oldComment.getUrl(),
bitbucketProperty.getToken(),
CommentJson.class
);
final Comment newComment = commentService.update(conversionService.convert(oldComment, Comment.class));
if (optCommentJson.isPresent()) {
final CommentJson commentJson = optCommentJson.get();
notifyNewCommentAnswers(oldComment, newComment);
}
}
}
private void notifyNewCommentAnswers(Comment oldComment, Comment newComment) {
final Set<Long> oldAnswerIds = oldComment.getAnswers();
final Set<Long> newAnswerIds = newComment.getAnswers();
if (!newAnswerIds.isEmpty()) {
final List<Comment> newAnswers = commentService.getAllById(newAnswerIds).stream()
.filter(comment -> !oldAnswerIds.contains(comment.getId()))
.collect(Collectors.toList());
changeService.save(
AnswerCommentChange.builder()
.telegramIds(
personService.getAllTelegramIdByLogin(Collections.singleton(newComment.getAuthor()))
)
.url(newComment.getPullRequestId().toString())
.youMessage(newComment.getMessage())
.answers(
newAnswers.stream()
.map(answerComment -> Answer.of(answerComment.getAuthor(), answerComment.getMessage()))
.collect(Collectors.toList())
)
.build()
);
}
}
}

View File

@ -23,7 +23,7 @@ bitbucketbot:
no-comment-count: 20
comment-count: 100
init:
start-comment-id: 5947
start-comment-id: 7623
server-send:
url: http://188.225.35.149:8080/api/send
bitbucket:

View File

@ -65,17 +65,17 @@
</changeSet>
<changeSet id="2020-09-06-create-table-pull-request-reviewer" author="upagge">
<createTable tableName="pull_request_reviewer">
<createTable tableName="reviewer">
<column name="id" type="integer" autoIncrement="true">
<constraints nullable="false" primaryKey="true"/>
</column>
<column name="pull_request_id" type="integer">
<constraints nullable="false" foreignKeyName="pull_request_reviewer_pull_request_id_pull_request_id"
<constraints nullable="false" foreignKeyName="reviewer_pull_request_id_pull_request_id"
references="pull_request(id)" deleteCascade="true"/>
</column>
<column name="user_login" type="varchar(64)">
<column name="person_login" type="varchar(64)">
<constraints nullable="false"
foreignKeyName="pull_request_reviewer_user_id_user_login"
foreignKeyName="reviewer_person_login_id_person_login"
references="person(login)" deleteCascade="true"/>
</column>
<column name="status" type="varchar(50)">
@ -83,21 +83,21 @@
</column>
</createTable>
<addUniqueConstraint tableName="pull_request_reviewer" columnNames="pull_request_id, user_login"/>
<addUniqueConstraint tableName="reviewer" columnNames="pull_request_id, person_login"/>
</changeSet>
<changeSet id="2020-09-06-create-table-comments" author="upagge">
<createTable tableName="pull_request_comment">
<createTable tableName="comment">
<column name="id" type="int">
<constraints primaryKey="true"/>
</column>
<column name="url" type="varchar(300)"/>
<column name="author_login" type="varchar(64)">
<constraints nullable="false" foreignKeyName="pull_request_task_author_login_person_login"
<constraints nullable="false" foreignKeyName="task_author_login_person_login"
references="person(login)" deleteCascade="true"/>
</column>
<column name="pull_request_id" type="integer">
<constraints nullable="false" foreignKeyName="pull_request_comment_pull_request_id_pull_request_id"
<constraints nullable="false" foreignKeyName="comment_pull_request_id_pull_request_id"
references="pull_request(id)" deleteCascade="true"/>
</column>
<column name="message" type="varchar(500)"/>
@ -113,13 +113,13 @@
<changeSet id="2020-09-06-create-table-comment-tree" author="upagge">
<createTable tableName="comment_tree">
<column name="parent_id" type="int">
<constraints foreignKeyName="comment_tree_parent_id_pull_request_comment_id"
references="pull_request_comment(id)" nullable="false"
<constraints foreignKeyName="comment_tree_parent_id_comment_id"
references="comment(id)" nullable="false"
deleteCascade="true"/>
</column>
<column name="child_id" type="int">
<constraints foreignKeyName="comment_tree_child_id_pull_request_comment_id"
references="pull_request_comment(id)" nullable="false"
<constraints foreignKeyName="comment_tree_child_id_comment_id"
references="comment(id)" nullable="false"
deleteCascade="true"/>
</column>
</createTable>
@ -128,7 +128,7 @@
</changeSet>
<changeSet id="2020-09-06-create-table-task" author="upagge">
<createTable tableName="pull_request_task">
<createTable tableName="task">
<column name="id" type="integer" autoIncrement="true">
<constraints nullable="false" primaryKey="true"/>
</column>
@ -145,11 +145,11 @@
<constraints nullable="false"/>
</column>
<column name="author_login" type="varchar(64)">
<constraints nullable="false" foreignKeyName="pull_request_task_author_login_person_login"
<constraints nullable="false" foreignKeyName="task_author_login_person_login"
references="person(login)" deleteCascade="true"/>
</column>
<column name="pull_request_id" type="int">
<constraints nullable="true" foreignKeyName="pull_request_task_pull_request_id_pull_request_id"
<constraints nullable="true" foreignKeyName="task_pull_request_id_pull_request_id"
references="pull_request(id)" deleteCascade="true"/>
</column>
<column name="create_date" type="datetime">
@ -161,4 +161,18 @@
</createTable>
</changeSet>
<changeSet id="2020-09-08-create-table-" author="">
<createTable tableName="task_comments">
<column name="task_id" type="integer">
<constraints nullable="false" foreignKeyName="task_comments_task_id_task_id" references="task(id)"/>
</column>
<column name="comment_id" type="integer">
<constraints nullable="false" foreignKeyName="task_comments_comment_id_comment_id"
references="comment(id)"/>
</column>
</createTable>
<addPrimaryKey tableName="task_comments" columnNames="task_id, comment_id"/>
</changeSet>
</databaseChangeLog>