From 24008c798922535b01e18dffee673b77f77aa514 Mon Sep 17 00:00:00 2001 From: uPagge Date: Sat, 16 Jan 2021 17:06:13 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D0=B0=D1=8F=20=D1=80?= =?UTF-8?q?=D0=B0=D0=B1=D0=BE=D1=87=D0=B0=D1=8F=20=D0=B2=D0=B5=D1=80=D1=81?= =?UTF-8?q?=D0=B8=D1=8F=20=D1=81=20=D0=BC=D0=B5=D0=BD=D1=8E=20=D0=B2=20?= =?UTF-8?q?=D1=82=D0=B5=D0=BB=D0=B5=D0=B3=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/scheduler/SchedulerService.java | 9 +- .../gitlab/app/service/ExecutorScanner.java | 67 ------ .../gitlab/app/service/executor/DataScan.java | 11 - .../gitlab/app/service/executor/Executor.java | 13 -- .../app/service/executor/ResultScan.java | 15 -- .../gitlab/app/service/executor/Seeker.java | 28 --- .../service/parser/CommentAndTaskParser.java | 213 ------------------ bot-app/src/main/resources/application.yaml | 4 +- .../v.1.0.0/2020-01-16-app-setting.xml | 14 ++ .../v.1.0.0/2021-01-14-create-tables.xml | 41 ++++ .../liquibase/v.1.0.0/cumulative.xml | 1 + .../src/main/resources/messages_en.properties | 5 + .../src/main/resources/messages_ru.properties | 5 + .../bot/gitlab/context/domain/AppLocale.java | 35 +++ .../context/domain/entity/AppSetting.java | 37 +++ .../gitlab/context/domain/entity/Comment.java | 61 ----- .../gitlab/context/domain/entity/Note.java | 65 ++++++ .../repository/AppSettingRepository.java | 13 ++ .../context/repository/CommentRepository.java | 10 +- .../context/service/AppSettingService.java | 23 ++ .../{CommentService.java => NoteService.java} | 10 +- .../gitlab/context/service/TaskService.java | 4 +- bot-core/pom.xml | 10 + .../service/convert/CommentToTaskConvert.java | 33 +++ .../convert/MergeRequestJsonConverter.java | 2 +- .../service/convert/PersonJsonConverter.java | 2 +- .../service/convert/ProjectJsonConverter.java | 2 +- .../service/convert/TaskToCommentConvert.java | 32 +++ .../converter/CommentToTaskConvert.java | 34 --- .../converter/TaskToCommentConvert.java | 32 --- .../service/impl/AppSettingServiceImpl.java | 72 ++++++ .../core/service/impl/CommentServiceImpl.java | 150 ------------ .../core/service/impl/NoteServiceImpl.java | 140 ++++++++++++ .../core/service/impl/TaskServiceImpl.java | 65 +++--- .../service/parser/MergeRequestParser.java | 2 +- .../core/service/parser/NoteParser.java | 191 ++++++++++++++++ .../core}/service/parser/ProjectParser.java | 80 ++++--- .../data/impl/AppSettingRepositoryImpl.java | 21 ++ .../data/impl/CommentRepositoryImpl.java | 10 +- .../data/jpa/AppSettingJpaRepository.java | 12 + .../gitlab/data/jpa/CommentRepositoryJpa.java | 10 +- .../bot/gitlab/sdk/domain/CommentJson.java | 33 --- .../bot/gitlab/sdk/domain/NoteJson.java | 41 ++++ .../telegram/config/TelegramBotConfig.java | 7 +- .../telegram/scheduler/CheckNewMessage.java | 3 +- .../telegram/unit/NotifySettingUnit.java | 125 +++++----- .../bot/gitlab/telegram/unit/UnitConfig.java | 132 ++++++----- 47 files changed, 1039 insertions(+), 886 deletions(-) delete mode 100644 bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/ExecutorScanner.java delete mode 100644 bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/DataScan.java delete mode 100644 bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/Executor.java delete mode 100644 bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/ResultScan.java delete mode 100644 bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/Seeker.java delete mode 100644 bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/CommentAndTaskParser.java create mode 100644 bot-app/src/main/resources/liquibase/v.1.0.0/2020-01-16-app-setting.xml create mode 100644 bot-app/src/main/resources/messages_en.properties create mode 100644 bot-app/src/main/resources/messages_ru.properties create mode 100644 bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/AppLocale.java create mode 100644 bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/AppSetting.java delete mode 100644 bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Comment.java create mode 100644 bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Note.java create mode 100644 bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/AppSettingRepository.java create mode 100644 bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/AppSettingService.java rename bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/{CommentService.java => NoteService.java} (51%) create mode 100644 bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/CommentToTaskConvert.java rename {bot-app/src/main/java/org/sadtech/bot/gitlab/app => bot-core/src/main/java/org/sadtech/bot/gitlab/core}/service/convert/MergeRequestJsonConverter.java (97%) rename {bot-app/src/main/java/org/sadtech/bot/gitlab/app => bot-core/src/main/java/org/sadtech/bot/gitlab/core}/service/convert/PersonJsonConverter.java (93%) rename {bot-app/src/main/java/org/sadtech/bot/gitlab/app => bot-core/src/main/java/org/sadtech/bot/gitlab/core}/service/convert/ProjectJsonConverter.java (94%) create mode 100644 bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/TaskToCommentConvert.java delete mode 100644 bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/converter/CommentToTaskConvert.java delete mode 100644 bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/converter/TaskToCommentConvert.java create mode 100644 bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/AppSettingServiceImpl.java delete mode 100644 bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/CommentServiceImpl.java create mode 100644 bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/NoteServiceImpl.java rename {bot-app/src/main/java/org/sadtech/bot/gitlab/app => bot-core/src/main/java/org/sadtech/bot/gitlab/core}/service/parser/MergeRequestParser.java (98%) create mode 100644 bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/NoteParser.java rename {bot-app/src/main/java/org/sadtech/bot/gitlab/app => bot-core/src/main/java/org/sadtech/bot/gitlab/core}/service/parser/ProjectParser.java (53%) create mode 100644 bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/AppSettingRepositoryImpl.java create mode 100644 bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/AppSettingJpaRepository.java delete mode 100644 gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/CommentJson.java create mode 100644 gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/NoteJson.java 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 2daee25..9290679 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 @@ -2,8 +2,8 @@ package org.sadtech.bot.gitlab.app.scheduler; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.sadtech.bot.gitlab.app.service.parser.MergeRequestParser; -import org.sadtech.bot.gitlab.app.service.parser.ProjectParser; +import org.sadtech.bot.gitlab.core.service.parser.MergeRequestParser; +import org.sadtech.bot.gitlab.core.service.parser.ProjectParser; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @@ -20,11 +20,6 @@ public class SchedulerService { private final ProjectParser projectParser; private final MergeRequestParser mergeRequestParser; - @Scheduled(cron = "*/30 * * * * *") - public void newProjectParse() { - projectParser.parseNewProject(); - } - @Scheduled(cron = "*/30 * * * * *") public void newMergeRequest() { mergeRequestParser.parsingNewMergeRequest(); diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/ExecutorScanner.java b/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/ExecutorScanner.java deleted file mode 100644 index 68b9f88..0000000 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/ExecutorScanner.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.sadtech.bot.gitlab.app.service; - -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.sadtech.bot.gitlab.app.service.executor.DataScan; -import org.sadtech.bot.gitlab.app.service.executor.Executor; -import org.sadtech.bot.gitlab.app.service.executor.Seeker; -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.CommentJson; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.stream.Collectors; - -@Slf4j -@Service -@RequiredArgsConstructor -public class ExecutorScanner implements Executor { - - private final ExecutorService executorService; - private List>> resultList = new ArrayList<>(); - private final GitlabProperty gitlabProperty; - private final PersonProperty personProperty; - - @Override - public boolean registration(@NonNull List dataScans) { - resultList.addAll( - dataScans.stream() - .map(dataScan -> new Seeker(dataScan, personProperty.getToken())) - .map(executorService::submit) - .collect(Collectors.toList()) - ); - return true; - } - - @Override - public List getResult() { - while (!resultList.stream().allMatch(Future::isDone)) { - - } - final List result = resultList.stream() - .filter(Future::isDone) - .map(this::getResultScan) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); - resultList.clear(); - return result; - } - - private Optional getResultScan(Future> test) { - try { - return test.get(); - } catch (InterruptedException | ExecutionException e) { - log.error(e.getMessage()); - } - return Optional.empty(); - } - -} diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/DataScan.java b/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/DataScan.java deleted file mode 100644 index 2a23135..0000000 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/DataScan.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.sadtech.bot.gitlab.app.service.executor; - -import lombok.Data; - -@Data -public class DataScan { - - private final String urlComment; - private final Long pullRequestId; - -} diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/Executor.java b/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/Executor.java deleted file mode 100644 index 3c0f8d2..0000000 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/Executor.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.sadtech.bot.gitlab.app.service.executor; - -import lombok.NonNull; - -import java.util.List; - -public interface Executor { - - boolean registration(@NonNull List seeker); - - List getResult(); - -} diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/ResultScan.java b/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/ResultScan.java deleted file mode 100644 index a355c61..0000000 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/ResultScan.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.sadtech.bot.gitlab.app.service.executor; - -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import org.sadtech.bot.gitlab.sdk.domain.CommentJson; - -@Getter -@RequiredArgsConstructor -public class ResultScan { - - private final String commentApiUrl; - private final Long pullRequestId; - private final CommentJson commentJson; - -} diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/Seeker.java b/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/Seeker.java deleted file mode 100644 index ef3a297..0000000 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/executor/Seeker.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.sadtech.bot.gitlab.app.service.executor; - -import lombok.RequiredArgsConstructor; -import org.sadtech.bot.gitlab.sdk.domain.CommentJson; - -import java.util.Optional; -import java.util.concurrent.Callable; - -@RequiredArgsConstructor -public class Seeker implements Callable> { - - private final DataScan dataScan; - private final String token; - - @Override - public Optional call() { -// return Utils.urlToJson(dataScan.getUrlComment(), token, CommentJson.class) -// .map( -// commentJson -> { -// commentJson.setCustomPullRequestId(dataScan.getPullRequestId()); -// commentJson.setCustomCommentApiUrl(dataScan.getUrlComment()); -// return commentJson; -// } -// ); - return Optional.empty(); - } - -} diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/CommentAndTaskParser.java b/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/CommentAndTaskParser.java deleted file mode 100644 index 88d53e1..0000000 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/CommentAndTaskParser.java +++ /dev/null @@ -1,213 +0,0 @@ -package org.sadtech.bot.gitlab.app.service.parser; - -import lombok.NonNull; -import org.sadtech.bot.gitlab.app.config.property.CommentSchedulerProperty; -import org.sadtech.bot.gitlab.app.service.ExecutorScanner; -import org.sadtech.bot.gitlab.app.service.executor.DataScan; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; -import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest; -import org.sadtech.bot.gitlab.context.domain.entity.MergeRequestMini; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.bot.gitlab.context.exception.NotFoundException; -import org.sadtech.bot.gitlab.context.service.CommentService; -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.config.properties.InitProperty; -import org.sadtech.bot.gitlab.sdk.domain.CommentJson; -import org.sadtech.bot.gitlab.sdk.domain.Severity; -import org.sadtech.haiti.context.page.Sheet; -import org.sadtech.haiti.core.page.PaginationImpl; -import org.springframework.core.convert.ConversionService; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -/** - *

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

- *

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

- */ -//@Component -public class CommentAndTaskParser { - - private final CommentService commentService; - private final MergeRequestsService mergeRequestsService; - private final ExecutorScanner executorScanner; - private final TaskService taskService; - private final ConversionService conversionService; - - private final GitlabProperty gitlabProperty; - private final CommentSchedulerProperty commentSchedulerProperty; - private final InitProperty initProperty; - - private boolean initStart = false; - - public CommentAndTaskParser( - CommentService commentService, - MergeRequestsService mergeRequestsService, - ExecutorScanner executorScanner, - TaskService taskService, - ConversionService conversionService, - GitlabProperty gitlabProperty, - CommentSchedulerProperty commentSchedulerProperty, - InitProperty initProperty - ) { - this.commentService = commentService; - this.mergeRequestsService = mergeRequestsService; - this.executorScanner = executorScanner; - this.taskService = taskService; - this.conversionService = conversionService; - this.gitlabProperty = gitlabProperty; - this.commentSchedulerProperty = commentSchedulerProperty; - this.initProperty = initProperty; - } - - public void scanNewCommentAndTask() { - long commentId = getLastIdCommentOrTask() + 1; - int count = 0; - do { - final List dataScans = generatingLinksToPossibleComments(commentId); - executorScanner.registration(dataScans); - final List resultScans = executorScanner.getResult(); - if (!resultScans.isEmpty()) { - final long commentMax = commentService.createAll(getCommentsByResultScan(resultScans)).stream() - .mapToLong(Comment::getId) - .max().orElse(0L); - final long taskMax = taskService.createAll(getTaskByResultScan(resultScans)).stream() - .mapToLong(Task::getId) - .max().orElse(0L); - commentId = Long.max(commentMax, taskMax) + 1; - count = 0; - } - } while (count++ < commentSchedulerProperty.getNoCommentCount()); - } - - private long getLastIdCommentOrTask() { - Long commentStartId = Long.max(commentService.getLastCommentId(), taskService.getLastTaskId()); - if (initProperty != null && !initStart && (commentStartId == 0L || initProperty.isUse())) { - commentStartId = initProperty.getStartCommentId(); - initStart = true; - } - return commentStartId; - } - - 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()) - ); - } - commentId++; - } - return commentUrls; - } - - private List getCommentsByResultScan(List commentJsons) { - return commentJsons.stream() - .filter(json -> Severity.NORMAL.equals(json.getSeverity())) - .map(resultScan -> conversionService.convert(resultScan, Comment.class)) - .peek( - comment -> { - final MergeRequestMini mergeRequestMini = mergeRequestsService.getMiniInfo(comment.getPullRequestId()) - .orElseThrow(() -> new NotFoundException("Автор ПР не найден")); - comment.setUrl(generateUrl(comment.getId(), mergeRequestMini.getWebUrl())); -// comment.setResponsible(mergeRequestMini.getAuthor()); - } - ) - .collect(Collectors.toList()); - } - - private List getTaskByResultScan(List commentJsons) { - return commentJsons.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())); - } - ) - .collect(Collectors.toList()); - } - - private String generateUrl(@NonNull Long id, @NonNull String pullRequestUrl) { - return MessageFormat.format("{0}/overview?commentId={1}", pullRequestUrl, Long.toString(id)); - } - - private String getCommentUrl(long commentId, MergeRequest mergeRequest) { -// return gitlabProperty.getUrlPullRequestComment() -// .replace("{projectKey}", mergeRequest.getProjectKey()) -// .replace("{repositorySlug}", mergeRequest.getRepositorySlug()) -// .replace("{pullRequestId}", mergeRequest.getBitbucketId().toString()) -// .replace("{commentId}", String.valueOf(commentId)); - return null; - } - - public void scanOldComment() { -// final List comments = commentService.getAllBetweenDate( -// LocalDateTime.now().minusDays(20), LocalDateTime.now() -// ); -// for (Comment oldComment : comments) { -// final Optional optCommentJson = Utils.urlToJson( -// oldComment.getUrlApi(), -// gitlabProperty.getToken(), -// CommentJson.class -// ); -// if (optCommentJson.isPresent()) { -// final CommentJson json = optCommentJson.get(); -// if (Severity.BLOCKER.equals(json.getSeverity())) { -// taskService.convert(oldComment); -// } else { -// final Comment newComment = conversionService.convert(json, Comment.class); -// commentService.update(newComment); -// } -// } else { -// commentService.deleteById(oldComment.getId()); -// } -// } - } - - public void scanOldTask() { -// final List tasks = taskService.getAllBetweenDate( -// LocalDateTime.now().minusDays(20), LocalDateTime.now() -// ); -// for (Task oldTask : tasks) { -// final Optional optCommentJson = Utils.urlToJson( -// oldTask.getUrlApi(), -// gitlabProperty.getToken(), -// CommentJson.class -// ); -// if (optCommentJson.isPresent()) { -// final CommentJson json = optCommentJson.get(); -// if (Severity.NORMAL.equals(json.getSeverity())) { -// commentService.convert(oldTask); -// } else { -// final Task newTask = conversionService.convert(json, Task.class); -// taskService.update(newTask); -// } -// } else { -// taskService.deleteById(oldTask.getId()); -// } -// } - } - -} diff --git a/bot-app/src/main/resources/application.yaml b/bot-app/src/main/resources/application.yaml index 629cea9..547d4a2 100644 --- a/bot-app/src/main/resources/application.yaml +++ b/bot-app/src/main/resources/application.yaml @@ -32,10 +32,10 @@ gitlab-bot: telegram-id: ${TELEGRAM_PERSON_ID} token: ${GITLAB_PERSONAL_TOKEN} gitlab: - url-project: ${GITLAB_URL}/api/v4/projects + url-project: ${GITLAB_URL}/api/v4/projects?page={0}&per_page=100 url-pull-request-open: ${GITLAB_URL}/api/v4/projects/{0}/merge_requests?state=opened url-pull-request-close: ${GITLAB_URL} - url-pull-request-comment: ${GITLAB_URL} + url-pull-request-comment: ${GITLAB_URL}/api/v4/projects/19/merge_requests/8/notes url-pull-request: ${GITLAB_URL}/api/v4/projects/{0}/merge_requests/{1} user-url: ${GITLAB_URL}/api/v4/user users-url: ${GITLAB_URL}/api/v4/users diff --git a/bot-app/src/main/resources/liquibase/v.1.0.0/2020-01-16-app-setting.xml b/bot-app/src/main/resources/liquibase/v.1.0.0/2020-01-16-app-setting.xml new file mode 100644 index 0000000..45603cc --- /dev/null +++ b/bot-app/src/main/resources/liquibase/v.1.0.0/2020-01-16-app-setting.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + \ 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 ebf0001..c8cb826 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 @@ -3,6 +3,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> + + + + + + + + + + @@ -104,4 +114,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ 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 15252f0..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 @@ -4,5 +4,6 @@ xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> + \ No newline at end of file diff --git a/bot-app/src/main/resources/messages_en.properties b/bot-app/src/main/resources/messages_en.properties new file mode 100644 index 0000000..555d6a6 --- /dev/null +++ b/bot-app/src/main/resources/messages_en.properties @@ -0,0 +1,5 @@ +main.yes=Yes +main.no=No +ui.lang_changed=Language changed successfully +ui.monitor_private_projects=Start tracking private projects? +ui.monitor_project_private_success=Projects have been successfully added to tracking \ No newline at end of file diff --git a/bot-app/src/main/resources/messages_ru.properties b/bot-app/src/main/resources/messages_ru.properties new file mode 100644 index 0000000..f847dc9 --- /dev/null +++ b/bot-app/src/main/resources/messages_ru.properties @@ -0,0 +1,5 @@ +main.yes=Да +main.no=Нет +ui.lang_changed=Язык успешно изменен +ui.monitor_private_projects=Начать отслеживать приватные проекты? +ui.monitor_project_private_success=Проекты успешно добавлены в отслеживание \ No newline at end of file diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/AppLocale.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/AppLocale.java new file mode 100644 index 0000000..e287ade --- /dev/null +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/AppLocale.java @@ -0,0 +1,35 @@ +package org.sadtech.bot.gitlab.context.domain; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NonNull; +import org.sadtech.haiti.context.exception.NotFoundException; + +import java.util.Arrays; +import java.util.Locale; + +/** + * // TODO: 16.01.2021 Добавить описание. + * + * @author upagge 16.01.2021 + */ +@Getter +@AllArgsConstructor +public enum AppLocale { + + RU("Русский"), EN("English"); + + private final String label; + + public static AppLocale of(@NonNull String label) { + return Arrays.stream(values()) + .filter(appLocale -> appLocale.getLabel().equals(label)) + .findFirst() + .orElseThrow(() -> new NotFoundException("Ошибка, локализация не найдена. Попробуйте снова.")); + } + + public Locale getValue() { + return Locale.forLanguageTag(name().toLowerCase()); + } + +} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/AppSetting.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/AppSetting.java new file mode 100644 index 0000000..1bb6957 --- /dev/null +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/AppSetting.java @@ -0,0 +1,37 @@ +package org.sadtech.bot.gitlab.context.domain.entity; + +import lombok.Getter; +import lombok.Setter; +import org.sadtech.bot.gitlab.context.domain.AppLocale; +import org.sadtech.haiti.context.domain.BasicEntity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * // TODO: 16.01.2021 Добавить описание. + * + * @author upagge 16.01.2021 + */ +@Entity +@Getter +@Setter +@Table(name = "app_setting") +public class AppSetting implements BasicEntity { + + @Id + @Column(name = "id") + private Long id; + + @Column(name = "language") + @Enumerated(EnumType.STRING) + private AppLocale appLocale; + + @Column(name = "first_start") + private boolean firstStart; + +} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Comment.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Comment.java deleted file mode 100644 index 7571e18..0000000 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Comment.java +++ /dev/null @@ -1,61 +0,0 @@ -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.CollectionTable; -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import java.time.LocalDateTime; -import java.util.Set; - -@Getter -@Setter -//@Entity -//@Table(name = "comment") -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -public class Comment implements BasicEntity { - - @Id - @Column(name = "id") - @EqualsAndHashCode.Include - private Long id; - - @Column(name = "url_api") - private String urlApi; - - @Column(name = "url") - private String url; - - @Column(name = "pull_request_id") - private Long pullRequestId; - - @Column(name = "author_login") - private String author; - - @Column(name = "responsible_login") - private String responsible; - - @Column(name = "message") - private String message; - - @Column(name = "create_date") - private LocalDateTime createDate; - - /** - * Версия объекта в битбакет - */ - @Column(name = "bitbucket_version") - private Integer bitbucketVersion; - - @ElementCollection(fetch = FetchType.EAGER) - @CollectionTable(name = "comment_tree", joinColumns = @JoinColumn(name = "parent_id")) - @Column(name = "child_id") - private Set answers; - -} 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 new file mode 100644 index 0000000..eadfee8 --- /dev/null +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/domain/entity/Note.java @@ -0,0 +1,65 @@ +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.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import java.time.LocalDateTime; + +@Getter +@Setter +@Entity +@Table(name = "note") +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +public class Note implements BasicEntity { + + @Id + @Column + private Long id; + + @Column(name = "type") + private String type; + + @Column(name = "body") + private String body; + + @Column(name = "created_date") + private LocalDateTime created; + + @Column(name = "updated_date") + private LocalDateTime updated; + + @ManyToOne + @JoinColumn(name = "author_id") + private Person author; + + @Column(name = "system") + private boolean system; + + @Column(name = "noteable_id") + private Long noteableId; + + @Column(name = "noteable_type") + private String noteableType; + + @Column(name = "resolveable") + private Boolean resolveable; + + @Column(name = "resolved") + private Boolean resolved; + + @ManyToOne + @JoinColumn(name = "resolved_id") + private Person resolvedBy; + + @Column(name = "noteable_iid") + private Long noteableIid; + +} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/AppSettingRepository.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/AppSettingRepository.java new file mode 100644 index 0000000..546bc74 --- /dev/null +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/AppSettingRepository.java @@ -0,0 +1,13 @@ +package org.sadtech.bot.gitlab.context.repository; + +import org.sadtech.bot.gitlab.context.domain.entity.AppSetting; +import org.sadtech.haiti.context.repository.SimpleManagerRepository; + +/** + * // TODO: 16.01.2021 Добавить описание. + * + * @author upagge 16.01.2021 + */ +public interface AppSettingRepository extends SimpleManagerRepository { + +} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/CommentRepository.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/CommentRepository.java index 2248e0f..be5f4c4 100644 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/CommentRepository.java +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/repository/CommentRepository.java @@ -1,7 +1,7 @@ package org.sadtech.bot.gitlab.context.repository; import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; +import org.sadtech.bot.gitlab.context.domain.entity.Note; import org.sadtech.haiti.context.repository.SimpleManagerRepository; import java.time.LocalDateTime; @@ -14,13 +14,13 @@ import java.util.Set; * * @author upagge 08.09.2020 */ -public interface CommentRepository extends SimpleManagerRepository { +public interface CommentRepository extends SimpleManagerRepository { - Optional findFirstByOrderByIdDesc(); + Optional findFirstByOrderByIdDesc(); - List findByCreateDateBetween(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); + List findByCreateDateBetween(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); - List findAllById(@NonNull Set ids); + List findAllById(@NonNull Set ids); Set existsById(Set ids); diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/AppSettingService.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/AppSettingService.java new file mode 100644 index 0000000..4adcdb2 --- /dev/null +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/AppSettingService.java @@ -0,0 +1,23 @@ +package org.sadtech.bot.gitlab.context.service; + +import lombok.NonNull; +import org.sadtech.bot.gitlab.context.domain.AppLocale; + +/** + * // TODO: 16.01.2021 Добавить описание. + * + * @author upagge 16.01.2021 + */ +public interface AppSettingService { + + boolean isFirstStart(); + + void disableFirstStart(); + + String getMessage(@NonNull String label); + + String getMessage(@NonNull String label, String... params); + + void setLocale(@NonNull AppLocale appLocale); + +} diff --git a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/CommentService.java b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/NoteService.java similarity index 51% rename from bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/CommentService.java rename to bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/NoteService.java index 3d54f4c..e898f46 100644 --- a/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/CommentService.java +++ b/bot-context/src/main/java/org/sadtech/bot/gitlab/context/service/NoteService.java @@ -1,7 +1,7 @@ package org.sadtech.bot.gitlab.context.service; import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; +import org.sadtech.bot.gitlab.context.domain.entity.Note; import org.sadtech.bot.gitlab.context.domain.entity.Task; import org.sadtech.haiti.context.service.SimpleManagerService; @@ -9,15 +9,15 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Set; -public interface CommentService extends SimpleManagerService { +public interface NoteService extends SimpleManagerService { Long getLastCommentId(); - List getAllBetweenDate(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); + List getAllBetweenDate(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); - List getAllById(@NonNull Set ids); + List getAllById(@NonNull Set ids); - Comment convert(@NonNull Task task); + Note convert(@NonNull Task task); Set existsById(@NonNull Set ids); 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 index 30e247c..2f6fdfb 100644 --- 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 @@ -2,7 +2,7 @@ package org.sadtech.bot.gitlab.context.service; import lombok.NonNull; import org.sadtech.bot.gitlab.context.domain.TaskStatus; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; +import org.sadtech.bot.gitlab.context.domain.entity.Note; import org.sadtech.bot.gitlab.context.domain.entity.Task; import org.sadtech.haiti.context.service.SimpleManagerService; @@ -13,7 +13,7 @@ public interface TaskService extends SimpleManagerService { Long getLastTaskId(); - Task convert(@NonNull Comment comment); + Task convert(@NonNull Note note); List getAllBetweenDate(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); diff --git a/bot-core/pom.xml b/bot-core/pom.xml index b5957eb..d5a7942 100644 --- a/bot-core/pom.xml +++ b/bot-core/pom.xml @@ -65,6 +65,16 @@ postgresql + + org.sadtech.haiti + haiti-utils + + + + org.sadtech.bot.gitlab + gitlab-sdk + + org.projectlombok lombok diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/CommentToTaskConvert.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/CommentToTaskConvert.java new file mode 100644 index 0000000..1ffa0fb --- /dev/null +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/CommentToTaskConvert.java @@ -0,0 +1,33 @@ +package org.sadtech.bot.gitlab.core.service.convert; + +import org.sadtech.bot.gitlab.context.domain.entity.Note; +import org.sadtech.bot.gitlab.context.domain.entity.Task; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +/** + * // TODO: 12.09.2020 Добавить описание. + * + * @author upagge 12.09.2020 + */ +@Component +public class CommentToTaskConvert implements Converter { + + @Override + public Task convert(Note source) { + final Task task = new Task(); +// task.setId(source.getId()); +// task.setUrl(source.getUrl()); +// task.setUrlApi(source.getUrlApi()); +// task.setResponsible(source.getResponsible()); +// task.setStatus(TaskStatus.OPEN); +// task.setPullRequestId(source.getPullRequestId()); +// task.setBitbucketVersion(source.getBitbucketVersion()); +// task.setCreateDate(source.getCreateDate()); +// task.setDescription(source.getMessage()); +// task.setAuthor(source.getAuthor()); +// task.setAnswers(source.getAnswers()); + return task; + } + +} diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/MergeRequestJsonConverter.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/MergeRequestJsonConverter.java similarity index 97% rename from bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/MergeRequestJsonConverter.java rename to bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/MergeRequestJsonConverter.java index 3675b6c..e25fe4a 100644 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/MergeRequestJsonConverter.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/MergeRequestJsonConverter.java @@ -1,4 +1,4 @@ -package org.sadtech.bot.gitlab.app.service.convert; +package org.sadtech.bot.gitlab.core.service.convert; import lombok.RequiredArgsConstructor; import org.sadtech.bot.gitlab.context.domain.MergeRequestState; diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/PersonJsonConverter.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/PersonJsonConverter.java similarity index 93% rename from bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/PersonJsonConverter.java rename to bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/PersonJsonConverter.java index 71e127e..3e773d0 100644 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/PersonJsonConverter.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/PersonJsonConverter.java @@ -1,4 +1,4 @@ -package org.sadtech.bot.gitlab.app.service.convert; +package org.sadtech.bot.gitlab.core.service.convert; import org.sadtech.bot.gitlab.context.domain.entity.Person; import org.sadtech.bot.gitlab.sdk.domain.PersonJson; diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/ProjectJsonConverter.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/ProjectJsonConverter.java similarity index 94% rename from bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/ProjectJsonConverter.java rename to bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/ProjectJsonConverter.java index 2338469..ab11bba 100644 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/convert/ProjectJsonConverter.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/ProjectJsonConverter.java @@ -1,4 +1,4 @@ -package org.sadtech.bot.gitlab.app.service.convert; +package org.sadtech.bot.gitlab.core.service.convert; import org.sadtech.bot.gitlab.context.domain.entity.Project; import org.sadtech.bot.gitlab.sdk.domain.ProjectJson; diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/TaskToCommentConvert.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/TaskToCommentConvert.java new file mode 100644 index 0000000..e94e7b6 --- /dev/null +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/convert/TaskToCommentConvert.java @@ -0,0 +1,32 @@ +package org.sadtech.bot.gitlab.core.service.convert; + +import org.sadtech.bot.gitlab.context.domain.entity.Note; +import org.sadtech.bot.gitlab.context.domain.entity.Task; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +/** + * // TODO: 12.09.2020 Добавить описание. + * + * @author upagge 12.09.2020 + */ +@Component +public class TaskToCommentConvert implements Converter { + + @Override + public Note convert(Task source) { + final Note note = new Note(); +// note.setId(source.getId()); +// note.setUrl(source.getUrl()); +// note.setUrlApi(source.getUrlApi()); +// note.setPullRequestId(source.getPullRequestId()); +// note.setBitbucketVersion(source.getBitbucketVersion()); +// note.setCreateDate(source.getCreateDate()); +// note.setMessage(source.getDescription()); +// note.setResponsible(source.getResponsible()); +// note.setAuthor(source.getAuthor()); +// note.setAnswers(source.getAnswers()); + return note; + } + +} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/converter/CommentToTaskConvert.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/converter/CommentToTaskConvert.java deleted file mode 100644 index 587fac5..0000000 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/converter/CommentToTaskConvert.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.sadtech.bot.gitlab.core.service.converter; - -import org.sadtech.bot.gitlab.context.domain.TaskStatus; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Component; - -/** - * // TODO: 12.09.2020 Добавить описание. - * - * @author upagge 12.09.2020 - */ -@Component -public class CommentToTaskConvert implements Converter { - - @Override - public Task convert(Comment source) { - final Task task = new Task(); - task.setId(source.getId()); - task.setUrl(source.getUrl()); - task.setUrlApi(source.getUrlApi()); - task.setResponsible(source.getResponsible()); - task.setStatus(TaskStatus.OPEN); - task.setPullRequestId(source.getPullRequestId()); - task.setBitbucketVersion(source.getBitbucketVersion()); - task.setCreateDate(source.getCreateDate()); - task.setDescription(source.getMessage()); - task.setAuthor(source.getAuthor()); - task.setAnswers(source.getAnswers()); - return task; - } - -} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/converter/TaskToCommentConvert.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/converter/TaskToCommentConvert.java deleted file mode 100644 index 189ec6e..0000000 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/converter/TaskToCommentConvert.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.sadtech.bot.gitlab.core.service.converter; - -import org.sadtech.bot.gitlab.context.domain.entity.Comment; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Component; - -/** - * // TODO: 12.09.2020 Добавить описание. - * - * @author upagge 12.09.2020 - */ -@Component -public class TaskToCommentConvert implements Converter { - - @Override - public Comment convert(Task source) { - final Comment comment = new Comment(); - comment.setId(source.getId()); - comment.setUrl(source.getUrl()); - comment.setUrlApi(source.getUrlApi()); - comment.setPullRequestId(source.getPullRequestId()); - comment.setBitbucketVersion(source.getBitbucketVersion()); - comment.setCreateDate(source.getCreateDate()); - comment.setMessage(source.getDescription()); - comment.setResponsible(source.getResponsible()); - comment.setAuthor(source.getAuthor()); - comment.setAnswers(source.getAnswers()); - return comment; - } - -} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/AppSettingServiceImpl.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/AppSettingServiceImpl.java new file mode 100644 index 0000000..5a7afa4 --- /dev/null +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/AppSettingServiceImpl.java @@ -0,0 +1,72 @@ +package org.sadtech.bot.gitlab.core.service.impl; + +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.sadtech.bot.gitlab.context.domain.AppLocale; +import org.sadtech.bot.gitlab.context.domain.entity.AppSetting; +import org.sadtech.bot.gitlab.context.repository.AppSettingRepository; +import org.sadtech.bot.gitlab.context.service.AppSettingService; +import org.sadtech.haiti.context.exception.NotFoundException; +import org.springframework.context.MessageSource; +import org.springframework.stereotype.Service; + +import java.util.Arrays; + +/** + * // TODO: 16.01.2021 Добавить описание. + * + * @author upagge 16.01.2021 + */ +@Service +@RequiredArgsConstructor +public class AppSettingServiceImpl implements AppSettingService { + + private static final Long KEY = 1L; + private static final NotFoundException EXCEPTION = new NotFoundException("Ошибка, невозможно найти настройки приложения, проверьте базу данных."); + private final AppSettingRepository appSettingRepository; + + private final MessageSource messageSource; + + @Override + public boolean isFirstStart() { + return appSettingRepository.findById(KEY) + .orElseThrow(() -> EXCEPTION) + .isFirstStart(); + } + + @Override + public void disableFirstStart() { + final AppSetting appSetting = appSettingRepository.findById(KEY).orElseThrow(() -> EXCEPTION); + appSetting.setFirstStart(false); + appSettingRepository.save(appSetting); + } + + @Override + public String getMessage(@NonNull String label) { + return messageSource.getMessage( + label, null, appSettingRepository.findById(KEY) + .orElseThrow(() -> EXCEPTION) + .getAppLocale().getValue() + ); + } + + @Override + public String getMessage(@NonNull String label, String... params) { + final Object[] paramsArray = Arrays.stream(params).toArray(); + return messageSource.getMessage( + label, + paramsArray, + appSettingRepository.findById(KEY) + .orElseThrow(() -> EXCEPTION) + .getAppLocale().getValue() + ); + } + + @Override + public void setLocale(@NonNull AppLocale appLocale) { + final AppSetting appSetting = appSettingRepository.findById(KEY).orElseThrow(() -> EXCEPTION); + appSetting.setAppLocale(appLocale); + appSettingRepository.save(appSetting); + } + +} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/CommentServiceImpl.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/CommentServiceImpl.java deleted file mode 100644 index f3ff91e..0000000 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/CommentServiceImpl.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.sadtech.bot.gitlab.core.service.impl; - -import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.Answer; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; -import org.sadtech.bot.gitlab.context.domain.entity.Task; -import org.sadtech.bot.gitlab.context.domain.notify.comment.AnswerCommentNotify; -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.CommentRepository; -import org.sadtech.bot.gitlab.context.service.CommentService; -import org.sadtech.bot.gitlab.context.service.NotifyService; -import org.sadtech.bot.gitlab.context.service.TaskService; -import org.sadtech.haiti.context.domain.ExistsContainer; -import org.sadtech.haiti.core.service.AbstractSimpleManagerService; -import org.sadtech.haiti.core.util.Assert; -import org.springframework.context.annotation.Lazy; -import org.springframework.core.convert.ConversionService; - -import java.time.LocalDateTime; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -//@Service -public class CommentServiceImpl extends AbstractSimpleManagerService implements CommentService { - - private static final Pattern PATTERN = Pattern.compile("@[\\w]+"); - - private final CommentRepository commentRepository; - private final NotifyService notifyService; - private final TaskService taskService; - - private final ConversionService conversionService; - - public CommentServiceImpl( - CommentRepository commentRepository, - NotifyService notifyService, - @Lazy TaskService taskService, - ConversionService conversionService - ) { - super(commentRepository); - this.commentRepository = commentRepository; - this.notifyService = notifyService; - this.taskService = taskService; - this.conversionService = conversionService; - } - - @Override - public Long getLastCommentId() { - return commentRepository.findFirstByOrderByIdDesc().map(Comment::getId).orElse(0L); - } - - @Override - public List getAllBetweenDate(@NonNull LocalDateTime dateFrom, LocalDateTime dateTo) { - return commentRepository.findByCreateDateBetween(dateFrom, dateTo); - } - - @Override - public Comment create(@NonNull Comment comment) { - Assert.isNotNull(comment.getId(), "При создании объекта должен быть установлен идентификатор"); - comment.getAnswers().clear(); - final Comment newComment = commentRepository.save(comment); - notificationPersonal(comment); - return newComment; - } - - private void notificationPersonal(@NonNull Comment comment) { - Matcher matcher = PATTERN.matcher(comment.getMessage()); - Set recipientsLogins = new HashSet<>(); - while (matcher.find()) { - final String login = matcher.group(0).replace("@", ""); - recipientsLogins.add(login); - } - notifyService.send( - CommentNotify.builder() - .authorName(comment.getAuthor()) - .url(comment.getUrl()) - .message(comment.getMessage()) - .build() - ); - } - - @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()); - } - updateAnswer(oldComment, comment); - - return commentRepository.save(oldComment); - } - - @Override - public List getAllById(@NonNull Set ids) { - return commentRepository.findAllById(ids); - } - - @Override - public Comment convert(@NonNull Task task) { - taskService.deleteById(task.getId()); - final Comment comment = conversionService.convert(task, Comment.class); - return commentRepository.save(comment); - } - - @Override - public Set existsById(@NonNull Set ids) { - return commentRepository.existsById(ids); - } - - private void updateAnswer(Comment oldComment, Comment newComment) { - final Set oldAnswerIds = oldComment.getAnswers(); - final Set newAnswerIds = newComment.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()); - oldComment.getAnswers().clear(); - oldComment.setAnswers(existsNewAnswersIds); - if (!newAnswers.isEmpty()) { - notifyService.send( - AnswerCommentNotify.builder() - .url(oldComment.getUrl()) - .youMessage(newComment.getMessage()) - .answers( - newAnswers.stream() - .map(answerComment -> Answer.of(answerComment.getAuthor(), answerComment.getMessage())) - .collect(Collectors.toList()) - ) - .build() - ); - } - } - } - - @Override - public ExistsContainer existsById(@NonNull Collection collection) { - return null; - } - -} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/NoteServiceImpl.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/NoteServiceImpl.java new file mode 100644 index 0000000..1d211c9 --- /dev/null +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/NoteServiceImpl.java @@ -0,0 +1,140 @@ +package org.sadtech.bot.gitlab.core.service.impl; + +import lombok.NonNull; +import org.sadtech.bot.gitlab.context.domain.entity.Note; +import org.sadtech.bot.gitlab.context.domain.entity.Task; +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.CommentRepository; +import org.sadtech.bot.gitlab.context.service.NoteService; +import org.sadtech.bot.gitlab.context.service.NotifyService; +import org.sadtech.bot.gitlab.context.service.TaskService; +import org.sadtech.haiti.context.domain.ExistsContainer; +import org.sadtech.haiti.core.service.AbstractSimpleManagerService; +import org.springframework.context.annotation.Lazy; +import org.springframework.core.convert.ConversionService; + +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +//@Service +public class NoteServiceImpl extends AbstractSimpleManagerService implements NoteService { + + private static final Pattern PATTERN = Pattern.compile("@[\\w]+"); + + private final CommentRepository commentRepository; + private final NotifyService notifyService; + private final TaskService taskService; + + private final ConversionService conversionService; + + public NoteServiceImpl( + CommentRepository commentRepository, + NotifyService notifyService, + @Lazy TaskService taskService, + ConversionService conversionService + ) { + super(commentRepository); + this.commentRepository = commentRepository; + this.notifyService = notifyService; + this.taskService = taskService; + this.conversionService = conversionService; + } + + @Override + public Long getLastCommentId() { + return commentRepository.findFirstByOrderByIdDesc().map(Note::getId).orElse(0L); + } + + @Override + public List getAllBetweenDate(@NonNull LocalDateTime dateFrom, LocalDateTime dateTo) { + return commentRepository.findByCreateDateBetween(dateFrom, dateTo); + } + + @Override + public Note create(@NonNull Note note) { + final Note newNote = commentRepository.save(note); + notificationPersonal(note); + return newNote; + } + + private 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); + } + notifyService.send( + CommentNotify.builder() +// .authorName(note.getAuthor()) +// .url(note.getUrl()) +// .message(note.getMessage()) + .build() + ); + } + + @Override + public Note update(Note note) { + final Note oldNote = commentRepository.findById(note.getId()) + .orElseThrow(() -> new NotFoundException("Комментарий не найден")); + + updateAnswer(oldNote, note); + + return commentRepository.save(oldNote); + } + + @Override + public List getAllById(@NonNull Set ids) { + return commentRepository.findAllById(ids); + } + + @Override + public Note convert(@NonNull Task task) { + taskService.deleteById(task.getId()); + final Note note = conversionService.convert(task, Note.class); + return commentRepository.save(note); + } + + @Override + public Set existsById(@NonNull Set ids) { + return commentRepository.existsById(ids); + } + + 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 ExistsContainer existsById(@NonNull Collection collection) { + return null; + } + +} diff --git a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/TaskServiceImpl.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/TaskServiceImpl.java index 8ef19fe..e2365cd 100644 --- a/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/TaskServiceImpl.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/impl/TaskServiceImpl.java @@ -1,19 +1,17 @@ package org.sadtech.bot.gitlab.core.service.impl; import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.Answer; import org.sadtech.bot.gitlab.context.domain.TaskStatus; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; 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.domain.notify.comment.AnswerCommentNotify; import org.sadtech.bot.gitlab.context.domain.notify.comment.CommentNotify; 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.exception.NotFoundException; import org.sadtech.bot.gitlab.context.repository.TaskRepository; -import org.sadtech.bot.gitlab.context.service.CommentService; import org.sadtech.bot.gitlab.context.service.MergeRequestsService; +import org.sadtech.bot.gitlab.context.service.NoteService; import org.sadtech.bot.gitlab.context.service.NotifyService; import org.sadtech.bot.gitlab.context.service.TaskService; import org.sadtech.haiti.context.domain.ExistsContainer; @@ -28,7 +26,6 @@ import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.stream.Collectors; //@Service public class TaskServiceImpl extends AbstractSimpleManagerService implements TaskService { @@ -39,7 +36,7 @@ public class TaskServiceImpl extends AbstractSimpleManagerService im private final MergeRequestsService mergeRequestsService; private final NotifyService notifyService; - private final CommentService commentService; + private final NoteService noteService; private final ConversionService conversionService; @@ -47,14 +44,14 @@ public class TaskServiceImpl extends AbstractSimpleManagerService im TaskRepository taskRepository, MergeRequestsService mergeRequestsService, NotifyService notifyService, - CommentService commentService, + NoteService noteService, ConversionService conversionService ) { super(taskRepository); this.taskRepository = taskRepository; this.mergeRequestsService = mergeRequestsService; this.notifyService = notifyService; - this.commentService = commentService; + this.noteService = noteService; this.conversionService = conversionService; } @@ -114,29 +111,29 @@ public class TaskServiceImpl extends AbstractSimpleManagerService im } private void updateAnswer(Task oldTask, Task task) { - final Set oldAnswerIds = oldTask.getAnswers(); - final Set newAnswerIds = task.getAnswers(); - if (!oldAnswerIds.equals(newAnswerIds)) { - final Set existsNewAnswersIds = commentService.existsById(newAnswerIds); - final List newAnswers = commentService.getAllById(existsNewAnswersIds).stream() - .filter(comment -> !oldAnswerIds.contains(comment.getId())) - .collect(Collectors.toList()); - oldTask.getAnswers().clear(); - oldTask.setAnswers(existsNewAnswersIds); - if (!newAnswers.isEmpty()) { - notifyService.send( - AnswerCommentNotify.builder() - .url(oldTask.getUrl()) - .youMessage(oldTask.getDescription()) - .answers( - newAnswers.stream() - .map(answerComment -> Answer.of(answerComment.getAuthor(), answerComment.getMessage())) - .collect(Collectors.toList()) - ) - .build() - ); - } - } +// final Set oldAnswerIds = oldTask.getAnswers(); +// final Set newAnswerIds = task.getAnswers(); +// if (!oldAnswerIds.equals(newAnswerIds)) { +// final Set existsNewAnswersIds = noteService.existsById(newAnswerIds); +// final List newAnswers = noteService.getAllById(existsNewAnswersIds).stream() +// .filter(comment -> !oldAnswerIds.contains(comment.getId())) +// .collect(Collectors.toList()); +// oldTask.getAnswers().clear(); +// oldTask.setAnswers(existsNewAnswersIds); +// if (!newAnswers.isEmpty()) { +// notifyService.send( +// AnswerCommentNotify.builder() +// .url(oldTask.getUrl()) +// .youMessage(oldTask.getDescription()) +// .answers( +// newAnswers.stream() +// .map(answerComment -> Answer.of(answerComment.getAuthor(), answerComment.getMessage())) +// .collect(Collectors.toList()) +// ) +// .build() +// ); +// } +// } } @Override @@ -145,9 +142,9 @@ public class TaskServiceImpl extends AbstractSimpleManagerService im } @Override - public Task convert(@NonNull Comment comment) { - commentService.deleteById(comment.getId()); - final Task task = conversionService.convert(comment, Task.class); + public Task convert(@NonNull Note note) { + noteService.deleteById(note.getId()); + final Task task = conversionService.convert(note, Task.class); final Task newTask = taskRepository.save(task); notifyNewTask(newTask); return newTask; diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/MergeRequestParser.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/MergeRequestParser.java similarity index 98% rename from bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/MergeRequestParser.java rename to bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/MergeRequestParser.java index 80dfe36..b802898 100644 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/MergeRequestParser.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/MergeRequestParser.java @@ -1,4 +1,4 @@ -package org.sadtech.bot.gitlab.app.service.parser; +package org.sadtech.bot.gitlab.core.service.parser; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; 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 new file mode 100644 index 0000000..b6aba65 --- /dev/null +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/NoteParser.java @@ -0,0 +1,191 @@ +package org.sadtech.bot.gitlab.core.service.parser; + +import lombok.NonNull; +import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest; +import org.sadtech.bot.gitlab.context.service.MergeRequestsService; +import org.sadtech.bot.gitlab.context.service.ProjectService; +import org.sadtech.bot.gitlab.core.config.properties.GitlabProperty; +import org.sadtech.bot.gitlab.core.config.properties.InitProperty; +import org.sadtech.bot.gitlab.core.config.properties.PersonProperty; +import org.sadtech.bot.gitlab.sdk.domain.NoteJson; +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 java.text.MessageFormat; +import java.util.List; + +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, и у них таска это то же самое что и комментарий, только с флагом

+ */ +//@Component +public class NoteParser { + + public static final int COUNT = 100; + + private final ProjectService projectService; + private final MergeRequestsService mergeRequestsService; + private final ConversionService conversionService; + + private final GitlabProperty gitlabProperty; + private final InitProperty initProperty; + private final PersonProperty personProperty; + + public NoteParser( + ProjectService projectService, MergeRequestsService mergeRequestsService, + ConversionService conversionService, + GitlabProperty gitlabProperty, + InitProperty initProperty, + PersonProperty personProperty) { + this.projectService = projectService; + this.mergeRequestsService = mergeRequestsService; + this.conversionService = conversionService; + this.gitlabProperty = gitlabProperty; + this.initProperty = initProperty; + this.personProperty = personProperty; + } + + 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) { + final List noteJsons = HttpParse.request(MessageFormat.format(gitlabProperty.getUrlPullRequestComment(), mergeRequest.getProjectId(), mergeRequest.getTwoId())) + .header(ACCEPT) + .header(AUTHORIZATION, BEARER + personProperty.getToken()) + .executeList(NoteJson.class); + + } + + mergeRequestSheet = mergeRequestsService.getAll(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()) +// ); +// } +// commentId++; +// } +// 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()); +// } +// ) +// .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())); +// } +// ) +// .collect(Collectors.toList()); +// } + + private String generateUrl(@NonNull Long id, @NonNull String pullRequestUrl) { + return MessageFormat.format("{0}/overview?commentId={1}", pullRequestUrl, Long.toString(id)); + } + + private String getCommentUrl(long commentId, MergeRequest mergeRequest) { +// return gitlabProperty.getUrlPullRequestComment() +// .replace("{projectKey}", mergeRequest.getProjectKey()) +// .replace("{repositorySlug}", mergeRequest.getRepositorySlug()) +// .replace("{pullRequestId}", mergeRequest.getBitbucketId().toString()) +// .replace("{commentId}", String.valueOf(commentId)); + return null; + } + + public void scanOldComment() { +// final List comments = commentService.getAllBetweenDate( +// LocalDateTime.now().minusDays(20), LocalDateTime.now() +// ); +// for (Comment oldComment : comments) { +// final Optional optCommentJson = Utils.urlToJson( +// oldComment.getUrlApi(), +// gitlabProperty.getToken(), +// CommentJson.class +// ); +// if (optCommentJson.isPresent()) { +// final CommentJson json = optCommentJson.get(); +// if (Severity.BLOCKER.equals(json.getSeverity())) { +// taskService.convert(oldComment); +// } else { +// final Comment newComment = conversionService.convert(json, Comment.class); +// commentService.update(newComment); +// } +// } else { +// commentService.deleteById(oldComment.getId()); +// } +// } + } + + public void scanOldTask() { +// final List tasks = taskService.getAllBetweenDate( +// LocalDateTime.now().minusDays(20), LocalDateTime.now() +// ); +// for (Task oldTask : tasks) { +// final Optional optCommentJson = Utils.urlToJson( +// oldTask.getUrlApi(), +// gitlabProperty.getToken(), +// CommentJson.class +// ); +// if (optCommentJson.isPresent()) { +// final CommentJson json = optCommentJson.get(); +// if (Severity.NORMAL.equals(json.getSeverity())) { +// commentService.convert(oldTask); +// } else { +// final Task newTask = conversionService.convert(json, Task.class); +// taskService.update(newTask); +// } +// } else { +// taskService.deleteById(oldTask.getId()); +// } +// } + } + +} diff --git a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/ProjectParser.java b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/ProjectParser.java similarity index 53% rename from bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/ProjectParser.java rename to bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/ProjectParser.java index 16aa2dc..275d228 100644 --- a/bot-app/src/main/java/org/sadtech/bot/gitlab/app/service/parser/ProjectParser.java +++ b/bot-core/src/main/java/org/sadtech/bot/gitlab/core/service/parser/ProjectParser.java @@ -1,14 +1,12 @@ -package org.sadtech.bot.gitlab.app.service.parser; +package org.sadtech.bot.gitlab.core.service.parser; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.sadtech.bot.gitlab.app.config.property.CommentSchedulerProperty; import org.sadtech.bot.gitlab.context.domain.entity.Person; import org.sadtech.bot.gitlab.context.domain.entity.Project; import org.sadtech.bot.gitlab.context.service.PersonService; import org.sadtech.bot.gitlab.context.service.ProjectService; import org.sadtech.bot.gitlab.core.config.properties.GitlabProperty; -import org.sadtech.bot.gitlab.core.config.properties.InitProperty; import org.sadtech.bot.gitlab.core.config.properties.PersonProperty; import org.sadtech.bot.gitlab.sdk.domain.PersonJson; import org.sadtech.bot.gitlab.sdk.domain.ProjectJson; @@ -17,12 +15,11 @@ import org.sadtech.haiti.context.exception.ConvertException; import org.sadtech.haiti.utils.network.HttpHeader; import org.sadtech.haiti.utils.network.HttpParse; import org.springframework.core.convert.ConversionService; -import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.text.MessageFormat; import java.util.Collection; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -40,6 +37,9 @@ import static org.sadtech.haiti.utils.network.HttpParse.BEARER; @RequiredArgsConstructor public class ProjectParser { + public static final String PRIVATE = "&visibility=private"; + public static final String OWNER = "&owned=true"; + private final ProjectService projectService; private final PersonService personService; @@ -47,30 +47,38 @@ public class ProjectParser { private final GitlabProperty gitlabProperty; private final PersonProperty personProperty; - private final CommentSchedulerProperty commentSchedulerProperty; - private final InitProperty initProperty; - @Scheduled(cron = "0 */1 * * * *") - public void parseNewProject() { - final List projectJsons = HttpParse.request(gitlabProperty.getUrlProject()) - .header(ACCEPT) - .header(HttpHeader.of(AUTHORIZATION, BEARER + personProperty.getToken())) - .executeList(ProjectJson.class); + public void parseAllPrivateProject() { + parseProjects(PRIVATE); + } - final Set jsonIds = projectJsons.stream() - .map(ProjectJson::getId) - .collect(Collectors.toSet()); + public void parseAllProjectOwner() { + parseProjects(OWNER); + } - createNewPersons(projectJsons); + private void parseProjects(String param) { + int page = 0; + List projectJsons = getProjectJsons(page, param); - final ExistsContainer existsContainer = projectService.existsById(jsonIds); - final List newProjects = projectJsons.stream() - .filter(json -> existsContainer.getIdNoFound().contains(json.getId())) - .map(json -> conversionService.convert(json, Project.class)) - .collect(Collectors.toList()); + while (!projectJsons.isEmpty()) { - if (!newProjects.isEmpty()) { - projectService.createAll(newProjects); + final Set jsonIds = projectJsons.stream() + .map(ProjectJson::getId) + .collect(Collectors.toSet()); + + createNewPersons(projectJsons); + + final ExistsContainer existsContainer = projectService.existsById(jsonIds); + final List newProjects = projectJsons.stream() + .filter(json -> existsContainer.getIdNoFound().contains(json.getId())) + .map(json -> conversionService.convert(json, Project.class)) + .collect(Collectors.toList()); + + if (!newProjects.isEmpty()) { + projectService.createAll(newProjects); + } + + projectJsons = getProjectJsons(++page, param); } } @@ -86,16 +94,11 @@ public class ProjectParser { final List newPersons = notFoundId.stream() .map( - userId -> { - final Optional execute = HttpParse.request(gitlabProperty.getUsersUrl() + "/" + userId) - .header(ACCEPT) - .header(AUTHORIZATION, BEARER + personProperty.getToken()) - .execute(PersonJson.class); - final Optional person = execute - .map(json -> conversionService.convert(json, Person.class)); - return person - .orElseThrow(() -> new ConvertException("Ошибка преобразования нового пользователя")); - } + userId -> HttpParse.request(gitlabProperty.getUsersUrl() + "/" + userId) + .header(ACCEPT) + .header(AUTHORIZATION, BEARER + personProperty.getToken()) + .execute(PersonJson.class) + .map(json -> conversionService.convert(json, Person.class)).orElseThrow(() -> new ConvertException("Ошибка преобразования нового пользователя")) ).collect(Collectors.toList()); personService.createAll(newPersons); @@ -103,4 +106,13 @@ public class ProjectParser { } } + private List getProjectJsons(int page, String... params) { + String param = String.join("", params); + final String url = MessageFormat.format(gitlabProperty.getUrlProject(), page); + return HttpParse.request(url + param) + .header(ACCEPT) + .header(HttpHeader.of(AUTHORIZATION, BEARER + personProperty.getToken())) + .executeList(ProjectJson.class); + } + } diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/AppSettingRepositoryImpl.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/AppSettingRepositoryImpl.java new file mode 100644 index 0000000..fbcd2e8 --- /dev/null +++ b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/AppSettingRepositoryImpl.java @@ -0,0 +1,21 @@ +package org.sadtech.bot.gitlab.data.impl; + +import org.sadtech.bot.gitlab.context.domain.entity.AppSetting; +import org.sadtech.bot.gitlab.context.repository.AppSettingRepository; +import org.sadtech.haiti.database.repository.manager.AbstractSimpleManagerRepository; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * // TODO: 16.01.2021 Добавить описание. + * + * @author upagge 16.01.2021 + */ +@Repository +public class AppSettingRepositoryImpl extends AbstractSimpleManagerRepository implements AppSettingRepository { + + public AppSettingRepositoryImpl(JpaRepository jpaRepository) { + super(jpaRepository); + } + +} diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/CommentRepositoryImpl.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/CommentRepositoryImpl.java index 3ada4be..eed6766 100644 --- a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/CommentRepositoryImpl.java +++ b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/impl/CommentRepositoryImpl.java @@ -1,7 +1,7 @@ package org.sadtech.bot.gitlab.data.impl; import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; +import org.sadtech.bot.gitlab.context.domain.entity.Note; import org.sadtech.bot.gitlab.context.repository.CommentRepository; import org.sadtech.bot.gitlab.data.jpa.CommentRepositoryJpa; import org.sadtech.haiti.database.repository.manager.AbstractSimpleManagerRepository; @@ -17,7 +17,7 @@ import java.util.Set; * @author upagge 08.09.2020 */ //@Repository -public class CommentRepositoryImpl extends AbstractSimpleManagerRepository implements CommentRepository { +public class CommentRepositoryImpl extends AbstractSimpleManagerRepository implements CommentRepository { private final CommentRepositoryJpa repositoryJpa; @@ -27,17 +27,17 @@ public class CommentRepositoryImpl extends AbstractSimpleManagerRepository findFirstByOrderByIdDesc() { + public Optional findFirstByOrderByIdDesc() { return repositoryJpa.findFirstByOrderByIdDesc(); } @Override - public List findByCreateDateBetween(LocalDateTime dateFrom, LocalDateTime dateTo) { + public List findByCreateDateBetween(LocalDateTime dateFrom, LocalDateTime dateTo) { return repositoryJpa.findByCreateDateBetween(dateFrom, dateTo); } @Override - public List findAllById(@NonNull Set ids) { + public List findAllById(@NonNull Set ids) { return repositoryJpa.findAllById(ids); } diff --git a/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/AppSettingJpaRepository.java b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/AppSettingJpaRepository.java new file mode 100644 index 0000000..0dab57b --- /dev/null +++ b/bot-data/src/main/java/org/sadtech/bot/gitlab/data/jpa/AppSettingJpaRepository.java @@ -0,0 +1,12 @@ +package org.sadtech.bot.gitlab.data.jpa; + +import org.sadtech.bot.gitlab.context.domain.entity.AppSetting; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * // TODO: 16.01.2021 Добавить описание. + * + * @author upagge 16.01.2021 + */ +public interface AppSettingJpaRepository extends JpaRepository { +} 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 index fc4e46a..86c9676 100644 --- 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 @@ -1,7 +1,7 @@ package org.sadtech.bot.gitlab.data.jpa; import lombok.NonNull; -import org.sadtech.bot.gitlab.context.domain.entity.Comment; +import org.sadtech.bot.gitlab.context.domain.entity.Note; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.NoRepositoryBean; @@ -11,13 +11,13 @@ import java.util.Optional; import java.util.Set; @NoRepositoryBean -public interface CommentRepositoryJpa extends JpaRepository { +public interface CommentRepositoryJpa extends JpaRepository { - Optional findFirstByOrderByIdDesc(); + Optional findFirstByOrderByIdDesc(); - List findByCreateDateBetween(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); + List findByCreateDateBetween(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); -// @Query("SELECT c.id FROM Comment c WHERE c.id IN :ids") + // @Query("SELECT c.id FROM Comment c WHERE c.id IN :ids") Set existsAllById(@NonNull Set ids); } diff --git a/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/CommentJson.java b/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/CommentJson.java deleted file mode 100644 index 4fe6eb4..0000000 --- a/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/CommentJson.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.sadtech.bot.gitlab.sdk.domain; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import lombok.Data; -import org.sadtech.bot.gitlab.sdk.utils.LocalDateTimeFromEpochDeserializer; - -import java.time.LocalDateTime; -import java.util.List; - -@Data -public class CommentJson { - - private Long id; - private Integer version; - private String text; - private UserJson author; - private List comments; - - private Severity severity; - - private CommentState state; - - @JsonDeserialize(using = LocalDateTimeFromEpochDeserializer.class) - private LocalDateTime createdDate; - - @JsonDeserialize(using = LocalDateTimeFromEpochDeserializer.class) - private LocalDateTime updatedDate; - - private Long customPullRequestId; - - private String customCommentApiUrl; - -} diff --git a/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/NoteJson.java b/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/NoteJson.java new file mode 100644 index 0000000..62c2b03 --- /dev/null +++ b/gitlab-sdk/src/main/java/org/sadtech/bot/gitlab/sdk/domain/NoteJson.java @@ -0,0 +1,41 @@ +package org.sadtech.bot.gitlab.sdk.domain; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class NoteJson { + + private Long id; + private String type; + private String body; + + @JsonProperty("created_at") + private LocalDateTime created; + + @JsonProperty("updated_at") + private LocalDateTime updated; + + private PersonJson author; + private boolean system; + + @JsonProperty("noteable_id") + private Long noteableId; + + @JsonProperty("noteable_type") + private String noteableType; + + private Boolean resolveable; + + private Boolean resolved; + + @JsonProperty("resolved_by") + private PersonJson resolvedBy; + + @JsonProperty("noteable_iid") + private Long noteableIid; + + +} diff --git a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/config/TelegramBotConfig.java b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/config/TelegramBotConfig.java index 027d25b..ea3f9be 100644 --- a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/config/TelegramBotConfig.java +++ b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/config/TelegramBotConfig.java @@ -8,7 +8,7 @@ import org.sadtech.bot.godfather.telegram.listen.EventDistributor; import org.sadtech.bot.godfather.telegram.listen.EventDistributorImpl; import org.sadtech.bot.godfather.telegram.listen.TelegramConnect; import org.sadtech.bot.godfather.telegram.listen.TelegramSender; -import org.sadtech.social.bot.domain.unit.AnswerText; +import org.sadtech.social.bot.domain.unit.AnswerCheck; import org.sadtech.social.core.domain.content.Mail; import org.sadtech.social.core.repository.impl.local.MailRepositoryList; import org.sadtech.social.core.service.MailService; @@ -45,10 +45,11 @@ public class TelegramBotConfig { public MessageAutoresponderTelegram messageAutoresponderTelegram( Sending sending, MessageService messageService, - UnitPointerRepository unitPointerRepository + UnitPointerRepository unitPointerRepository, + AnswerCheck checkFirstStart ) { return new MessageAutoresponderTelegram( - Collections.singleton(AnswerText.of("TEST")), + Collections.singleton(checkFirstStart), sending, messageService, unitPointerRepository diff --git a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/scheduler/CheckNewMessage.java b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/scheduler/CheckNewMessage.java index fbd1835..fc3800f 100644 --- a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/scheduler/CheckNewMessage.java +++ b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/scheduler/CheckNewMessage.java @@ -3,8 +3,9 @@ package org.sadtech.bot.gitlab.telegram.scheduler; import lombok.RequiredArgsConstructor; import org.sadtech.bot.godfather.telegram.autoresponder.MessageAutoresponderTelegram; import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; -//@Service +@Service @RequiredArgsConstructor public class CheckNewMessage { diff --git a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/NotifySettingUnit.java b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/NotifySettingUnit.java index b32ce78..ff9fb66 100644 --- a/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/NotifySettingUnit.java +++ b/telegram-bot/src/main/java/org/sadtech/bot/gitlab/telegram/unit/NotifySettingUnit.java @@ -1,58 +1,47 @@ package org.sadtech.bot.gitlab.telegram.unit; -import lombok.Getter; -import lombok.NonNull; import lombok.RequiredArgsConstructor; -import org.sadtech.bot.gitlab.context.exception.NotFoundException; import org.sadtech.bot.gitlab.context.service.NotifyService; -import org.sadtech.social.bot.domain.unit.AnswerProcessing; -import org.sadtech.social.bot.domain.unit.AnswerText; -import org.sadtech.social.core.domain.BoxAnswer; -import org.sadtech.social.core.domain.content.Message; -import org.sadtech.social.core.utils.KeyBoards; -import org.springframework.context.annotation.Bean; - -import java.util.Arrays; -import java.util.stream.Collectors; +import org.springframework.context.annotation.Configuration; /** * // TODO: 20.09.2020 Добавить описание. * * @author upagge 20.09.2020 */ -//@Configuration +@Configuration @RequiredArgsConstructor public class NotifySettingUnit { private final NotifyService notifyService; - @Bean - public AnswerText notifySetting( - AnswerProcessing disableNotifications - ) { - return AnswerText.builder() - .boxAnswer( - BoxAnswer.builder() - .message("Вы можете полностью остановить уведомления от бота") - .keyBoard( - KeyBoards.verticalDuoMenuString( - Arrays.stream(DisableMenu.values()) - .map(DisableMenu::getName) - .collect(Collectors.toList()) - ) - ) - .build() - ) - .phrase("Уведомления") - .nextUnit(disableNotifications) - .build(); - } +// @Bean +// public AnswerText notifySetting( +// AnswerProcessing disableNotifications +// ) { +// return AnswerText.builder() +// .boxAnswer( +// BoxAnswer.builder() +// .message("Вы можете полностью остановить уведомления от бота") +// .keyBoard( +// KeyBoards.verticalDuoMenuString( +// Arrays.stream(DisableMenu.values()) +// .map(DisableMenu::getName) +// .collect(Collectors.toList()) +// ) +// ) +// .build() +// ) +// .phrase("Уведомления") +// .nextUnit(disableNotifications) +// .build(); +// } - @Bean - public AnswerProcessing disableNotifications() { - return AnswerProcessing.builder() - .processingData( - message -> { +// @Bean +// public AnswerProcessing disableNotifications() { +// return AnswerProcessing.builder() +// .processingData( +// message -> { // final Person person = personService.getByTelegramId(message.getPersonId()) // .orElseThrow(() -> new NotFoundException("Не найдено")); // final NotifySetting notifySetting = notifyService.getSetting(person.getLogin()) @@ -62,35 +51,35 @@ public class NotifySettingUnit { // ); // notifyService.saveSettings(notifySetting); // return BoxAnswer.of("Настройки сохранены"); - return null; - } - ) - .build(); - } +// return null; +// } +// ) +// .build(); +// } - @Getter - @RequiredArgsConstructor - private enum DisableMenu { - - TURN_ON("Включить", 0), - TURN_OFF("Выключить", 525600), - DISABLE_15_MIN("15 мин", 15), - DISABLE_2_HOUR("2 часа", 120), - DISABLE_30_MIN("30 мин", 30), - DISABLE_4_HOUR("4 часа", 240), - DISABLE_60_MIN("60 мин", 60), - DISABLE_8_HOUR("8 часов", 480); - - private final String name; - private final int minutes; - - public static DisableMenu from(@NonNull String name) { - return Arrays.stream(DisableMenu.values()) - .filter(disableMenu -> disableMenu.getName().equals(name)) - .findFirst() - .orElseThrow(() -> new NotFoundException("Не найдено")); - } - - } +// @Getter +// @RequiredArgsConstructor +// private enum DisableMenu { +// +// TURN_ON("Включить", 0), +// TURN_OFF("Выключить", 525600), +// DISABLE_15_MIN("15 мин", 15), +// DISABLE_2_HOUR("2 часа", 120), +// DISABLE_30_MIN("30 мин", 30), +// DISABLE_4_HOUR("4 часа", 240), +// DISABLE_60_MIN("60 мин", 60), +// DISABLE_8_HOUR("8 часов", 480); +// +// private final String name; +// private final int minutes; +// +// public static DisableMenu from(@NonNull String name) { +// return Arrays.stream(DisableMenu.values()) +// .filter(disableMenu -> disableMenu.getName().equals(name)) +// .findFirst() +// .orElseThrow(() -> new NotFoundException("Не найдено")); +// } +// +// } } 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 71f6fe7..13fce7f 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 @@ -1,93 +1,117 @@ package org.sadtech.bot.gitlab.telegram.unit; import lombok.RequiredArgsConstructor; -import org.sadtech.bot.gitlab.telegram.service.unit.TaskProcessing; -import org.sadtech.bot.gitlab.telegram.utils.GeneratorKeyBoards; +import org.sadtech.bot.gitlab.context.domain.AppLocale; +import org.sadtech.bot.gitlab.context.service.AppSettingService; +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.Message; import org.sadtech.social.core.utils.KeyBoards; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; /** * TODO: Добавить описание класса. * * @author upagge [30.01.2020] */ -//@Configuration +@Configuration @RequiredArgsConstructor public class UnitConfig { - @Bean - public AnswerText menu( - AnswerProcessing getTasks, - AnswerText menuPullRequest, - AnswerText settings + public AnswerCheck checkFirstStart( + AppSettingService settingService, + AnswerText textCheckLanguage ) { - return AnswerText.builder() - .boxAnswer( - BoxAnswer.builder() - .message("Привет, выбери пункт меню!") - .keyBoard(GeneratorKeyBoards.menu()) - .build() + return AnswerCheck.builder() + .check( + message -> settingService.isFirstStart() ) - .nextUnit(getTasks) - .nextUnit(menuPullRequest) - .nextUnit(settings) + .unitTrue(textCheckLanguage) .build(); } @Bean - public AnswerText settings( - AnswerText notifySetting + public AnswerText textCheckLanguage( + AnswerProcessing checkLanguage ) { return AnswerText.builder() .boxAnswer( BoxAnswer.builder() - .message("Здесь вы можете персонализировать бота") - .keyBoard( - KeyBoards.verticalMenuString("Уведомления") - ) + .message("Hi :)\n\nLet's choose a language for.") + .keyBoard(KeyBoards.verticalDuoMenuString("Русский", "English")) .build() ) - .phrase("Настройки") - .nextUnit(notifySetting) + .nextUnit(checkLanguage) .build(); } @Bean - public AnswerProcessing getTasks( - TaskProcessing taskProcessing + public AnswerProcessing checkLanguage( + AppSettingService settingService, + AnswerText textParserPrivateProject + ) { + return AnswerProcessing + .builder() + .processingData( + message -> { + final AppLocale appLocale = AppLocale.of(message.getText()); + settingService.setLocale(appLocale); + return BoxAnswer.of( + settingService.getMessage("ui.lang_changed") + ); + } + ) + .nextUnit(textParserPrivateProject) + .build(); + } + + @Bean + public AnswerText textParserPrivateProject( + AnswerCheck checkParserPrivateProject, + AppSettingService settingService + ) { + return AnswerText.builder() + .boxAnswer( + BoxAnswer.builder() + .message(settingService.getMessage("ui.monitor_private_projects")) + .keyBoard(KeyBoards.verticalDuoMenuString( + settingService.getMessage("main.yes"), settingService.getMessage("main.no") + )) + .build() + ) + .activeType(UnitActiveType.AFTER) + .nextUnit(checkParserPrivateProject) + .build(); + } + + @Bean + public AnswerCheck checkParserPrivateProject( + AppSettingService appSettingService, + AnswerProcessing parserPrivateProject + ) { + return AnswerCheck.builder() + .check( + message -> appSettingService.getMessage("main.yes").equalsIgnoreCase(message.getText()) + ) + .unitTrue(parserPrivateProject) + .build(); + } + + @Bean + public AnswerProcessing parserPrivateProject( + ProjectParser projectParser, + AppSettingService settingService ) { return AnswerProcessing.builder() - .processingData(taskProcessing) - .phrase("Мои задачи") - .build(); - } - - @Bean - public AnswerProcessing noRegister() { - return AnswerProcessing.builder() - .processingData(message -> - BoxAnswer.builder() - .message("Привет :)\nЭтот бот сообщает о появлении новых ПР и об изменениях в старых\n\n" + - "Теперь когда ты знаешь правду, ты просто обязан отправь POST запрос на адрес " + - "http://192.168.236.164:8018/api/user/reg\n\n" + - "В теле запроса укажи следующее:\n\n" + - "{\n" + - "\t\"telegramId\": " + message.getPersonId() + ",\n" + - "\t\"login\": \"apetrov\",\n" + - "\t\"token\": \"token value\"\n" + - "}" + - "\n\n" + - "ВНИМАНИЕ!!!\ntelegramId не менять; login как в bitbucket; токен получать [тут](http://192.168.236.164:7990/plugins/servlet/access-tokens/manage)" + - "\n-- -- --\n" + - "По всем вопросам обращаться к @uPagge") - .build() - ) + .processingData(message -> { + projectParser.parseAllPrivateProject(); + return BoxAnswer.of(settingService.getMessage("ui.monitor_project_private_success")); + }) .build(); }