Возможность изменить язык

This commit is contained in:
uPagge 2021-01-16 21:35:29 +03:00
parent 44949a650f
commit 87bc00e0ee
No known key found for this signature in database
GPG Key ID: 964B40928E4C9088
31 changed files with 460 additions and 503 deletions

View File

@ -33,10 +33,10 @@ gitlab-bot:
token: ${GITLAB_PERSONAL_TOKEN} token: ${GITLAB_PERSONAL_TOKEN}
gitlab: gitlab:
url-project: ${GITLAB_URL}/api/v4/projects?page={0}&per_page=100 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-open: ${GITLAB_URL}/api/v4/projects/{0}/merge_requests?state=opened&page={1}&per_page=100
url-pull-request-close: ${GITLAB_URL} url-pull-request-close: ${GITLAB_URL}
url-pull-request-comment: ${GITLAB_URL}/api/v4/projects/19/merge_requests/8/notes url-pull-request-comment: ${GITLAB_URL}/api/v4/projects/{0}/merge_requests/{1}/notes
url-pull-request: ${GITLAB_URL}/api/v4/projects/{0}/merge_requests/{1} url-pull-request: ${GITLAB_URL}/api/v4/projects/{0}/merge_requests/{1}?page={2}&per_page=100
user-url: ${GITLAB_URL}/api/v4/user user-url: ${GITLAB_URL}/api/v4/user
users-url: ${GITLAB_URL}/api/v4/users users-url: ${GITLAB_URL}/api/v4/users
teamcity: teamcity:

View File

@ -5,3 +5,21 @@ ui.monitor_private_projects=Start tracking private projects?
ui.monitor_project_private_success=Projects have been successfully added to tracking ui.monitor_project_private_success=Projects have been successfully added to tracking
ui.monitor_owner_projects=Start tracking public projects that you own? ui.monitor_owner_projects=Start tracking public projects that you own?
ui.setup_finished=Configuration completed successfully ui.setup_finished=Configuration completed successfully
ui.menu.header=This is the bot menu, select a new item
ui.menu.task=My tasks
ui.menu.mr=Merge Request
ui.menu.setting=Settings
ui.menu.add_mr=Add project
ui.menu.setting.text=This is the settings menu
ui.menu.setting.language=Language settings
ui.menu.setting.language.text=Choose your language
notify.pr.new={0} *New PullRequest | {1}*{2}[{3}]({4}){5}{2}{9}: {10} {12} {11}\n{7}: {8}
notify.pr.forgotten={0} *MergeRequest Review Reminder | {4}*{3}[{1}]({2})
notify.pr.conflict={0} *Attention! MergeRequest conflict | {4}*{1}[{2}]({3})
notify.pr.smart={0} *MergeRequest Reminder | {6}*{3}[{1}]({2}){3}{4} изменил свое решение на {5}
notify.pr.state={0} *MergeRequest status changed | {7}*{1}[{2}]({3}){1}{4} {5} {6}
notify.pr.update={0} *MergeRequest update | {6}*{3}[{1}]({2}){3}{4}: {5}
notify.task.close={0} *Closed [task]({1}){2}*{3}*: {4}
notify.task.new={0} *New [task]({1}) assigned{2}*{3}*: {4}
notify.project.new={0} *New project*{1}[{2}]({3}){1}{4}{5}: {6}
notify.comment.bell={0} *New mention* | [MR]({1}){2}*{3}*: {4}

View File

@ -5,3 +5,21 @@ ui.monitor_private_projects=Начать отслеживать приватны
ui.monitor_project_private_success=Проекты успешно добавлены в отслеживание ui.monitor_project_private_success=Проекты успешно добавлены в отслеживание
ui.monitor_owner_projects=Начать отслеживать публичные проекты, владельцем которых вы являетесь? ui.monitor_owner_projects=Начать отслеживать публичные проекты, владельцем которых вы являетесь?
ui.setup_finished=Настройка успешно завершена ui.setup_finished=Настройка успешно завершена
ui.menu.header=Это меню бота, выберите новый пункт
ui.menu.task=Мои задачи
ui.menu.mr=Merge Request
ui.menu.setting=Настройки
ui.menu.add_mr=Добавить проект
ui.menu.setting.text=Это меню настроек
ui.menu.setting.language=Настройки языка
ui.menu.setting.language.text=Выберете язык
notify.pr.new={0} *Новый PullRequest | {1}*{2}[{3}]({4}){5}{2}{9}: {10} {12} {11}\n{7}: {8}
notify.pr.forgotten={0} *Напоминание о просмотре PullRequest | {4}*{3}[{1}]({2})
notify.pr.conflict={0} *Внимание! Конфликт в MergeRequest | {4}*{1}[{2}]({3})
notify.pr.smart={0} *Напоминание о MergeRequest | {6}*{3}[{1}]({2}){3}{4} изменил свое решение на {5}
notify.pr.state={0} *Изменился статус MergeRequest | {7}*{1}[{2}]({3}){1}{4} {5} {6}
notify.pr.update={0} *Обновление MergeRequest | {6}*{3}[{1}]({2}){3}{4}: {5}
notify.task.close={0} *Закрыта* [задача]({1}){2}*{3}*: {4}
notify.task.new={0} *Назначена новая* [задача]({1}){2}*{3}*: {4}
notify.project.new={0} *Новый Проект*{1}[{2}]({3}){1}{4}{5}: {6}
notify.comment.bell={0} *Новое упоминание* | [MR]({1}){2}*{3}*: {4}

