diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/scheduler/SchedulerService.java b/bot-app/src/main/java/org/sadtech/bot/gitlab/app/scheduler/SchedulerService.java index 7d15801..54c6eaa 100644 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/scheduler/SchedulerService.java +++ b/bot-app/src/main/java/org/sadtech/bot/gitlab/app/scheduler/SchedulerService.java @@ -3,6 +3,7 @@ package org.sadtech.bot.gitlab.app.scheduler; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.sadtech.bot.gitlab.context.service.CleanService; +import org.sadtech.bot.gitlab.core.service.parser.DiscussionParser; import org.sadtech.bot.gitlab.core.service.parser.MergeRequestParser; import org.sadtech.bot.gitlab.core.service.parser.NoteParser; import org.sadtech.bot.gitlab.core.service.parser.PipelineParser; @@ -23,6 +24,7 @@ public class SchedulerService { private final MergeRequestParser mergeRequestParser; private final NoteParser noteParser; private final CleanService cleanService; + private final DiscussionParser discussionParser; @Scheduled(cron = "*/30 * * * * *") public void newMergeRequest() { @@ -35,13 +37,8 @@ public class SchedulerService { } @Scheduled(cron = "*/30 * * * * *") - public void newNoteParser() { - noteParser.scanNewCommentAndTask(); - } - - @Scheduled(cron = "*/30 * * * * *") - public void oldTaskParser() { - noteParser.scanOldTask(); + public void newDiscussion() { + discussionParser.scanNewDiscussion(); } @Scheduled(cron = "*/30 * * * * *") diff --git a/bot-app/src/main/resources/application.yaml b/bot-app/src/main/resources/application.yaml index 5517a6c..744944f 100644 --- a/bot-app/src/main/resources/application.yaml +++ b/bot-app/src/main/resources/application.yaml @@ -39,4 +39,6 @@ gitlab-bot: url-note-api: "${GITLAB_URL}/api/v4/projects/{0,number,#}/merge_requests/{1,number,#}/notes/{2,number,#}" url-pipelines: "${GITLAB_URL}/api/v4/projects/{0,number,#}/pipelines?&page={1,number,#}&per_page=100" url-pipeline: "${GITLAB_URL}/api/v4/projects/{0,number,#}/pipelines/{1,number,#}" - url-commit: "${GITLAB_URL}/api/v4/projects/{0,number,#}/merge_requests/{1,number,#}/commits?&page=1&per_page=1" \ No newline at end of file + url-commit: "${GITLAB_URL}/api/v4/projects/{0,number,#}/merge_requests/{1,number,#}/commits?&page=1&per_page=1" + url-new-note: "${GITLAB_URL}/api/v4/projects/{0,number,#}/merge_requests/{1,number,#}/discussions/{2}/notes?body={3}" + url-discussion: "${GITLAB_URL}/api/v4/projects/{0,number,#}/merge_requests/{1,number,#}/discussions?&page={2,number,integer}&per_page=100" \ No newline at end of file diff --git a/bot-app/src/main/resources/liquibase/v.1.0.0/2021-01-14-create-tables.xml b/bot-app/src/main/resources/liquibase/v.1.0.0/2021-01-14-create-tables.xml index 888a700..a48c898 100644 --- a/bot-app/src/main/resources/liquibase/v.1.0.0/2021-01-14-create-tables.xml +++ b/bot-app/src/main/resources/liquibase/v.1.0.0/2021-01-14-create-tables.xml @@ -117,6 +117,28 @@ + + + + + + + + + + + + + + + + + + + + + @@ -149,22 +171,10 @@ - - - - - - - - - - + + - - @@ -186,6 +196,9 @@ + + + diff --git a/bot-app/src/main/resources/liquibase/v.1.0.0/2021-02-05-edit-pipelines.xml b/bot-app/src/main/resources/liquibase/v.1.0.0/2021-02-05-edit-pipelines.xml deleted file mode 100644 index 6fdb000..0000000 --- a/bot-app/src/main/resources/liquibase/v.1.0.0/2021-02-05-edit-pipelines.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/bot-app/src/main/resources/liquibase/v.1.0.0/cumulative.xml b/bot-app/src/main/resources/liquibase/v.1.0.0/cumulative.xml index ded14d1..f4fa8c2 100644 --- a/bot-app/src/main/resources/liquibase/v.1.0.0/cumulative.xml +++ b/bot-app/src/main/resources/liquibase/v.1.0.0/cumulative.xml @@ -5,6 +5,5 @@ - \ No newline at end of file diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Discussion.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Discussion.java new file mode 100644 index 0000000..dac9485 --- /dev/null +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Discussion.java @@ -0,0 +1,57 @@ +package org.sadtech.bot.gitlab.context.domain.entity; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import org.sadtech.haiti.context.domain.BasicEntity; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import java.util.List; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +@Getter +@Setter +@Entity +@Table(name = "discussion") +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +public class Discussion implements BasicEntity { + + @Id + @Column(name = "id") + private String id; + + @ManyToOne() + @JoinTable( + name = "discussion_merge_request", + joinColumns = @JoinColumn(name = "discussion_id"), + inverseJoinColumns = @JoinColumn(name = "merge_request_id") + ) + private MergeRequest mergeRequest; + + @OneToMany( + mappedBy = "discussion", + cascade = { + CascadeType.PERSIST, + CascadeType.MERGE + } + ) + private List notes; + + public void setNotes(List notes) { + notes.forEach(note -> note.setDiscussion(this)); + this.notes = notes; + } + +} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/MergeRequest.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/MergeRequest.java index 3101388..dafeb71 100644 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/MergeRequest.java +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/MergeRequest.java @@ -12,17 +12,12 @@ import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; -import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; import javax.persistence.Table; import java.time.LocalDateTime; -import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; /** @@ -95,8 +90,4 @@ public class MergeRequest implements BasicEntity { @Column(name = "date_last_commit") private LocalDateTime dateLastCommit; - @JoinTable - @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true) - private List notes = new ArrayList<>(); - } diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Note.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Note.java index 2cf9cb4..6750f07 100644 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Note.java +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Note.java @@ -6,14 +6,9 @@ import lombok.Setter; import org.sadtech.haiti.context.domain.BasicEntity; import javax.persistence.Column; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.time.LocalDateTime; @@ -23,9 +18,6 @@ import java.time.LocalDateTime; @Entity @Table(name = "note") @EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Inheritance(strategy = InheritanceType.SINGLE_TABLE) -@DiscriminatorColumn(name = "resolvable") -@DiscriminatorValue("false") public class Note implements BasicEntity { @Id @@ -63,12 +55,19 @@ public class Note implements BasicEntity { @Column(name = "web_url") private String webUrl; + @Column(name = "resolved") + private Boolean resolved; + @ManyToOne - @JoinTable( - name = "merge_request_notes", - joinColumns = @JoinColumn(name = "notes_id"), - inverseJoinColumns = @JoinColumn(name = "merge_request_id") - ) - private MergeRequest mergeRequest; + @JoinColumn(name = "resolved_id") + private Person resolvedBy; + + @ManyToOne + @JoinColumn(name = "responsible_id") + private Person responsible; + + @ManyToOne(optional = false) + @JoinColumn(name = "discussion_id") + private Discussion discussion; } diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Task.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Task.java deleted file mode 100644 index 53d9982..0000000 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Task.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.sadtech.bot.gitlab.context.domain.entity; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -import javax.persistence.Column; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - -@Entity -@Getter -@Setter -@DiscriminatorValue("true") -@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true) -public class Task extends Note { - - @Column(name = "resolved") - private Boolean resolved; - - @ManyToOne - @JoinColumn(name = "resolved_id") - private Person resolvedBy; - - @ManyToOne - @JoinColumn(name = "responsible_id") - private Person responsible; - -} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/DiscussionRepository.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/DiscussionRepository.java new file mode 100644 index 0000000..4c83096 --- /dev/null +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/DiscussionRepository.java @@ -0,0 +1,13 @@ +package org.sadtech.bot.gitlab.context.repository; + +import org.sadtech.bot.gitlab.context.domain.entity.Discussion; +import org.sadtech.haiti.context.repository.SimpleManagerRepository; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +public interface DiscussionRepository extends SimpleManagerRepository { + +} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/NoteRepository.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/NoteRepository.java index 13bcfbe..f1f558f 100644 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/NoteRepository.java +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/NoteRepository.java @@ -2,8 +2,12 @@ package org.sadtech.bot.gitlab.context.repository; import lombok.NonNull; import org.sadtech.bot.gitlab.context.domain.entity.Note; +import org.sadtech.haiti.context.page.Pagination; +import org.sadtech.haiti.context.page.Sheet; import org.sadtech.haiti.context.repository.SimpleManagerRepository; +import java.util.List; + /** * // TODO: 08.09.2020 Добавить описание. * @@ -11,6 +15,8 @@ import org.sadtech.haiti.context.repository.SimpleManagerRepository; */ public interface NoteRepository extends SimpleManagerRepository { - void link(@NonNull Long noteId, @NonNull Long mergeRequestId); + Sheet findAllByResolved(boolean resolved, @NonNull Pagination pagination); + + List findAllByResponsibleIdAndResolved(@NonNull Long userId, boolean resolved); } diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/TaskRepository.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/TaskRepository.java deleted file mode 100644 index a803a2e..0000000 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/TaskRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.sadtech.bot.gitlab.context.repository; - -import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.haiti.context.page.Pagination; -import org.sadtech.haiti.context.page.Sheet; -import org.sadtech.haiti.context.repository.SimpleManagerRepository; - -import java.util.List; - -public interface TaskRepository extends SimpleManagerRepository { - - Sheet findAllByResolved(boolean resolved, @NonNull Pagination pagination); - - List findAllByResponsibleIdAndResolved(@NonNull Long userId, boolean resolved); - -} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/DiscussionService.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/DiscussionService.java new file mode 100644 index 0000000..1e1110d --- /dev/null +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/DiscussionService.java @@ -0,0 +1,18 @@ +package org.sadtech.bot.gitlab.context.service; + +import lombok.NonNull; +import org.sadtech.bot.gitlab.context.domain.entity.Discussion; +import org.sadtech.haiti.context.service.SimpleManagerService; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +public interface DiscussionService extends SimpleManagerService { + + void answer(@NonNull String discussionId, @NonNull String text); + + void linkMergeRequest(@NonNull String discussionId, @NonNull Long mergeRequestId); + +} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/NoteService.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/NoteService.java index 06237f4..c70f94f 100644 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/NoteService.java +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/NoteService.java @@ -2,10 +2,16 @@ package org.sadtech.bot.gitlab.context.service; import lombok.NonNull; import org.sadtech.bot.gitlab.context.domain.entity.Note; +import org.sadtech.haiti.context.page.Pagination; +import org.sadtech.haiti.context.page.Sheet; import org.sadtech.haiti.context.service.SimpleManagerService; +import java.util.List; + public interface NoteService extends SimpleManagerService { - void link(@NonNull Long noteId, Long mergeRequestId); + Sheet getAllByResolved(boolean resolved, @NonNull Pagination pagination); + + List getAllPersonTask(@NonNull Long userId, boolean resolved); } diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/TaskService.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/TaskService.java deleted file mode 100644 index 40ab0cf..0000000 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/TaskService.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.sadtech.bot.gitlab.context.service; - -import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.haiti.context.page.Pagination; -import org.sadtech.haiti.context.page.Sheet; -import org.sadtech.haiti.context.service.SimpleManagerService; - -import java.util.List; - -public interface TaskService extends SimpleManagerService { - - Sheet getAllByResolved(boolean resolved, @NonNull Pagination pagination); - - List getAllPersonTask(@NonNull Long userId, boolean resolved); - -} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/config/properties/GitlabProperty.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/config/properties/GitlabProperty.java index b6080f9..7c97064 100644 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/config/properties/GitlabProperty.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/config/properties/GitlabProperty.java @@ -54,4 +54,8 @@ public class GitlabProperty { private String urlCommit; + private String urlNewNote; + + private String urlDiscussion; + } diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/DiscussionJsonConverter.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/DiscussionJsonConverter.java new file mode 100644 index 0000000..6a30ac9 --- /dev/null +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/DiscussionJsonConverter.java @@ -0,0 +1,33 @@ +package org.sadtech.bot.gitlab.core.service.convert; + +import lombok.RequiredArgsConstructor; +import org.sadtech.bot.gitlab.context.domain.entity.Discussion; +import org.sadtech.bot.gitlab.sdk.domain.DiscussionJson; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +import java.util.stream.Collectors; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +@Component +@RequiredArgsConstructor +public class DiscussionJsonConverter implements Converter { + + private final NoteJsonConvert noteJsonConvert; + + @Override + public Discussion convert(DiscussionJson source) { + final Discussion discussion = new Discussion(); + discussion.setId(source.getId()); + discussion.setNotes( + source.getNotes().stream() + .map(noteJsonConvert::convert) + .collect(Collectors.toList()) + ); + return discussion; + } +} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/NoteJsonConvert.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/NoteJsonConvert.java index 327ad90..30f6240 100644 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/NoteJsonConvert.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/NoteJsonConvert.java @@ -30,6 +30,10 @@ public class NoteJsonConvert implements Converter { note.setNoteableId(source.getNoteableId()); note.setNoteableIid(source.getNoteableIid()); note.setSystem(source.isSystem()); + note.setResolved(source.getResolved()); + if (source.getResolvedBy() != null) { + note.setResolvedBy(personConverter.convert(source.getResolvedBy())); + } return note; } diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/NoteJsonToTaskConvert.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/NoteJsonToTaskConvert.java deleted file mode 100644 index 96178a9..0000000 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/NoteJsonToTaskConvert.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.sadtech.bot.gitlab.core.service.convert; - -import lombok.RequiredArgsConstructor; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.bot.gitlab.sdk.domain.NoteJson; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Component; - -/** - * // TODO: 12.09.2020 Добавить описание. - * - * @author upagge 12.09.2020 - */ -@Component -@RequiredArgsConstructor -public class NoteJsonToTaskConvert implements Converter { - - private final PersonJsonConverter personConverter; - - @Override - public Task convert(NoteJson source) { - final Task task = new Task(); - task.setAuthor(personConverter.convert(source.getAuthor())); - task.setId(source.getId()); - task.setBody(source.getBody()); - task.setType(source.getType()); - task.setNoteableType(source.getNoteableType()); - task.setCreated(source.getCreated()); - task.setUpdated(source.getUpdated()); - task.setNoteableId(source.getNoteableId()); - task.setNoteableIid(source.getNoteableIid()); - task.setSystem(source.isSystem()); - - task.setResolved(source.getResolved()); - if (source.getResolvedBy() != null) { - task.setResolvedBy(personConverter.convert(source.getResolvedBy())); - } - return task; - } - -} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/DiscussionServiceImpl.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/DiscussionServiceImpl.java new file mode 100644 index 0000000..09cb85e --- /dev/null +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/DiscussionServiceImpl.java @@ -0,0 +1,136 @@ +package org.sadtech.bot.gitlab.core.service.impl; + +import lombok.NonNull; +import lombok.extern.slf4j.Slf4j; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.sadtech.bot.gitlab.context.domain.PersonInformation; +import org.sadtech.bot.gitlab.context.domain.entity.Discussion; +import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest; +import org.sadtech.bot.gitlab.context.domain.entity.Note; +import org.sadtech.bot.gitlab.context.domain.notify.comment.CommentNotify; +import org.sadtech.bot.gitlab.context.repository.DiscussionRepository; +import org.sadtech.bot.gitlab.context.service.DiscussionService; +import org.sadtech.bot.gitlab.context.service.NotifyService; +import org.sadtech.bot.gitlab.core.config.properties.GitlabProperty; +import org.sadtech.bot.gitlab.core.config.properties.PersonProperty; +import org.sadtech.haiti.context.exception.NotFoundException; +import org.sadtech.haiti.core.service.AbstractSimpleManagerService; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.text.MessageFormat; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.sadtech.haiti.utils.network.HttpParse.AUTHORIZATION; +import static org.sadtech.haiti.utils.network.HttpParse.BEARER; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +@Slf4j +@Service +public class DiscussionServiceImpl extends AbstractSimpleManagerService implements DiscussionService { + + protected static final Pattern PATTERN = Pattern.compile("@[\\w]+"); + + private final DiscussionRepository discussionRepository; + private final PersonInformation personInformation; + + private final OkHttpClient client = new OkHttpClient(); + private final GitlabProperty gitlabProperty; + private final PersonProperty personProperty; + private final NotifyService notifyService; + + public DiscussionServiceImpl(DiscussionRepository discussionRepository, PersonInformation personInformation, GitlabProperty gitlabProperty, PersonProperty personProperty, NotifyService notifyService) { + super(discussionRepository); + this.discussionRepository = discussionRepository; + this.personInformation = personInformation; + this.gitlabProperty = gitlabProperty; + this.personProperty = personProperty; + this.notifyService = notifyService; + } + + @Override + public Discussion create(@NonNull Discussion discussion) { + discussion.getNotes().forEach(this::notificationPersonal); + return discussionRepository.save(discussion); + } + + @Override + public Discussion update(@NonNull Discussion discussion) { + final Map noteMap = discussionRepository.findById(discussion.getId()).orElseThrow(() -> new NotFoundException("Дискуссия не найдена")) + .getNotes().stream() + .collect(Collectors.toMap(Note::getId, note -> note)); + + discussion.getNotes().forEach(note -> updateNote(note, noteMap)); + + return discussionRepository.save(discussion); + } + + private void updateNote(Note note, Map noteMap) { + if (noteMap.containsKey(note.getId())) { + final Note oldNote = noteMap.get(note.getId()); + if (!oldNote.getUpdated().equals(note.getUpdated())) { + note.setWebUrl(oldNote.getWebUrl()); + } + } + } + + + @Override + public void answer(@NonNull String discussionId, @NonNull String text) { + final Discussion discussion = discussionRepository.findById(discussionId) + .orElseThrow(() -> new org.sadtech.haiti.context.exception.NotFoundException("Note " + discussionId + " не найдена")); + final MergeRequest mergeRequest = discussion.getMergeRequest(); + final Long projectId = mergeRequest.getProjectId(); + + final String requestUrl = MessageFormat.format(gitlabProperty.getUrlNewNote(), projectId, mergeRequest.getTwoId(), discussion.getId(), text); + + Request request = new Request.Builder() + .header(AUTHORIZATION, BEARER + personProperty.getToken()) + .url(requestUrl) + .build(); + + try { + final Response execute = client.newCall(request).execute(); + System.out.println(execute.isSuccessful()); + System.out.println(execute.body().toString()); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + + } + + @Override + public void linkMergeRequest(@NonNull String discussionId, @NonNull Long mergeRequestId) { + + } + + protected void notificationPersonal(@NonNull Note note) { + Matcher matcher = PATTERN.matcher(note.getBody()); + Set recipientsLogins = new HashSet<>(); + while (matcher.find()) { + final String login = matcher.group(0).replace("@", ""); + recipientsLogins.add(login); + } + if (recipientsLogins.contains(personInformation.getUsername())) { + notifyService.send( + CommentNotify.builder() + .authorName(note.getAuthor().getName()) + .message(note.getBody()) + .url(note.getWebUrl()) + .build() + ); + } + } + +} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/AbstractNoteService.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/AbstractNoteService.java deleted file mode 100644 index 52083e0..0000000 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/AbstractNoteService.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.sadtech.bot.gitlab.core.service.impl.note; - -import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.PersonInformation; -import org.sadtech.bot.gitlab.context.domain.entity.Note; -import org.sadtech.bot.gitlab.context.domain.notify.comment.CommentNotify; -import org.sadtech.bot.gitlab.context.service.NotifyService; -import org.sadtech.haiti.context.repository.SimpleManagerRepository; -import org.sadtech.haiti.core.service.AbstractSimpleManagerService; - -import java.util.HashSet; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * // TODO: 17.01.2021 Добавить описание. - * - * @author upagge 17.01.2021 - */ -public abstract class AbstractNoteService extends AbstractSimpleManagerService { - - protected static final Pattern PATTERN = Pattern.compile("@[\\w]+"); - - private final NotifyService notifyService; - private final PersonInformation personInformation; - - protected AbstractNoteService( - SimpleManagerRepository repository, - NotifyService notifyService, - PersonInformation personInformation - ) { - super(repository); - this.notifyService = notifyService; - this.personInformation = personInformation; - } - - protected void notificationPersonal(@NonNull Note note) { - Matcher matcher = PATTERN.matcher(note.getBody()); - Set recipientsLogins = new HashSet<>(); - while (matcher.find()) { - final String login = matcher.group(0).replace("@", ""); - recipientsLogins.add(login); - } - if (recipientsLogins.contains(personInformation.getUsername())) { - notifyService.send( - CommentNotify.builder() - .authorName(note.getAuthor().getName()) - .message(note.getBody()) - .url(note.getWebUrl()) - .build() - ); - } - } - -} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/NoteServiceImpl.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/NoteServiceImpl.java index 3166f59..5213f1b 100644 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/NoteServiceImpl.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/NoteServiceImpl.java @@ -1,29 +1,49 @@ package org.sadtech.bot.gitlab.core.service.impl.note; import lombok.NonNull; +import lombok.extern.slf4j.Slf4j; import org.sadtech.bot.gitlab.context.domain.PersonInformation; import org.sadtech.bot.gitlab.context.domain.entity.Note; +import org.sadtech.bot.gitlab.context.domain.notify.comment.CommentNotify; import org.sadtech.bot.gitlab.context.exception.NotFoundException; import org.sadtech.bot.gitlab.context.repository.NoteRepository; import org.sadtech.bot.gitlab.context.service.NoteService; import org.sadtech.bot.gitlab.context.service.NotifyService; import org.sadtech.bot.gitlab.context.service.PersonService; +import org.sadtech.haiti.context.page.Pagination; +import org.sadtech.haiti.context.page.Sheet; +import org.sadtech.haiti.core.service.AbstractSimpleManagerService; import org.springframework.stereotype.Service; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Slf4j @Service -public class NoteServiceImpl extends AbstractNoteService implements NoteService { +public class NoteServiceImpl extends AbstractSimpleManagerService implements NoteService { + + protected static final Pattern PATTERN = Pattern.compile("@[\\w]+"); private final NoteRepository noteRepository; private final PersonService personService; + private final NotifyService notifyService; + private final PersonInformation personInformation; + public NoteServiceImpl( NoteRepository noteRepository, + PersonService personService, NotifyService notifyService, - PersonInformation personInformation, - PersonService personService) { - super(noteRepository, notifyService, personInformation); + PersonInformation personInformation + ) { + super(noteRepository); this.noteRepository = noteRepository; this.personService = personService; + this.notifyService = notifyService; + this.personInformation = personInformation; } @Override @@ -44,40 +64,36 @@ public class NoteServiceImpl extends AbstractNoteService implements NoteSe note.setWebUrl(oldNote.getWebUrl()); return noteRepository.save(note); } -// updateAnswer(oldNote, note); return oldNote; } - private void updateAnswer(Note oldNote, Note newNote) { -// final Set oldAnswerIds = oldNote.getAnswers(); -// final Set newAnswerIds = newNote.getAnswers(); -// if (!oldAnswerIds.equals(newAnswerIds)) { -// final Set existsNewAnswersIds = commentRepository.existsById(newAnswerIds); -// final List newAnswers = commentRepository.findAllById(existsNewAnswersIds).stream() -// .filter(comment -> !oldAnswerIds.contains(comment.getId())) -// .collect(Collectors.toList()); -// oldNote.getAnswers().clear(); -// oldNote.setAnswers(existsNewAnswersIds); -// if (!newAnswers.isEmpty()) { -// notifyService.send( -// AnswerCommentNotify.builder() -// .url(oldNote.getUrl()) -// .youMessage(newNote.getMessage()) -// .answers( -// newAnswers.stream() -// .map(answerComment -> Answer.of(answerComment.getAuthor(), answerComment.getMessage())) -// .collect(Collectors.toList()) -// ) -// .build() -// ); -// } -// } + @Override + public Sheet getAllByResolved(boolean resolved, @NonNull Pagination pagination) { + return noteRepository.findAllByResolved(resolved, pagination); } @Override - public void link(@NonNull Long noteId, @NonNull Long mergeRequestId) { - noteRepository.link(noteId, mergeRequestId); + public List getAllPersonTask(@NonNull Long userId, boolean resolved) { + return noteRepository.findAllByResponsibleIdAndResolved(userId, resolved); + } + + protected void notificationPersonal(@NonNull Note note) { + Matcher matcher = PATTERN.matcher(note.getBody()); + Set recipientsLogins = new HashSet<>(); + while (matcher.find()) { + final String login = matcher.group(0).replace("@", ""); + recipientsLogins.add(login); + } + if (recipientsLogins.contains(personInformation.getUsername())) { + notifyService.send( + CommentNotify.builder() + .authorName(note.getAuthor().getName()) + .message(note.getBody()) + .url(note.getWebUrl()) + .build() + ); + } } } diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/TaskServiceImpl.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/TaskServiceImpl.java deleted file mode 100644 index f1be6b0..0000000 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/note/TaskServiceImpl.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.sadtech.bot.gitlab.core.service.impl.note; - -import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.PersonInformation; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.bot.gitlab.context.domain.notify.task.TaskCloseNotify; -import org.sadtech.bot.gitlab.context.domain.notify.task.TaskNewNotify; -import org.sadtech.bot.gitlab.context.repository.TaskRepository; -import org.sadtech.bot.gitlab.context.service.NotifyService; -import org.sadtech.bot.gitlab.context.service.PersonService; -import org.sadtech.bot.gitlab.context.service.TaskService; -import org.sadtech.haiti.context.exception.NotFoundException; -import org.sadtech.haiti.context.page.Pagination; -import org.sadtech.haiti.context.page.Sheet; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class TaskServiceImpl extends AbstractNoteService implements TaskService { - - private final TaskRepository taskRepository; - private final NotifyService notifyService; - private final PersonInformation personInformation; - private final PersonService personService; - - public TaskServiceImpl( - TaskRepository taskRepository, - NotifyService notifyService, - PersonInformation personInformation, - PersonService personService - ) { - super(taskRepository, notifyService, personInformation); - this.taskRepository = taskRepository; - this.notifyService = notifyService; - this.personInformation = personInformation; - this.personService = personService; - } - - @Override - public Task create(@NonNull Task task) { - createPerson(task); - - final Task newTask = taskRepository.save(task); - notifyNewTask(task); - notificationPersonal(task); - return newTask; - } - - private void createPerson(@NonNull Task task) { - personService.create(task.getAuthor()); - if (task.getResolvedBy() != null) { - personService.create(task.getResolvedBy()); - } - personService.create(task.getResponsible()); - } - - @Override - public Task update(@NonNull Task task) { - final Task oldTask = taskRepository.findById(task.getId()) - .orElseThrow(() -> new NotFoundException("Задача не найдена")); - - task.setMergeRequest(oldTask.getMergeRequest()); - task.setWebUrl(oldTask.getWebUrl()); - task.setResponsible(oldTask.getResponsible()); - - notifyUpdateStatus(oldTask, task); - - return taskRepository.save(task); - - } - - private void notifyUpdateStatus(Task oldTask, Task task) { - if ( - personInformation.getId().equals(oldTask.getAuthor().getId()) - ) { - final boolean oldStatus = oldTask.getResolved(); - final boolean newStatus = task.getResolved(); - if (!oldStatus && newStatus) { - notifyService.send( - TaskCloseNotify.builder() - .authorName(task.getAuthor().getName()) - .messageTask(task.getBody()) - .url(task.getWebUrl()) - .build() - ); - } - } - } - - private void notifyNewTask(Task task) { - if (personInformation.getId().equals(task.getResponsible().getId()) - && !personInformation.getId().equals(task.getAuthor().getId()) - && task.getResolved() != null && !task.getResolved() - ) { - notifyService.send( - TaskNewNotify.builder() - .authorName(task.getAuthor().getName()) - .messageTask(task.getBody()) - .url(task.getWebUrl()) - .build() - ); - } - } - - @Override - public Sheet getAllByResolved(boolean resolved, @NonNull Pagination pagination) { - return taskRepository.findAllByResolved(resolved, pagination); - } - - @Override - public List getAllPersonTask(@NonNull Long userId, boolean resolved) { - return taskRepository.findAllByResponsibleIdAndResolved(userId, resolved); - } - -} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/DiscussionParser.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/DiscussionParser.java new file mode 100644 index 0000000..fd1283e --- /dev/null +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/DiscussionParser.java @@ -0,0 +1,106 @@ +package org.sadtech.bot.gitlab.core.service.parser; + +import lombok.RequiredArgsConstructor; +import org.sadtech.bot.gitlab.context.domain.entity.Discussion; +import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest; +import org.sadtech.bot.gitlab.context.service.DiscussionService; +import org.sadtech.bot.gitlab.context.service.MergeRequestsService; +import org.sadtech.bot.gitlab.core.config.properties.GitlabProperty; +import org.sadtech.bot.gitlab.core.config.properties.PersonProperty; +import org.sadtech.bot.gitlab.sdk.domain.DiscussionJson; +import org.sadtech.haiti.context.domain.ExistsContainer; +import org.sadtech.haiti.context.page.Sheet; +import org.sadtech.haiti.core.page.PaginationImpl; +import org.sadtech.haiti.utils.network.HttpParse; +import org.springframework.core.convert.ConversionService; +import org.springframework.stereotype.Component; + +import java.text.MessageFormat; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.sadtech.haiti.utils.network.HttpParse.ACCEPT; +import static org.sadtech.haiti.utils.network.HttpParse.AUTHORIZATION; +import static org.sadtech.haiti.utils.network.HttpParse.BEARER; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +@Component +@RequiredArgsConstructor +public class DiscussionParser { + + public static final int COUNT = 100; + + private final DiscussionService discussionService; + private final MergeRequestsService mergeRequestsService; + private final ConversionService conversionService; + + private final GitlabProperty gitlabProperty; + private final PersonProperty personProperty; + + public void scanNewDiscussion() { + int page = 0; + Sheet mergeRequestSheet = mergeRequestsService.getAll(PaginationImpl.of(page, COUNT)); + + while (mergeRequestSheet.hasContent()) { + + final List mergeRequests = mergeRequestSheet.getContent(); + for (MergeRequest mergeRequest : mergeRequests) { + + processingMergeRequest(mergeRequest); + + } + + mergeRequestSheet = mergeRequestsService.getAll(PaginationImpl.of(++page, COUNT)); + } + } + + private void processingMergeRequest(MergeRequest mergeRequest) { + int page = 1; + List discussionJson = getDiscussionJson(mergeRequest, page); + + while (!discussionJson.isEmpty()) { + + createNewDiscussion(discussionJson, mergeRequest); + + discussionJson = getDiscussionJson(mergeRequest, ++page); + } + } + + private void createNewDiscussion(List discussionJson, MergeRequest mergeRequest) { + final Set jsonIds = discussionJson.stream() + .map(DiscussionJson::getId) + .collect(Collectors.toSet()); + + final ExistsContainer existsContainer = discussionService.existsById(jsonIds); + if (!existsContainer.isAllFound()) { + final List newDiscussions = discussionJson.stream() + .filter(json -> existsContainer.getIdNoFound().contains(json.getId())) + .map(json -> { + final Discussion discussion = conversionService.convert(json, Discussion.class); + discussion.setMergeRequest(mergeRequest); + discussion.getNotes().forEach( + note -> { + final String url = MessageFormat.format(gitlabProperty.getUrlNote(), mergeRequest.getWebUrl(), note.getId()); + note.setWebUrl(url); + } + ); + return discussion; + }) + .collect(Collectors.toList()); + final List discussions = discussionService.createAll(newDiscussions); + } + } + + private List getDiscussionJson(MergeRequest mergeRequest, int page) { + return HttpParse.request(MessageFormat.format(gitlabProperty.getUrlDiscussion(), mergeRequest.getProjectId(), mergeRequest.getTwoId(), page)) + .header(ACCEPT) + .header(AUTHORIZATION, BEARER + personProperty.getToken()) + .executeList(DiscussionJson.class); + } + +} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/NoteParser.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/NoteParser.java index a9c5a33..5eaee28 100644 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/NoteParser.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/NoteParser.java @@ -1,31 +1,7 @@ package org.sadtech.bot.gitlab.core.service.parser; -import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest; -import org.sadtech.bot.gitlab.context.domain.entity.Note; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.bot.gitlab.context.service.MergeRequestsService; -import org.sadtech.bot.gitlab.context.service.NoteService; -import org.sadtech.bot.gitlab.context.service.TaskService; -import org.sadtech.bot.gitlab.core.config.properties.GitlabProperty; -import org.sadtech.bot.gitlab.core.config.properties.PersonProperty; -import org.sadtech.bot.gitlab.sdk.domain.NoteJson; -import org.sadtech.haiti.context.domain.ExistsContainer; -import org.sadtech.haiti.context.exception.ConvertException; -import org.sadtech.haiti.context.page.Sheet; -import org.sadtech.haiti.core.page.PaginationImpl; -import org.sadtech.haiti.utils.network.HttpParse; -import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Component; -import java.text.MessageFormat; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.sadtech.haiti.utils.network.HttpParse.ACCEPT; -import static org.sadtech.haiti.utils.network.HttpParse.AUTHORIZATION; -import static org.sadtech.haiti.utils.network.HttpParse.BEARER; - /** *

Поиск новых комментариев и задач.

*

К несчастью, у битбакета не очень удобный API, и у них таска это то же самое что и комментарий, только с флагом

@@ -33,216 +9,161 @@ import static org.sadtech.haiti.utils.network.HttpParse.BEARER; @Component public class NoteParser { - public static final int COUNT = 100; - - private final MergeRequestsService mergeRequestsService; - private final ConversionService conversionService; - - private final GitlabProperty gitlabProperty; - private final PersonProperty personProperty; - private final NoteService noteService; - private final TaskService taskService; - - public NoteParser( - MergeRequestsService mergeRequestsService, - ConversionService conversionService, - GitlabProperty gitlabProperty, - PersonProperty personProperty, - NoteService noteService, - TaskService taskService - ) { - this.mergeRequestsService = mergeRequestsService; - this.conversionService = conversionService; - this.gitlabProperty = gitlabProperty; - this.personProperty = personProperty; - this.noteService = noteService; - this.taskService = taskService; - } - - public void scanNewCommentAndTask() { - int page = 0; - Sheet mergeRequestSheet = mergeRequestsService.getAll(PaginationImpl.of(page, COUNT)); - - while (mergeRequestSheet.hasContent()) { - - final List mergeRequests = mergeRequestSheet.getContent(); - for (MergeRequest mergeRequest : mergeRequests) { - - processingMergeRequest(mergeRequest); - - } - - mergeRequestSheet = mergeRequestsService.getAll(PaginationImpl.of(++page, COUNT)); - } - - } - - private void processingMergeRequest(MergeRequest mergeRequest) { - int page = 1; - List noteJsons = getNoteJson(mergeRequest, page); - - while (!noteJsons.isEmpty()) { - - createNewComment(noteJsons, mergeRequest); - createNewTask(noteJsons, mergeRequest); - - noteJsons = getNoteJson(mergeRequest, ++page); - } - } - - private List getNoteJson(MergeRequest mergeRequest, int page) { - return HttpParse.request(MessageFormat.format(gitlabProperty.getUrlPullRequestComment(), mergeRequest.getProjectId(), mergeRequest.getTwoId(), page)) - .header(ACCEPT) - .header(AUTHORIZATION, BEARER + personProperty.getToken()) - .executeList(NoteJson.class) - .stream() - .filter(noteJson -> !noteJson.isSystem()) - .collect(Collectors.toList()); - } - - private void createNewTask(List noteJsons, MergeRequest mergeRequest) { - final List newJsons = noteJsons.stream() - .filter(json -> json.getType() != null) - .collect(Collectors.toList()); - - final Set jsonIds = newJsons.stream() - .map(NoteJson::getId) - .collect(Collectors.toSet()); - - final ExistsContainer existsContainer = taskService.existsById(jsonIds); - - if (!existsContainer.isAllFound()) { - final List newNotes = newJsons.stream() - .filter(json -> existsContainer.getIdNoFound().contains(json.getId())) - .map(json -> conversionService.convert(json, Task.class)) - .peek(task -> { - task.setWebUrl(MessageFormat.format(gitlabProperty.getUrlNote(), mergeRequest.getWebUrl(), task.getId())); - task.setResponsible(mergeRequest.getAuthor()); - } - ) - .collect(Collectors.toList()); - - final Set newNoteIds = newNotes.stream().map(Task::getId).collect(Collectors.toSet()); - - final ExistsContainer existsNoteContainer = noteService.existsById(newNoteIds); - - if (existsContainer.getContainer() != null && !existsContainer.getContainer().isEmpty()) { - noteService.deleteAllById(existsNoteContainer.getContainer().stream().map(Note::getId).collect(Collectors.toSet())); - } - - final List newTasks = taskService.createAll(newNotes); - newTasks.forEach(task -> noteService.link(task.getId(), mergeRequest.getId())); - } - } - - private void createNewComment(List noteJsons, MergeRequest mergeRequest) { - final List newJsons = noteJsons.stream() - .filter(json -> json.getType() == null) - .collect(Collectors.toList()); - - final Set jsonIds = newJsons.stream() - .map(NoteJson::getId) - .collect(Collectors.toSet()); - - final ExistsContainer existsContainer = noteService.existsById(jsonIds); - - if (!existsContainer.isAllFound()) { - final List notes = newJsons.stream() - .filter(json -> existsContainer.getIdNoFound().contains(json.getId())) - .map(json -> conversionService.convert(json, Note.class)) - .peek(note -> note.setWebUrl( - MessageFormat.format(gitlabProperty.getUrlNote(), mergeRequest.getWebUrl(), note.getId())) - ) - .collect(Collectors.toList()); - - final List newNotes = noteService.createAll(notes); - newNotes.forEach(note -> noteService.link(note.getId(), mergeRequest.getId())); - } - - } - - public void scanOldTask() { - int page = 0; - Sheet taskSheet = taskService.getAllByResolved(false, PaginationImpl.of(page, COUNT)); - - while (taskSheet.hasContent()) { - final List tasks = taskSheet.getContent(); - - for (Task task : tasks) { - final MergeRequest mergeRequest = task.getMergeRequest(); - final Task newTask = HttpParse.request(MessageFormat.format( - gitlabProperty.getUrlNoteApi(), - mergeRequest.getProjectId(), - mergeRequest.getTwoId(), - task.getId()) - ) - .header(ACCEPT) - .header(AUTHORIZATION, BEARER + personProperty.getToken()) - .execute(NoteJson.class) - .map(json -> conversionService.convert(json, Task.class)) - .orElseThrow(() -> new ConvertException("Ошибка обработки задачи id: " + task.getId())); - taskService.update(newTask); - } - - taskSheet = taskService.getAllByResolved(false, PaginationImpl.of(++page, COUNT)); - } - - } - -// private List generatingLinksToPossibleComments(@NonNull Long commentId) { -// List commentUrls = new ArrayList<>(); -// for (int i = 0; i < 5; i++) { -// int page = 0; -// Sheet pullRequestPage = mergeRequestsService.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 = mergeRequestsService.getAll( -// PaginationImpl.of(++page, commentSchedulerProperty.getCommentCount()) -// ); +// public static final int COUNT = 100; +// +// private final MergeRequestsService mergeRequestsService; +// private final ConversionService conversionService; +// +// private final GitlabProperty gitlabProperty; +// private final PersonProperty personProperty; +// private final NoteService noteService; +// +// public NoteParser( +// MergeRequestsService mergeRequestsService, +// ConversionService conversionService, +// GitlabProperty gitlabProperty, +// PersonProperty personProperty, +// NoteService noteService +// ) { +// this.mergeRequestsService = mergeRequestsService; +// this.conversionService = conversionService; +// this.gitlabProperty = gitlabProperty; +// this.personProperty = personProperty; +// this.noteService = noteService; +// } +// +// public void scanNewCommentAndTask() { +// int page = 0; +// Sheet mergeRequestSheet = mergeRequestsService.getAll(PaginationImpl.of(page, COUNT)); +// +// while (mergeRequestSheet.hasContent()) { +// +// final List mergeRequests = mergeRequestSheet.getContent(); +// for (MergeRequest mergeRequest : mergeRequests) { +// +// processingMergeRequest(mergeRequest); +// // } -// commentId++; +// +// mergeRequestSheet = mergeRequestsService.getAll(PaginationImpl.of(++page, COUNT)); // } -// return commentUrls; +// // } - -// private List getCommentsByResultScan(List noteJsons) { -// return noteJsons.stream() -// .filter(json -> Severity.NORMAL.equals(json.getSeverity())) -// .map(resultScan -> conversionService.convert(resultScan, Note.class)) -// .peek( -// comment -> { -// final MergeRequestMini mergeRequestMini = mergeRequestsService.getMiniInfo(comment.getPullRequestId()) -// .orElseThrow(() -> new NotFoundException("Автор ПР не найден")); -// comment.setUrl(generateUrl(comment.getId(), mergeRequestMini.getWebUrl())); -// comment.setResponsible(mergeRequestMini.getAuthor()); -// } -// ) +// +// private void processingMergeRequest(MergeRequest mergeRequest) { +// int page = 1; +// List noteJsons = getNoteJson(mergeRequest, page); +// +// while (!noteJsons.isEmpty()) { +// +// createNewComment(noteJsons, mergeRequest); +// +// noteJsons = getNoteJson(mergeRequest, ++page); +// } +// } +// +// private List getNoteJson(MergeRequest mergeRequest, int page) { +// return HttpParse.request(MessageFormat.format(gitlabProperty.getUrlPullRequestComment(), mergeRequest.getProjectId(), mergeRequest.getTwoId(), page)) +// .header(ACCEPT) +// .header(AUTHORIZATION, BEARER + personProperty.getToken()) +// .executeList(NoteJson.class) +// .stream() +// .filter(noteJson -> !noteJson.isSystem()) // .collect(Collectors.toList()); // } -// private List getTaskByResultScan(List noteJsons) { -// return noteJsons.stream() -// .filter(json -> Severity.BLOCKER.equals(json.getSeverity())) -// .map(resultScan -> conversionService.convert(resultScan, Task.class)) -// .peek( -// task -> { -// final MergeRequestMini mergeRequestMini = mergeRequestsService.getMiniInfo(task.getPullRequestId()) -// .orElseThrow(() -> new NotFoundException("Автор ПР не найден")); -// task.setResponsible(mergeRequestMini.getAuthorLogin()); -// task.setUrl(generateUrl(task.getId(), mergeRequestMini.getWebUrl())); -// } -// ) +// private void createNewTask(List noteJsons, MergeRequest mergeRequest) { +// final List newJsons = noteJsons.stream() +// .filter(json -> json.getType() != null) // .collect(Collectors.toList()); +// +// final Set jsonIds = newJsons.stream() +// .map(NoteJson::getId) +// .collect(Collectors.toSet()); +// +// final ExistsContainer existsContainer = taskService.existsById(jsonIds); +// +// if (!existsContainer.isAllFound()) { +// final List newNotes = newJsons.stream() +// .filter(json -> existsContainer.getIdNoFound().contains(json.getId())) +// .map(json -> conversionService.convert(json, Task.class)) +// .peek(task -> { +// task.setWebUrl(MessageFormat.format(gitlabProperty.getUrlNote(), mergeRequest.getWebUrl(), task.getId())); +// task.setResponsible(mergeRequest.getAuthor()); +// } +// ) +// .collect(Collectors.toList()); +// +// final Set newNoteIds = newNotes.stream().map(Task::getId).collect(Collectors.toSet()); +// +// final ExistsContainer existsNoteContainer = noteService.existsById(newNoteIds); +// +// if (existsContainer.getContainer() != null && !existsContainer.getContainer().isEmpty()) { +// noteService.deleteAllById(existsNoteContainer.getContainer().stream().map(Note::getId).collect(Collectors.toSet())); +// } +// +// final List newTasks = taskService.createAll(newNotes); +// newTasks.forEach(task -> noteService.link(task.getId(), mergeRequest.getId())); +// } +// } +// +// private void createNewComment(List noteJsons, MergeRequest mergeRequest) { +// final List newJsons = noteJsons.stream() +// .filter(json -> json.getType() == null) +// .collect(Collectors.toList()); +// +// final Set jsonIds = newJsons.stream() +// .map(NoteJson::getId) +// .collect(Collectors.toSet()); +// +// final ExistsContainer existsContainer = noteService.existsById(jsonIds); +// +// if (!existsContainer.isAllFound()) { +// final List notes = newJsons.stream() +// .filter(json -> existsContainer.getIdNoFound().contains(json.getId())) +// .map(json -> conversionService.convert(json, Note.class)) +// .peek(note -> note.setWebUrl( +// MessageFormat.format(gitlabProperty.getUrlNote(), mergeRequest.getWebUrl(), note.getId())) +// ) +// .collect(Collectors.toList()); +// +// final List newNotes = noteService.createAll(notes); +// newNotes.forEach(note -> noteService.link(note.getId(), mergeRequest.getId())); +// } + +// } + +// public void scanOldTask() { +// int page = 0; +// Sheet taskSheet = taskService.getAllByResolved(false, PaginationImpl.of(page, COUNT)); +// +// while (taskSheet.hasContent()) { +// final List tasks = taskSheet.getContent(); +// +// for (Task task : tasks) { +// final MergeRequest mergeRequest = task.getMergeRequest(); +// // FIXME: 11.02.2021 Костыль, исправить в будущем +// if (mergeRequest!=null) { +// final Task newTask = HttpParse.request(MessageFormat.format( +// gitlabProperty.getUrlNoteApi(), +// mergeRequest.getProjectId(), +// mergeRequest.getTwoId(), +// task.getId()) +// ) +// .header(ACCEPT) +// .header(AUTHORIZATION, BEARER + personProperty.getToken()) +// .execute(NoteJson.class) +// .map(json -> conversionService.convert(json, Task.class)) +// .orElseThrow(() -> new ConvertException("Ошибка обработки задачи id: " + task.getId())); +// taskService.update(newTask); +// } else { +// taskService.deleteById(task.getId()); +// } +// } +// +// taskSheet = taskService.getAllByResolved(false, PaginationImpl.of(++page, COUNT)); +// } +// // } } diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/DiscussionRepositoryImpl.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/DiscussionRepositoryImpl.java new file mode 100644 index 0000000..3dd01d3 --- /dev/null +++ b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/DiscussionRepositoryImpl.java @@ -0,0 +1,21 @@ +package org.sadtech.bot.gitlab.data.impl; + +import org.sadtech.bot.gitlab.context.domain.entity.Discussion; +import org.sadtech.bot.gitlab.context.repository.DiscussionRepository; +import org.sadtech.haiti.database.repository.manager.AbstractSimpleManagerRepository; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +@Repository +public class DiscussionRepositoryImpl extends AbstractSimpleManagerRepository implements DiscussionRepository { + + public DiscussionRepositoryImpl(JpaRepository jpaRepository) { + super(jpaRepository); + } + +} diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/NoteRepositoryImpl.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/NoteRepositoryImpl.java index 71aba22..29d1e7a 100644 --- a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/NoteRepositoryImpl.java +++ b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/NoteRepositoryImpl.java @@ -3,10 +3,15 @@ package org.sadtech.bot.gitlab.data.impl; import lombok.NonNull; import org.sadtech.bot.gitlab.context.domain.entity.Note; import org.sadtech.bot.gitlab.context.repository.NoteRepository; -import org.sadtech.bot.gitlab.data.jpa.CommentRepositoryJpa; +import org.sadtech.bot.gitlab.data.jpa.NoteRepositoryJpa; +import org.sadtech.haiti.context.page.Pagination; +import org.sadtech.haiti.context.page.Sheet; import org.sadtech.haiti.database.repository.manager.AbstractSimpleManagerRepository; +import org.sadtech.haiti.database.util.Converter; import org.springframework.stereotype.Repository; +import java.util.List; + /** * // TODO: 08.09.2020 Добавить описание. * @@ -15,16 +20,23 @@ import org.springframework.stereotype.Repository; @Repository public class NoteRepositoryImpl extends AbstractSimpleManagerRepository implements NoteRepository { - private final CommentRepositoryJpa repositoryJpa; + private final NoteRepositoryJpa repositoryJpa; - public NoteRepositoryImpl(CommentRepositoryJpa repositoryJpa) { + public NoteRepositoryImpl(NoteRepositoryJpa repositoryJpa) { super(repositoryJpa); this.repositoryJpa = repositoryJpa; } @Override - public void link(@NonNull Long noteId, @NonNull Long mergeRequestId) { - repositoryJpa.link(noteId, mergeRequestId); + public Sheet findAllByResolved(boolean resolved, @NonNull Pagination pagination) { + return Converter.page( + repositoryJpa.findAllByResolved(resolved, Converter.pagination(pagination)) + ); + } + + @Override + public List findAllByResponsibleIdAndResolved(@NonNull Long userId, boolean resolved) { + return repositoryJpa.findAllByResponsibleIdAndResolved(userId, resolved); } } diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/TaskRepositoryImpl.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/TaskRepositoryImpl.java deleted file mode 100644 index 7c618da..0000000 --- a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/TaskRepositoryImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.sadtech.bot.gitlab.data.impl; - -import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.bot.gitlab.context.repository.TaskRepository; -import org.sadtech.bot.gitlab.data.jpa.TaskRepositoryJpa; -import org.sadtech.haiti.context.page.Pagination; -import org.sadtech.haiti.context.page.Sheet; -import org.sadtech.haiti.database.repository.manager.AbstractSimpleManagerRepository; -import org.sadtech.haiti.database.util.Converter; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public class TaskRepositoryImpl extends AbstractSimpleManagerRepository implements TaskRepository { - - private final TaskRepositoryJpa taskRepositoryJpa; - - public TaskRepositoryImpl(TaskRepositoryJpa taskRepositoryJpa) { - super(taskRepositoryJpa); - this.taskRepositoryJpa = taskRepositoryJpa; - } - - @Override - public Sheet findAllByResolved(boolean resolved, @NonNull Pagination pagination) { - return Converter.page( - taskRepositoryJpa.findAllByResolved(resolved, Converter.pagination(pagination)) - ); - } - - @Override - public List findAllByResponsibleIdAndResolved(@NonNull Long userId, boolean resolved) { - return taskRepositoryJpa.findAllByResponsibleIdAndResolved(userId, resolved); - } -} diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/CommentRepositoryJpa.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/CommentRepositoryJpa.java deleted file mode 100644 index 76c0bbf..0000000 --- a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/CommentRepositoryJpa.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.sadtech.bot.gitlab.data.jpa; - -import org.sadtech.bot.gitlab.context.domain.entity.Note; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.transaction.annotation.Transactional; - -public interface CommentRepositoryJpa extends JpaRepository { - - @Modifying - @Transactional - @Query(value = "INSERT INTO gitlab_bot.public.merge_request_notes(merge_request_id, notes_id) values (:mergeRequestId, :noteId)", nativeQuery = true) - void link(@Param("noteId") Long noteId, @Param("mergeRequestId") Long mergeRequestId); - -} diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/DiscussionJpaRepository.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/DiscussionJpaRepository.java new file mode 100644 index 0000000..525b69c --- /dev/null +++ b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/DiscussionJpaRepository.java @@ -0,0 +1,13 @@ +package org.sadtech.bot.gitlab.data.jpa; + +import org.sadtech.bot.gitlab.context.domain.entity.Discussion; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +public interface DiscussionJpaRepository extends JpaRepository { + +} diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/TaskRepositoryJpa.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/NoteRepositoryJpa.java similarity index 51% rename from bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/TaskRepositoryJpa.java rename to bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/NoteRepositoryJpa.java index 69b9534..c9e04fc 100644 --- a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/TaskRepositoryJpa.java +++ b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/NoteRepositoryJpa.java @@ -1,16 +1,16 @@ package org.sadtech.bot.gitlab.data.jpa; -import org.sadtech.bot.gitlab.context.domain.entity.Task; +import org.sadtech.bot.gitlab.context.domain.entity.Note; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; -public interface TaskRepositoryJpa extends JpaRepository { +public interface NoteRepositoryJpa extends JpaRepository { - Page findAllByResolved(boolean resolved, Pageable pageable); + Page findAllByResolved(boolean resolved, Pageable pageable); - List findAllByResponsibleIdAndResolved(Long responsibleId, boolean resolved); + List findAllByResponsibleIdAndResolved(Long responsibleId, boolean resolved); } diff --git a/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/DiscussionJson.java b/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/DiscussionJson.java new file mode 100644 index 0000000..8ff2e7b --- /dev/null +++ b/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/DiscussionJson.java @@ -0,0 +1,20 @@ +package org.sadtech.bot.gitlab.sdk.domain; + +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * // TODO: 11.02.2021 Добавить описание. + * + * @author upagge 11.02.2021 + */ +@Getter +@Setter +public class DiscussionJson { + + private String id; + private List notes; + +} diff --git a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/service/unit/TaskProcessing.java b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/service/unit/TaskProcessing.java index 8c1c394..4781848 100644 --- a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/service/unit/TaskProcessing.java +++ b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/service/unit/TaskProcessing.java @@ -1,25 +1,18 @@ package org.sadtech.bot.gitlab.telegram.service.unit; -import lombok.RequiredArgsConstructor; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.bot.gitlab.context.service.TaskService; -import org.sadtech.social.core.domain.BoxAnswer; -import org.sadtech.social.core.domain.ProcessingData; -import org.sadtech.social.core.domain.content.Message; - /** * // TODO: 17.09.2020 Добавить описание. * * @author upagge 17.09.2020 */ //@Component -@RequiredArgsConstructor -public class TaskProcessing implements ProcessingData { - - private final TaskService taskService; - - @Override - public BoxAnswer processing(Message message) { +//@RequiredArgsConstructor +//public class TaskProcessing implements ProcessingData { +// +// private final TaskService taskService; +// +// @Override +// public BoxAnswer processing(Message message) { // final Person person = personService.getByTelegramId(message.getPersonId()) // .orElseThrow(() -> new NotFoundException("Ошибочка")); // final List tasks = taskService.getAllByResponsibleAndStatus(person.getLogin(), TaskStatus.OPEN); @@ -36,15 +29,15 @@ public class TaskProcessing implements ProcessingData { // ); // } // return BoxAnswer.of(messageText); - return null; - } - - private String createTaskString(Task task) { +// return null; +// } +// +// private String createTaskString(Task task) { // return MessageFormat.format( // "- [{0}]({1})", // task.getDescription(), task.getUrl() // ); - return null; - } - -} +// return null; +// } +// +//} diff --git a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/MenuConfig.java b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/MenuConfig.java index 0cd1a6f..5de18e5 100644 --- a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/MenuConfig.java +++ b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/MenuConfig.java @@ -3,11 +3,10 @@ package org.sadtech.bot.gitlab.telegram.unit; import org.sadtech.bot.gitlab.context.domain.MergeRequestState; import org.sadtech.bot.gitlab.context.domain.PersonInformation; import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest; -import org.sadtech.bot.gitlab.context.domain.entity.Task; import org.sadtech.bot.gitlab.context.domain.filter.MergeRequestFilter; import org.sadtech.bot.gitlab.context.service.AppSettingService; +import org.sadtech.bot.gitlab.context.service.DiscussionService; import org.sadtech.bot.gitlab.context.service.MergeRequestsService; -import org.sadtech.bot.gitlab.context.service.TaskService; import org.sadtech.bot.gitlab.core.config.properties.GitlabProperty; import org.sadtech.bot.gitlab.core.service.parser.ProjectParser; import org.sadtech.haiti.context.page.Sheet; @@ -130,7 +129,7 @@ public class MenuConfig { @Bean public AnswerText getTasks( - TaskService taskService, + DiscussionService discussionService, AppSettingService settingService, PersonInformation personInformation ) { @@ -138,21 +137,22 @@ public class MenuConfig { .boxAnswer(message -> { final Long userId = personInformation.getId(); - final String text = taskService.getAllPersonTask(userId, false).stream() - .collect(Collectors.groupingBy(Task::getMergeRequest)) - .entrySet() - .stream() - .map(node -> { - final String mrTitle = node.getKey().getTitle(); - final String mrUrl = node.getKey().getWebUrl(); - - final String taskText = node.getValue().stream() - .map(task -> MessageFormat.format("[{0}]({1})", task.getBody(), task.getWebUrl())) - .collect(Collectors.joining("\n")); - - return MessageFormat.format("- [{0}]({1}):\n{2}", mrTitle, mrUrl, taskText); - }) - .collect(Collectors.joining("\n\n")); + final String text = "test"; +// taskService.getAllPersonTask(userId, false).stream() +// .collect(Collectors.groupingBy(Task::getMergeRequest)) +// .entrySet() +// .stream() +// .map(node -> { +// final String mrTitle = node.getKey().getTitle(); +// final String mrUrl = node.getKey().getWebUrl(); +// +// final String taskText = node.getValue().stream() +// .map(task -> MessageFormat.format("[{0}]({1})", task.getBody(), task.getWebUrl())) +// .collect(Collectors.joining("\n")); +// +// return MessageFormat.format("- [{0}]({1}):\n{2}", mrTitle, mrUrl, taskText); +// }) +// .collect(Collectors.joining("\n\n")); return BoxAnswer.of("".equals(text) ? settingService.getMessage("ui.answer.no_task") : text); }) .phrase(settingService.getMessage("ui.menu.task")) diff --git a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/UnitConfig.java b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/UnitConfig.java index 1907cc3..6ece51f 100644 --- a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/UnitConfig.java +++ b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/UnitConfig.java @@ -3,16 +3,25 @@ package org.sadtech.bot.gitlab.telegram.unit; import lombok.RequiredArgsConstructor; import org.sadtech.bot.gitlab.context.domain.AppLocale; import org.sadtech.bot.gitlab.context.service.AppSettingService; +import org.sadtech.bot.gitlab.context.service.NoteService; import org.sadtech.bot.gitlab.core.service.parser.ProjectParser; import org.sadtech.social.bot.domain.unit.AnswerCheck; import org.sadtech.social.bot.domain.unit.AnswerProcessing; import org.sadtech.social.bot.domain.unit.AnswerText; import org.sadtech.social.bot.domain.unit.UnitActiveType; import org.sadtech.social.core.domain.BoxAnswer; +import org.sadtech.social.core.domain.content.Mail; +import org.sadtech.social.core.domain.content.attachment.Attachment; +import org.sadtech.social.core.domain.content.attachment.AttachmentType; +import org.sadtech.social.core.domain.content.attachment.Link; import org.sadtech.social.core.utils.KeyBoards; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * TODO: Добавить описание класса. * @@ -22,21 +31,72 @@ import org.springframework.context.annotation.Configuration; @RequiredArgsConstructor public class UnitConfig { + private static final Pattern NOTE_LINK = Pattern.compile("#note_\\d+$"); + @Bean public AnswerCheck checkFirstStart( AppSettingService settingService, AnswerText textCheckLanguage, - AnswerText menu + AnswerCheck checkMenuOrAnswer ) { return AnswerCheck.builder() .check( message -> settingService.isFirstStart() ) - .unitFalse(menu) + .unitFalse(checkMenuOrAnswer) .unitTrue(textCheckLanguage) .build(); } + @Bean + public AnswerCheck checkMenuOrAnswer( + AnswerText menu, + AnswerText answerNote + ) { + return AnswerCheck.builder() + .check( + message -> { + Mail mail = (Mail) message; + final List forwardMails = mail.getForwardMail(); + if (forwardMails.size() == 1) { + final Mail forwardMail = forwardMails.get(0); + return forwardMail.getAttachments().stream() + .anyMatch(attachment -> AttachmentType.LINK.equals(attachment.getType())); + } + return false; + } + ) + .unitTrue(answerNote) + .unitFalse(menu) + .build(); + } + + @Bean + public AnswerText answerNote( + NoteService noteService + ) { + return AnswerText.builder() + .boxAnswer( + message -> { + final List attachments = ((Mail) message).getForwardMail().get(0).getAttachments(); + for (Attachment attachment : attachments) { + if (AttachmentType.LINK.equals(attachment.getType())) { + final String url = ((Link) attachment).getUrl(); + Matcher matcher = NOTE_LINK.matcher(url); + if (matcher.find()) { + final String note = url.substring(matcher.start(), matcher.end()); + Long noteId = Long.valueOf(note.replaceAll("#note_", "")); +// noteService.answer(noteId, message.getText()); + } + return BoxAnswer.of("Победа"); + } + } + return BoxAnswer.of("Ошибка"); + } + ) + .build(); + } + @Bean public AnswerText textCheckLanguage( AnswerProcessing checkLanguage