View File

@ -6,8 +6,12 @@ import lombok.Setter;
import org.sadtech.haiti.context.domain.BasicEntity; import org.sadtech.haiti.context.domain.BasicEntity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
@ -18,6 +22,9 @@ import java.time.LocalDateTime;
@Entity @Entity
@Table(name = "note") @Table(name = "note")
@EqualsAndHashCode(onlyExplicitlyIncluded = true) @EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("null")
public class Note implements BasicEntity<Long> { public class Note implements BasicEntity<Long> {
@Id @Id

View File

@ -1,72 +1,12 @@
package org.sadtech.bot.gitlab.context.domain.entity; package org.sadtech.bot.gitlab.context.domain.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.sadtech.bot.gitlab.context.domain.TaskStatus;
import org.sadtech.haiti.context.domain.BasicEntity;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
//@Entity //@Entity
@Getter @Getter
@Setter @Setter
//@Table(name = "task") //@Table(name = "task")
@EqualsAndHashCode(onlyExplicitlyIncluded = true) public class Task extends Note {
public class Task implements BasicEntity<Long> {
@Id
@Column(name = "id")
@EqualsAndHashCode.Include
private Long id;
/**
* Описание задачи
*/
@Column(name = "description")
private String description;
@Enumerated(EnumType.STRING)
@Column(name = "status")
private TaskStatus status;
@Column(name = "create_date")
private LocalDateTime createDate;
@Column(name = "pull_request_id")
private Long pullRequestId;
@Column(name = "url")
private String url;
@Column(name = "url_api")
private String urlApi;
/**
* Версия объекта в битбакет
*/
@Column(name = "bitbucket_version")
private Integer bitbucketVersion;
@Column(name = "author_login")
private String author;
@Column(name = "responsible_login")
private String responsible;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "task_comments", joinColumns = @JoinColumn(name = "task_id"))
@Column(name = "comment_id")
private Set<Long> answers = new HashSet<>();
} }

View File

@ -3,6 +3,7 @@ package org.sadtech.bot.gitlab.context.domain.notify;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest; import org.sadtech.bot.gitlab.context.domain.entity.MergeRequest;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.MessageUtils; import org.sadtech.bot.gitlab.context.utils.MessageUtils;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import org.sadtech.bot.gitlab.context.utils.UpdateDataComparator; import org.sadtech.bot.gitlab.context.utils.UpdateDataComparator;
@ -38,7 +39,7 @@ public class GoodMorningNotify extends Notify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
StringBuilder message = new StringBuilder().append(Smile.SUN).append(" *Доброе утро, ").append(personName).append("* ").append(Smile.SUN).append(Smile.TWO_BR); StringBuilder message = new StringBuilder().append(Smile.SUN).append(" *Доброе утро, ").append(personName).append("* ").append(Smile.SUN).append(Smile.TWO_BR);
if (!mergeRequestsReviews.isEmpty()) { if (!mergeRequestsReviews.isEmpty()) {
message.append("Необходимо проверить ").append(mergeRequestsReviews.size()).append(" ПР:").append(Smile.BR); message.append("Необходимо проверить ").append(mergeRequestsReviews.size()).append(" ПР:").append(Smile.BR);

View File

@ -1,10 +1,9 @@
package org.sadtech.bot.gitlab.context.domain.notify; package org.sadtech.bot.gitlab.context.domain.notify;
import lombok.Builder; import lombok.Builder;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
/** /**
* // TODO: 15.01.2021 Добавить описание. * // TODO: 15.01.2021 Добавить описание.
* *
@ -26,15 +25,12 @@ public class NewProjectNotify extends Notify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
return MessageFormat.format( return settingService.getMessage(
"{0} *Новый Проект*{1}" + "notify.project.new",
"[{2}]({3}){1}" + Smile.FUN.getValue(), Smile.HR.getValue(), projectName, projectUrl,
"{4}" +
"{5}: {6}\n\n",
Smile.FUN, Smile.HR, projectName, projectUrl,
(projectDescription != null && !"".equals(projectDescription)) ? escapeMarkdown(projectDescription) + Smile.HR : "", (projectDescription != null && !"".equals(projectDescription)) ? escapeMarkdown(projectDescription) + Smile.HR : "",
Smile.AUTHOR, authorName Smile.AUTHOR.getValue(), authorName
); );
} }

View File

@ -3,6 +3,7 @@ package org.sadtech.bot.gitlab.context.domain.notify;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import lombok.Setter; import lombok.Setter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -12,11 +13,11 @@ import java.util.stream.Stream;
@Setter @Setter
public abstract class Notify { public abstract class Notify {
public static final Set<Character> FORBIDDEN_SYMBOLS = Stream.of( protected static final Set<Character> FORBIDDEN_SYMBOLS = Stream.of(
'\\', '+', '`', '[', ']', '\"', '~', '*', '#', '=', '_', '>', '<' '\\', '+', '`', '[', ']', '\"', '~', '*', '#', '=', '_', '>', '<'
).collect(Collectors.toSet()); ).collect(Collectors.toSet());
public abstract String generateMessage(); public abstract String generateMessage(AppSettingService appSettingService);
public static String escapeMarkdown(@NonNull String s) { public static String escapeMarkdown(@NonNull String s) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

View File

@ -2,6 +2,7 @@ package org.sadtech.bot.gitlab.context.domain.notify;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
/** /**
* // TODO: 20.09.2020 Добавить описание. * // TODO: 20.09.2020 Добавить описание.
@ -19,7 +20,7 @@ public class SimpleTextNotify extends Notify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService appSettingService) {
return message; return message;
} }

View File

@ -4,6 +4,7 @@ import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.Answer; import org.sadtech.bot.gitlab.context.domain.Answer;
import org.sadtech.bot.gitlab.context.domain.notify.Notify; import org.sadtech.bot.gitlab.context.domain.notify.Notify;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat; import java.text.MessageFormat;
@ -29,7 +30,7 @@ public class AnswerCommentNotify extends Notify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
final String answerText = answers.stream() final String answerText = answers.stream()
.map(answer -> answer.getAuthorName() + ": " + answer.getMessage().substring(0, Math.min(answer.getMessage().length(), 500))) .map(answer -> answer.getAuthorName() + ": " + answer.getMessage().substring(0, Math.min(answer.getMessage().length(), 500)))
.collect(Collectors.joining("\n\n")); .collect(Collectors.joining("\n\n"));

View File

@ -3,10 +3,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.comment;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.notify.Notify; import org.sadtech.bot.gitlab.context.domain.notify.Notify;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
@Getter @Getter
public class CommentNotify extends Notify { public class CommentNotify extends Notify {
@ -26,11 +25,10 @@ public class CommentNotify extends Notify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
return MessageFormat.format( return settingService.getMessage(
"{0} *Новое упоминание* | [ПР]({1}){2}" + "notify.comment.bell",
"*{3}*: {4}", Smile.COMMENT.getValue(), url, Smile.HR.getValue(), authorName, escapeMarkdown(message)
Smile.COMMENT, url, Smile.HR, authorName, escapeMarkdown(message)
); );
} }

View File

@ -2,10 +2,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
@Getter @Getter
public class ConflictPrNotify extends PrNotify { public class ConflictPrNotify extends PrNotify {
@ -19,12 +18,10 @@ public class ConflictPrNotify extends PrNotify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
return MessageFormat.format( return settingService.getMessage(
"{0} *Внимание конфликт в ПР | {4}*" + "notify.pr.conflict",
"{1}" + Smile.DANGEROUS.getValue(), Smile.HR.getValue(), title, url, projectName
"[{2}]({3})\n\n",
Smile.DANGEROUS, Smile.HR, title, url, projectName
); );
} }

View File

@ -2,10 +2,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
/** /**
* // TODO: 11.10.2020 Добавить описание. * // TODO: 11.10.2020 Добавить описание.
* *
@ -25,11 +24,10 @@ public class ForgottenSmartPrNotify extends PrNotify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService appSettingService) {
return MessageFormat.format( return appSettingService.getMessage(
"{0} *Напоминание о просмотре PullRequest | {4}*" + "notify.pr.forgotten",
"{3}[{1}]({2})", Smile.SMART.getValue(), title, url, Smile.HR.getValue(), projectName
Smile.SMART, title, url, Smile.HR, projectName
); );
} }

View File

@ -2,9 +2,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -37,21 +37,28 @@ public class NewPrNotify extends PrNotify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
String labelText = labels.stream() String labelText = labels.stream()
.map(label -> "#" + label) .map(label -> "#" + label)
.collect(Collectors.joining(" ")); .collect(Collectors.joining(" "));
if (!labelText.isEmpty()) { if (!labelText.isEmpty()) {
labelText = "\n\n" + labelText; labelText = "\n\n" + labelText;
} }
return MessageFormat.format( return settingService.getMessage(
"{0} *Новый PullRequest | {1}*{2}" + "notify.pr.new",
"[{3}]({4})" + Smile.FUN.getValue(),
"{5}" + projectName,
"{2}{9}: {10} {12} {11}\n{7}: {8}", Smile.HR.getValue(),
Smile.FUN, projectName, Smile.HR, title, url, labelText, title,
url,
labelText,
(description != null && !"".equals(description)) ? escapeMarkdown(description) + Smile.HR : "", (description != null && !"".equals(description)) ? escapeMarkdown(description) + Smile.HR : "",
Smile.AUTHOR, author, Smile.TREE, sourceBranch, targetBranch, Smile.ARROW Smile.AUTHOR.getValue(),
author,
Smile.TREE.getValue(),
sourceBranch,
targetBranch,
Smile.ARROW.getValue()
); );
} }

View File

@ -3,10 +3,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.entity.Reviewer; import org.sadtech.bot.gitlab.context.domain.entity.Reviewer;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
/** /**
* // TODO: 11.10.2020 Добавить описание. * // TODO: 11.10.2020 Добавить описание.
* *
@ -30,13 +29,10 @@ public class SmartPrNotify extends PrNotify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
return MessageFormat.format( return settingService.getMessage(
"{0} *Напоминание о PullRequest | {6}*" + "notify.pr.smart",
"{3}[{1}]({2})" + Smile.SMART.getValue(), title, url, Smile.HR.getValue(), reviewerTriggered.getPersonLogin(),
"{3}" +
"{4} изменил свое решение на {5}\n\n",
Smile.SMART, title, url, Smile.HR, reviewerTriggered.getPersonLogin(),
projectName projectName
); );
} }

View File

@ -3,10 +3,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.MergeRequestState; import org.sadtech.bot.gitlab.context.domain.MergeRequestState;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
@Getter @Getter
public class StatusPrNotify extends PrNotify { public class StatusPrNotify extends PrNotify {
@ -27,12 +26,10 @@ public class StatusPrNotify extends PrNotify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
return MessageFormat.format( return settingService.getMessage(
"{0} *Изменился статус PullRequest | {7}*{1}" + "notify.pr.state",
"[{2}]({3}){1}" + Smile.PEN.getValue(), Smile.HR.getValue(), title, url, oldStatus.name(), Smile.ARROW.getValue(), newStatus.name(), projectName
"{4} {5} {6}\n\n",
Smile.PEN, Smile.HR, title, url, oldStatus.name(), Smile.ARROW, newStatus.name(), projectName
); );
} }

View File

@ -2,10 +2,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
@Getter @Getter
public class UpdatePrNotify extends PrNotify { public class UpdatePrNotify extends PrNotify {
@ -23,13 +22,10 @@ public class UpdatePrNotify extends PrNotify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
return MessageFormat.format( return settingService.getMessage(
"{0} *Обновление PullRequest | {6}*{3}" + "notify.pr.update",
"[{1}]({2})" + Smile.UPDATE.getValue(), title, url, Smile.HR.getValue(), Smile.AUTHOR.getValue(), author, projectName
"{3}" +
"{4}: {5}\n\n",
Smile.UPDATE, title, url, Smile.HR, Smile.AUTHOR, author, projectName
); );
} }

View File

@ -1,10 +1,9 @@
package org.sadtech.bot.gitlab.context.domain.notify.task; package org.sadtech.bot.gitlab.context.domain.notify.task;
import lombok.Builder; import lombok.Builder;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
/** /**
* // TODO: 10.09.2020 Добавить описание. * // TODO: 10.09.2020 Добавить описание.
* *
@ -22,11 +21,10 @@ public class TaskCloseNotify extends TaskNotify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
return MessageFormat.format( return settingService.getMessage(
"{0} *Закрыта* [задача]({1}){2}" + "notify.task.close",
"*{3}*: {4}", Smile.TASK.getValue(), url, Smile.HR.getValue(), authorName, escapeMarkdown(messageTask)
Smile.TASK, url, Smile.HR, authorName, escapeMarkdown(messageTask)
); );
} }

View File

@ -2,10 +2,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.task;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
/** /**
* // TODO: 10.09.2020 Добавить описание. * // TODO: 10.09.2020 Добавить описание.
* *
@ -24,11 +23,10 @@ public class TaskNewNotify extends TaskNotify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService settingService) {
return MessageFormat.format( return settingService.getMessage(
"{0} *Назначена новая* [задача]({1}){2}" + "notify.task.new",
"*{3}*: {4}", Smile.TASK.getValue(), url, Smile.HR.getValue(), authorName, escapeMarkdown(messageTask)
Smile.TASK, url, Smile.HR, authorName, escapeMarkdown(messageTask)
); );
} }

View File

@ -67,9 +67,9 @@ public class MergeRequestsServiceImpl extends AbstractSimpleManagerService<Merge
final MergeRequest newMergeRequest = mergeRequestRepository.save(mergeRequest); final MergeRequest newMergeRequest = mergeRequestRepository.save(mergeRequest);
if (!settingService.isFirstStart()) { // if (!settingService.isFirstStart()) {
notifyNewPr(newMergeRequest); notifyNewPr(newMergeRequest);
} // }
return newMergeRequest; return newMergeRequest;
} }

View File

@ -1,203 +1,176 @@
package org.sadtech.bot.gitlab.core.service.impl; package org.sadtech.bot.gitlab.core.service.impl;
import lombok.NonNull;
import org.sadtech.bot.gitlab.context.domain.TaskStatus;
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.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.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;
import org.sadtech.haiti.core.service.AbstractSimpleManagerService;
import org.sadtech.haiti.core.util.Assert;
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 //@Service
public class TaskServiceImpl extends AbstractSimpleManagerService<Task, Long> implements TaskService { //public class TaskServiceImpl extends AbstractSimpleManagerService<Task, Long> implements TaskService {
//
private static final Pattern PATTERN = Pattern.compile("@[\\w]+"); // private static final Pattern PATTERN = Pattern.compile("@[\\w]+");
//
private final TaskRepository taskRepository; // private final TaskRepository taskRepository;
//
private final MergeRequestsService mergeRequestsService; // private final MergeRequestsService mergeRequestsService;
private final NotifyService notifyService; // private final NotifyService notifyService;
private final NoteService noteService; // private final NoteService noteService;
//
private final ConversionService conversionService; // private final ConversionService conversionService;
//
public TaskServiceImpl( // public TaskServiceImpl(
TaskRepository taskRepository, // TaskRepository taskRepository,
MergeRequestsService mergeRequestsService, // MergeRequestsService mergeRequestsService,
NotifyService notifyService, // NotifyService notifyService,
NoteService noteService, // NoteService noteService,
ConversionService conversionService // ConversionService conversionService
) { // ) {
super(taskRepository); // super(taskRepository);
this.taskRepository = taskRepository; // this.taskRepository = taskRepository;
this.mergeRequestsService = mergeRequestsService; // this.mergeRequestsService = mergeRequestsService;
this.notifyService = notifyService; // this.notifyService = notifyService;
this.noteService = noteService; // this.noteService = noteService;
this.conversionService = conversionService; // this.conversionService = conversionService;
} // }
//
@Override // @Override
public Task create(@NonNull Task task) { // public Task create(@NonNull Task task) {
Assert.isNotNull(task.getId(), "При создании объекта должен быть установлен идентификатор"); // Assert.isNotNull(task.getId(), "При создании объекта должен быть установлен идентификатор");
task.getAnswers().clear(); // task.getAnswers().clear();
final Task newTask = taskRepository.save(task); // final Task newTask = taskRepository.save(task);
notifyNewTask(task); // notifyNewTask(task);
notificationPersonal(task); // notificationPersonal(task);
return newTask; // return newTask;
} // }
//
@Override // @Override
public Task update(@NonNull Task task) { // public Task update(@NonNull Task task) {
final Task oldTask = taskRepository.findById(task.getId()) // final Task oldTask = taskRepository.findById(task.getId())
.orElseThrow(() -> new NotFoundException("Задача не найдена")); // .orElseThrow(() -> new NotFoundException("Задача не найдена"));
//
if (!task.getBitbucketVersion().equals(oldTask.getBitbucketVersion())) { // if (!task.getBitbucketVersion().equals(oldTask.getBitbucketVersion())) {
oldTask.setDescription(task.getDescription()); // oldTask.setDescription(task.getDescription());
oldTask.setBitbucketVersion(task.getBitbucketVersion()); // oldTask.setBitbucketVersion(task.getBitbucketVersion());
} // }
updateAnswer(oldTask, task); // updateAnswer(oldTask, task);
updateStatus(oldTask, task); // updateStatus(oldTask, task);
oldTask.setStatus(task.getStatus()); // oldTask.setStatus(task.getStatus());
return taskRepository.save(oldTask); // return taskRepository.save(oldTask);
} // }
//
private void updateStatus(Task oldTask, Task task) { // private void updateStatus(Task oldTask, Task task) {
final TaskStatus oldStatus = oldTask.getStatus(); // final TaskStatus oldStatus = oldTask.getStatus();
final TaskStatus newStatus = task.getStatus(); // final TaskStatus newStatus = task.getStatus();
if (!oldStatus.equals(newStatus)) { // if (!oldStatus.equals(newStatus)) {
switch (newStatus) { // switch (newStatus) {
case OPEN: // case OPEN:
notifyService.send(
TaskNewNotify.builder()
.messageTask(task.getDescription())
.authorName(oldTask.getAuthor())
.url(oldTask.getUrl())
.build()
);
break;
case RESOLVED:
notifyService.send(
TaskCloseNotify.builder()
.messageTask(oldTask.getDescription())
.authorName(oldTask.getAuthor())
.url(oldTask.getUrl())
.build()
);
break;
default:
throw new NotFoundException("Обработчика типа не существует");
}
oldTask.setStatus(newStatus);
}
}
private void updateAnswer(Task oldTask, Task task) {
// final Set<Long> oldAnswerIds = oldTask.getAnswers();
// final Set<Long> newAnswerIds = task.getAnswers();
// if (!oldAnswerIds.equals(newAnswerIds)) {
// final Set<Long> existsNewAnswersIds = noteService.existsById(newAnswerIds);
// final List<Note> 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( // notifyService.send(
// AnswerCommentNotify.builder() // TaskNewNotify.builder()
// .messageTask(task.getDescription())
// .authorName(oldTask.getAuthor())
// .url(oldTask.getUrl()) // .url(oldTask.getUrl())
// .youMessage(oldTask.getDescription()) // .build()
// .answers( // );
// newAnswers.stream() // break;
// .map(answerComment -> Answer.of(answerComment.getAuthor(), answerComment.getMessage())) // case RESOLVED:
// .collect(Collectors.toList()) // notifyService.send(
// ) // TaskCloseNotify.builder()
// .messageTask(oldTask.getDescription())
// .authorName(oldTask.getAuthor())
// .url(oldTask.getUrl())
// .build()
// );
// break;
// default:
// throw new NotFoundException("Обработчика типа не существует");
// }
// oldTask.setStatus(newStatus);
// }
// }
//
// private void updateAnswer(Task oldTask, Task task) {
//// final Set<Long> oldAnswerIds = oldTask.getAnswers();
//// final Set<Long> newAnswerIds = task.getAnswers();
//// if (!oldAnswerIds.equals(newAnswerIds)) {
//// final Set<Long> existsNewAnswersIds = noteService.existsById(newAnswerIds);
//// final List<Note> 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
// public Long getLastTaskId() {
// return taskRepository.findFirstByOrderByIdDesc().map(Task::getId).orElse(0L);
// }
//
// @Override
// 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;
// }
//
// @Override
// public List<Task> getAllBetweenDate(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo) {
// return taskRepository.findByCreateDateBetween(dateFrom, dateTo);
// }
//
// @Override
// public List<Task> getAllByResponsibleAndStatus(@NonNull String login, @NonNull TaskStatus status) {
// return taskRepository.findAllByResponsibleAndStatus(login, status);
// }
//
// private void notifyNewTask(Task task) {
// final MergeRequest mergeRequest = mergeRequestsService.getById(task.getPullRequestId())
// .orElseThrow(() -> new NotFoundException("ПР не найден"));
//
// notifyService.send(
// TaskNewNotify.builder()
// .authorName(task.getAuthor())
// .messageTask(task.getDescription())
// .url(task.getUrl())
//// .recipients(Collections.singleton(mergeRequest.getAuthor().getId()))
// .build() // .build()
// ); // );
// } // }
//
// private void notificationPersonal(@NonNull Task task) {
// Matcher matcher = PATTERN.matcher(task.getDescription());
// Set<String> recipientsLogins = new HashSet<>();
// while (matcher.find()) {
// final String login = matcher.group(0).replace("@", "");
// recipientsLogins.add(login);
// } // }
} // notifyService.send(
// CommentNotify.builder()
@Override // .authorName(task.getAuthor())
public Long getLastTaskId() { // .url(task.getUrl())
return taskRepository.findFirstByOrderByIdDesc().map(Task::getId).orElse(0L); // .message(task.getDescription())
} // .build()
// );
@Override // }
public Task convert(@NonNull Note note) { //
noteService.deleteById(note.getId()); // @Override
final Task task = conversionService.convert(note, Task.class); // public void deleteById(@NonNull Long id) {
final Task newTask = taskRepository.save(task); // super.deleteById(id);
notifyNewTask(newTask); // }
return newTask; //
} // @Override
// public ExistsContainer<Task, Long> existsById(@NonNull Collection<Long> collection) {
@Override // return null;
public List<Task> getAllBetweenDate(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo) { // }
return taskRepository.findByCreateDateBetween(dateFrom, dateTo); //
} //}
@Override
public List<Task> getAllByResponsibleAndStatus(@NonNull String login, @NonNull TaskStatus status) {
return taskRepository.findAllByResponsibleAndStatus(login, status);
}
private void notifyNewTask(Task task) {
final MergeRequest mergeRequest = mergeRequestsService.getById(task.getPullRequestId())
.orElseThrow(() -> new NotFoundException("ПР не найден"));
notifyService.send(
TaskNewNotify.builder()
.authorName(task.getAuthor())
.messageTask(task.getDescription())
.url(task.getUrl())
// .recipients(Collections.singleton(mergeRequest.getAuthor().getId()))
.build()
);
}
private void notificationPersonal(@NonNull Task task) {
Matcher matcher = PATTERN.matcher(task.getDescription());
Set<String> recipientsLogins = new HashSet<>();
while (matcher.find()) {
final String login = matcher.group(0).replace("@", "");
recipientsLogins.add(login);
}
notifyService.send(
CommentNotify.builder()
.authorName(task.getAuthor())
.url(task.getUrl())
.message(task.getDescription())
.build()
);
}
@Override
public void deleteById(@NonNull Long id) {
super.deleteById(id);
}
@Override
public ExistsContainer<Task, Long> existsById(@NonNull Collection<Long> collection) {
return null;
}
}

View File

@ -65,20 +65,25 @@ public class MergeRequestParser {
public void parsingNewMergeRequest() { public void parsingNewMergeRequest() {
int page = 0; int page = 0;
Sheet<Project> projectSheet = projectService.getAll(PaginationImpl.of(page, COUNT)); Sheet<Project> projectSheet = projectService.getAll(PaginationImpl.of(page, COUNT));
while (projectSheet.hasContent()) { while (projectSheet.hasContent()) {
final List<Project> projects = projectSheet.getContent(); final List<Project> projects = projectSheet.getContent();
for (Project project : projects) { for (Project project : projects) {
final List<MergeRequestJson> mergeRequestJsons = HttpParse.request( projectProcessing(project);
MessageFormat.format(gitlabProperty.getUrlPullRequestOpen(), project.getId()) }
)
.header(HttpHeader.of(AUTHORIZATION, BEARER + personProperty.getToken()))
.header(ACCEPT)
.executeList(MergeRequestJson.class);
if (!mergeRequestJsons.isEmpty()) { projectSheet = projectService.getAll(PaginationImpl.of(++page, COUNT));
}
}
private void projectProcessing(Project project) {
int page = 1;
List<MergeRequestJson> mergeRequestJsons = getMergeRequestJsons(project, page);
while (!mergeRequestJsons.isEmpty()) {
final Set<Long> jsonIds = mergeRequestJsons.stream() final Set<Long> jsonIds = mergeRequestJsons.stream()
.map(MergeRequestJson::getId) .map(MergeRequestJson::getId)
@ -92,13 +97,16 @@ public class MergeRequestParser {
.collect(Collectors.toList()); .collect(Collectors.toList());
mergeRequestsService.createAll(newMergeRequests); mergeRequestsService.createAll(newMergeRequests);
} }
mergeRequestJsons = getMergeRequestJsons(project, page++);
} }
} }
projectSheet = projectService.getAll(PaginationImpl.of(++page, COUNT)); private List<MergeRequestJson> getMergeRequestJsons(Project project, int page) {
} return HttpParse.request(MessageFormat.format(gitlabProperty.getUrlPullRequestOpen(), project.getId(), page))
.header(HttpHeader.of(AUTHORIZATION, BEARER + personProperty.getToken()))
.header(ACCEPT)
.executeList(MergeRequestJson.class);
} }
} }

View File

@ -15,6 +15,7 @@ import org.springframework.core.convert.ConversionService;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import static org.sadtech.haiti.utils.network.HttpParse.ACCEPT; 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.AUTHORIZATION;
@ -62,7 +63,10 @@ public class NoteParser {
final List<NoteJson> noteJsons = HttpParse.request(MessageFormat.format(gitlabProperty.getUrlPullRequestComment(), mergeRequest.getProjectId(), mergeRequest.getTwoId())) final List<NoteJson> noteJsons = HttpParse.request(MessageFormat.format(gitlabProperty.getUrlPullRequestComment(), mergeRequest.getProjectId(), mergeRequest.getTwoId()))
.header(ACCEPT) .header(ACCEPT)
.header(AUTHORIZATION, BEARER + personProperty.getToken()) .header(AUTHORIZATION, BEARER + personProperty.getToken())
.executeList(NoteJson.class); .executeList(NoteJson.class)
.stream()
.filter(noteJson -> !noteJson.isSystem())
.collect(Collectors.toList());
} }

View File

@ -57,7 +57,7 @@ public class ProjectParser {
} }
private void parseProjects(String param) { private void parseProjects(String param) {
int page = 0; int page = 1;
List<ProjectJson> projectJsons = getProjectJsons(page, param); List<ProjectJson> projectJsons = getProjectJsons(page, param);
while (!projectJsons.isEmpty()) { while (!projectJsons.isEmpty()) {

View File

@ -3,6 +3,7 @@ package org.sadtech.bot.gitlab.teamcity.core.domain;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.notify.Notify; import org.sadtech.bot.gitlab.context.domain.notify.Notify;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile; import org.sadtech.bot.gitlab.context.utils.Smile;
import org.sadtech.bot.gitlab.teamcity.core.domain.entity.BuildShort; import org.sadtech.bot.gitlab.teamcity.core.domain.entity.BuildShort;
import org.sadtech.bot.gitlab.teamcity.sdk.BuildStatus; import org.sadtech.bot.gitlab.teamcity.sdk.BuildStatus;
@ -25,7 +26,7 @@ public class TeamcityBuildNotify extends Notify {
} }
@Override @Override
public String generateMessage() { public String generateMessage(AppSettingService appSettingService) {
return MessageFormat.format( return MessageFormat.format(
"{0} *Сборка* | {1,number,#}:{2,number,#} | {3}" + "{0} *Сборка* | {1,number,#}:{2,number,#} | {3}" +
"{4} [{5}]({6}) {4}" + "{4} [{5}]({6}) {4}" +

View File

@ -4,6 +4,7 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.sadtech.bot.gitlab.context.domain.PersonInformation; import org.sadtech.bot.gitlab.context.domain.PersonInformation;
import org.sadtech.bot.gitlab.context.domain.notify.Notify; import org.sadtech.bot.gitlab.context.domain.notify.Notify;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.service.MessageSendService; import org.sadtech.bot.gitlab.context.service.MessageSendService;
import org.sadtech.social.core.domain.BoxAnswer; import org.sadtech.social.core.domain.BoxAnswer;
import org.sadtech.social.core.service.sender.Sending; import org.sadtech.social.core.service.sender.Sending;
@ -21,10 +22,11 @@ public class MessageSendTelegramService implements MessageSendService {
private final Sending sending; private final Sending sending;
private final PersonInformation personInformation; private final PersonInformation personInformation;
private final AppSettingService settingService;
@Override @Override
public void send(@NonNull Notify notify) { public void send(@NonNull Notify notify) {
sending.send(personInformation.getTelegramId(), BoxAnswer.of(notify.generateMessage())); sending.send(personInformation.getTelegramId(), BoxAnswer.of(notify.generateMessage(settingService)));
} }
} }

View File

@ -7,8 +7,6 @@ import org.sadtech.social.core.domain.BoxAnswer;
import org.sadtech.social.core.domain.ProcessingData; import org.sadtech.social.core.domain.ProcessingData;
import org.sadtech.social.core.domain.content.Message; import org.sadtech.social.core.domain.content.Message;
import java.text.MessageFormat;
/** /**
* // TODO: 17.09.2020 Добавить описание. * // TODO: 17.09.2020 Добавить описание.
* *
@ -42,10 +40,11 @@ public class TaskProcessing implements ProcessingData<Message> {
} }
private String createTaskString(Task task) { private String createTaskString(Task task) {
return MessageFormat.format( // return MessageFormat.format(
"- [{0}]({1})", // "- [{0}]({1})",
task.getDescription(), task.getUrl() // task.getDescription(), task.getUrl()
); // );
return null;
} }
} }

View File

@ -0,0 +1,114 @@
package org.sadtech.bot.gitlab.telegram.unit;
import org.sadtech.bot.gitlab.context.domain.AppLocale;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.social.bot.domain.unit.AnswerText;
import org.sadtech.social.core.domain.BoxAnswer;
import org.sadtech.social.core.domain.keyboard.KeyBoard;
import org.sadtech.social.core.domain.keyboard.KeyBoardLine;
import org.sadtech.social.core.domain.keyboard.button.KeyBoardButtonText;
import org.sadtech.social.core.utils.KeyBoards;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* // TODO: 16.01.2021 Добавить описание.
*
* @author upagge 16.01.2021
*/
@Configuration
public class MenuConfig {
@Bean
public AnswerText menu(
AppSettingService settingService,
AnswerText settings
) {
return AnswerText.builder()
.boxAnswer(message ->
{
final KeyBoardButtonText newMr = KeyBoardButtonText.builder().label(settingService.getMessage("ui.menu.add_mr")).build();
final KeyBoardButtonText tasks = KeyBoardButtonText.builder().label(settingService.getMessage("ui.menu.task")).build();
final KeyBoardButtonText pr = KeyBoardButtonText.builder().label(settingService.getMessage("ui.menu.mr")).build();
final KeyBoardButtonText settingsKeyBoard = KeyBoardButtonText.builder().label(settingService.getMessage("ui.menu.setting")).build();
final KeyBoardLine oneLine = KeyBoardLine.builder()
.buttonKeyBoard(newMr)
.build();
final KeyBoardLine twoLine = KeyBoardLine.builder()
.buttonKeyBoard(tasks)
.buttonKeyBoard(pr)
.build();
final KeyBoardLine threeLine = KeyBoardLine.builder()
.buttonKeyBoard(settingsKeyBoard)
.build();
final KeyBoard keyBoard = KeyBoard.builder()
.lineKeyBoard(oneLine)
.lineKeyBoard(twoLine)
.lineKeyBoard(threeLine)
.build();
return BoxAnswer.builder()
.message(settingService.getMessage("ui.menu.header"))
.keyBoard(keyBoard)
.build();
}
)
.nextUnit(settings)
.build();
}
@Bean
public AnswerText settings(
AppSettingService settingService,
AnswerText settingsLanguage
) {
return AnswerText.builder()
.boxAnswer(message ->
BoxAnswer.builder()
.message(settingService.getMessage("ui.menu.setting.text"))
.keyBoard(KeyBoards.verticalMenuString(settingService.getMessage("ui.menu.setting.language")))
.build())
.phrase(settingService.getMessage("ui.menu.setting"))
.nextUnit(settingsLanguage)
.build();
}
@Bean
public AnswerText settingsLanguage(
AppSettingService settingService,
AnswerText setLanguage
) {
return AnswerText.builder()
.boxAnswer(message ->
BoxAnswer.builder()
.message(settingService.getMessage("ui.menu.setting.language.text"))
.keyBoard(KeyBoards.verticalDuoMenuString("Русский", "English"))
.build())
.nextUnit(setLanguage)
.phrase(settingService.getMessage("ui.menu.setting.language"))
.build();
}
@Bean
public AnswerText setLanguage(
AppSettingService settingService
) {
return AnswerText.builder()
.boxAnswer(
message -> {
final AppLocale appLocale = AppLocale.of(message.getText());
settingService.setLocale(appLocale);
return BoxAnswer.of(
settingService.getMessage("ui.lang_changed")
);
}
)
.build();
}
}

View File

@ -1,85 +0,0 @@
package org.sadtech.bot.gitlab.telegram.unit;
import lombok.RequiredArgsConstructor;
import org.sadtech.bot.gitlab.context.service.NotifyService;
import org.springframework.context.annotation.Configuration;
/**
* // TODO: 20.09.2020 Добавить описание.
*
* @author upagge 20.09.2020
*/
@Configuration
@RequiredArgsConstructor
public class NotifySettingUnit {
private final NotifyService notifyService;
// @Bean
// public AnswerText notifySetting(
// AnswerProcessing<Message> 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<Message> disableNotifications() {
// return AnswerProcessing.builder()
// .processingData(
// message -> {
// final Person person = personService.getByTelegramId(message.getPersonId())
// .orElseThrow(() -> new NotFoundException("Не найдено"));
// final NotifySetting notifySetting = notifyService.getSetting(person.getLogin())
// .orElseThrow(() -> new NotFoundException("Не найдено"));
// notifySetting.setStartReceiving(
// LocalDateTime.now().plusMinutes(DisableMenu.from(message.getText()).getMinutes())
// );
// notifyService.saveSettings(notifySetting);
// return BoxAnswer.of("Настройки сохранены");
// 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("Не найдено"));
// }
//
// }
}

View File

@ -25,12 +25,14 @@ public class UnitConfig {
@Bean @Bean
public AnswerCheck checkFirstStart( public AnswerCheck checkFirstStart(
AppSettingService settingService, AppSettingService settingService,
AnswerText textCheckLanguage AnswerText textCheckLanguage,
AnswerText menu
) { ) {
return AnswerCheck.builder() return AnswerCheck.builder()
.check( .check(
message -> settingService.isFirstStart() message -> settingService.isFirstStart()
) )
.unitFalse(menu)
.unitTrue(textCheckLanguage) .unitTrue(textCheckLanguage)
.build(); .build();
} }

View File

@ -1,43 +1,14 @@
package org.sadtech.bot.gitlab.telegram.utils; package org.sadtech.bot.gitlab.telegram.utils;
import lombok.AccessLevel; import org.springframework.context.annotation.Configuration;
import lombok.NoArgsConstructor;
import org.sadtech.social.core.domain.keyboard.KeyBoard;
import org.sadtech.social.core.domain.keyboard.KeyBoardLine;
import org.sadtech.social.core.domain.keyboard.button.KeyBoardButtonText;
/** /**
* // TODO: 20.09.2020 Добавить описание. * // TODO: 20.09.2020 Добавить описание.
* *
* @author upagge 20.09.2020 * @author upagge 20.09.2020
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE) @Configuration
public class GeneratorKeyBoards { public class GeneratorKeyBoards {
public static KeyBoard menu() {
final KeyBoardButtonText tasks = KeyBoardButtonText.builder().label("Мои задачи").build();
final KeyBoardButtonText pr = KeyBoardButtonText.builder().label("Pull Requests").build();
final KeyBoardButtonText top = KeyBoardButtonText.builder().label("\uD83C\uDF1F Таблица рейтинга \uD83C\uDF1F").build();
final KeyBoardButtonText settings = KeyBoardButtonText.builder().label("Настройки").build();
final KeyBoardLine oneLine = KeyBoardLine.builder()
.buttonKeyBoard(tasks)
.buttonKeyBoard(pr)
.build();
final KeyBoardLine twoLine = KeyBoardLine.builder()
.buttonKeyBoard(top)
.build();
final KeyBoardLine threeLine = KeyBoardLine.builder()
.buttonKeyBoard(settings)
.build();
return KeyBoard.builder()
.lineKeyBoard(oneLine)
.lineKeyBoard(twoLine)
.lineKeyBoard(threeLine)
.build();
}
} }