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

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}
gitlab:
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-comment: ${GITLAB_URL}/api/v4/projects/19/merge_requests/8/notes
url-pull-request: ${GITLAB_URL}/api/v4/projects/{0}/merge_requests/{1}
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}?page={2}&per_page=100
user-url: ${GITLAB_URL}/api/v4/user
users-url: ${GITLAB_URL}/api/v4/users
teamcity:

View File

@ -4,4 +4,22 @@ 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
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

@ -4,4 +4,22 @@ ui.lang_changed=Язык успешно изменен
ui.monitor_private_projects=Начать отслеживать приватные проекты?
ui.monitor_project_private_success=Проекты успешно добавлены в отслеживание
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 javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@ -18,6 +22,9 @@ import java.time.LocalDateTime;
@Entity
@Table(name = "note")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("null")
public class Note implements BasicEntity<Long> {
@Id

View File

@ -1,72 +1,12 @@
package org.sadtech.bot.gitlab.context.domain.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
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
@Getter
@Setter
//@Table(name = "task")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
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<>();
public class Task extends Note {
}

View File

@ -3,6 +3,7 @@ package org.sadtech.bot.gitlab.context.domain.notify;
import lombok.Builder;
import lombok.Getter;
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.Smile;
import org.sadtech.bot.gitlab.context.utils.UpdateDataComparator;
@ -38,7 +39,7 @@ public class GoodMorningNotify extends Notify {
}
@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);
if (!mergeRequestsReviews.isEmpty()) {
message.append("Необходимо проверить ").append(mergeRequestsReviews.size()).append(" ПР:").append(Smile.BR);

View File

@ -1,10 +1,9 @@
package org.sadtech.bot.gitlab.context.domain.notify;
import lombok.Builder;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
/**
* // TODO: 15.01.2021 Добавить описание.
*
@ -26,15 +25,12 @@ public class NewProjectNotify extends Notify {
}
@Override
public String generateMessage() {
return MessageFormat.format(
"{0} *Новый Проект*{1}" +
"[{2}]({3}){1}" +
"{4}" +
"{5}: {6}\n\n",
Smile.FUN, Smile.HR, projectName, projectUrl,
public String generateMessage(AppSettingService settingService) {
return settingService.getMessage(
"notify.project.new",
Smile.FUN.getValue(), Smile.HR.getValue(), projectName, projectUrl,
(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.NonNull;
import lombok.Setter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import java.util.Set;
import java.util.stream.Collectors;
@ -12,11 +13,11 @@ import java.util.stream.Stream;
@Setter
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());
public abstract String generateMessage();
public abstract String generateMessage(AppSettingService appSettingService);
public static String escapeMarkdown(@NonNull String s) {
StringBuilder sb = new StringBuilder();

View File

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

View File

@ -4,6 +4,7 @@ import lombok.Builder;
import lombok.Getter;
import org.sadtech.bot.gitlab.context.domain.Answer;
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 java.text.MessageFormat;
@ -29,7 +30,7 @@ public class AnswerCommentNotify extends Notify {
}
@Override
public String generateMessage() {
public String generateMessage(AppSettingService settingService) {
final String answerText = answers.stream()
.map(answer -> answer.getAuthorName() + ": " + answer.getMessage().substring(0, Math.min(answer.getMessage().length(), 500)))
.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.Getter;
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 java.text.MessageFormat;
@Getter
public class CommentNotify extends Notify {
@ -26,11 +25,10 @@ public class CommentNotify extends Notify {
}
@Override
public String generateMessage() {
return MessageFormat.format(
"{0} *Новое упоминание* | [ПР]({1}){2}" +
"*{3}*: {4}",
Smile.COMMENT, url, Smile.HR, authorName, escapeMarkdown(message)
public String generateMessage(AppSettingService settingService) {
return settingService.getMessage(
"notify.comment.bell",
Smile.COMMENT.getValue(), url, Smile.HR.getValue(), authorName, escapeMarkdown(message)
);
}

View File

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

View File

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

View File

@ -2,9 +2,9 @@ package org.sadtech.bot.gitlab.context.domain.notify.pullrequest;
import lombok.Builder;
import lombok.Getter;
import org.sadtech.bot.gitlab.context.service.AppSettingService;
import org.sadtech.bot.gitlab.context.utils.Smile;
import java.text.MessageFormat;
import java.util.Set;
import java.util.stream.Collectors;
@ -37,21 +37,28 @@ public class NewPrNotify extends PrNotify {
}
@Override
public String generateMessage() {
public String generateMessage(AppSettingService settingService) {
String labelText = labels.stream()
.map(label -> "#" + label)
.collect(Collectors.joining(" "));
if (!labelText.isEmpty()) {
labelText = "\n\n" + labelText;
}
return MessageFormat.format(
"{0} *Новый PullRequest | {1}*{2}" +
"[{3}]({4})" +
"{5}" +
"{2}{9}: {10} {12} {11}\n{7}: {8}",
Smile.FUN, projectName, Smile.HR, title, url, labelText,
return settingService.getMessage(
"notify.pr.new",
Smile.FUN.getValue(),
projectName,
Smile.HR.getValue(),
title,
url,
labelText,
(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.Getter;
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 java.text.MessageFormat;
/**
* // TODO: 11.10.2020 Добавить описание.
*
@ -30,13 +29,10 @@ public class SmartPrNotify extends PrNotify {
}
@Override
public String generateMessage() {
return MessageFormat.format(
"{0} *Напоминание о PullRequest | {6}*" +
"{3}[{1}]({2})" +
"{3}" +
"{4} изменил свое решение на {5}\n\n",
Smile.SMART, title, url, Smile.HR, reviewerTriggered.getPersonLogin(),
public String generateMessage(AppSettingService settingService) {
return settingService.getMessage(
"notify.pr.smart",
Smile.SMART.getValue(), title, url, Smile.HR.getValue(), reviewerTriggered.getPersonLogin(),
projectName
);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,203 +1,176 @@
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
public class TaskServiceImpl extends AbstractSimpleManagerService<Task, Long> implements TaskService {
private static final Pattern PATTERN = Pattern.compile("@[\\w]+");
private final TaskRepository taskRepository;
private final MergeRequestsService mergeRequestsService;
private final NotifyService notifyService;
private final NoteService noteService;
private final ConversionService conversionService;
public TaskServiceImpl(
TaskRepository taskRepository,
MergeRequestsService mergeRequestsService,
NotifyService notifyService,
NoteService noteService,
ConversionService conversionService
) {
super(taskRepository);
this.taskRepository = taskRepository;
this.mergeRequestsService = mergeRequestsService;
this.notifyService = notifyService;
this.noteService = noteService;
this.conversionService = conversionService;
}
@Override
public Task create(@NonNull Task task) {
Assert.isNotNull(task.getId(), "При создании объекта должен быть установлен идентификатор");
task.getAnswers().clear();
final Task newTask = taskRepository.save(task);
notifyNewTask(task);
notificationPersonal(task);
return newTask;
}
@Override
public Task update(@NonNull Task task) {
final Task oldTask = taskRepository.findById(task.getId())
.orElseThrow(() -> new NotFoundException("Задача не найдена"));
if (!task.getBitbucketVersion().equals(oldTask.getBitbucketVersion())) {
oldTask.setDescription(task.getDescription());
oldTask.setBitbucketVersion(task.getBitbucketVersion());
}
updateAnswer(oldTask, task);
updateStatus(oldTask, task);
oldTask.setStatus(task.getStatus());
return taskRepository.save(oldTask);
}
private void updateStatus(Task oldTask, Task task) {
final TaskStatus oldStatus = oldTask.getStatus();
final TaskStatus newStatus = task.getStatus();
if (!oldStatus.equals(newStatus)) {
switch (newStatus) {
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(
// AnswerCommentNotify.builder()
// .url(oldTask.getUrl())
// .youMessage(oldTask.getDescription())
// .answers(
// newAnswers.stream()
// .map(answerComment -> Answer.of(answerComment.getAuthor(), answerComment.getMessage()))
// .collect(Collectors.toList())
// )
// .build()
// );
// }
//public class TaskServiceImpl extends AbstractSimpleManagerService<Task, Long> implements TaskService {
//
// private static final Pattern PATTERN = Pattern.compile("@[\\w]+");
//
// private final TaskRepository taskRepository;
//
// private final MergeRequestsService mergeRequestsService;
// private final NotifyService notifyService;
// private final NoteService noteService;
//
// private final ConversionService conversionService;
//
// public TaskServiceImpl(
// TaskRepository taskRepository,
// MergeRequestsService mergeRequestsService,
// NotifyService notifyService,
// NoteService noteService,
// ConversionService conversionService
// ) {
// super(taskRepository);
// this.taskRepository = taskRepository;
// this.mergeRequestsService = mergeRequestsService;
// this.notifyService = notifyService;
// this.noteService = noteService;
// this.conversionService = conversionService;
// }
//
// @Override
// public Task create(@NonNull Task task) {
// Assert.isNotNull(task.getId(), "При создании объекта должен быть установлен идентификатор");
// task.getAnswers().clear();
// final Task newTask = taskRepository.save(task);
// notifyNewTask(task);
// notificationPersonal(task);
// return newTask;
// }
//
// @Override
// public Task update(@NonNull Task task) {
// final Task oldTask = taskRepository.findById(task.getId())
// .orElseThrow(() -> new NotFoundException("Задача не найдена"));
//
// if (!task.getBitbucketVersion().equals(oldTask.getBitbucketVersion())) {
// oldTask.setDescription(task.getDescription());
// oldTask.setBitbucketVersion(task.getBitbucketVersion());
// }
}
@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()
);
}
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;
}
}
// updateAnswer(oldTask, task);
// updateStatus(oldTask, task);
// oldTask.setStatus(task.getStatus());
// return taskRepository.save(oldTask);
// }
//
// private void updateStatus(Task oldTask, Task task) {
// final TaskStatus oldStatus = oldTask.getStatus();
// final TaskStatus newStatus = task.getStatus();
// if (!oldStatus.equals(newStatus)) {
// switch (newStatus) {
// 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(
//// 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()
// );
// }
//
// 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,40 +65,48 @@ public class MergeRequestParser {
public void parsingNewMergeRequest() {
int page = 0;
Sheet<Project> projectSheet = projectService.getAll(PaginationImpl.of(page, COUNT));
while (projectSheet.hasContent()) {
final List<Project> projects = projectSheet.getContent();
for (Project project : projects) {
final List<MergeRequestJson> mergeRequestJsons = HttpParse.request(
MessageFormat.format(gitlabProperty.getUrlPullRequestOpen(), project.getId())
)
.header(HttpHeader.of(AUTHORIZATION, BEARER + personProperty.getToken()))
.header(ACCEPT)
.executeList(MergeRequestJson.class);
if (!mergeRequestJsons.isEmpty()) {
final Set<Long> jsonIds = mergeRequestJsons.stream()
.map(MergeRequestJson::getId)
.collect(Collectors.toSet());
final ExistsContainer<MergeRequest, Long> existsContainer = mergeRequestsService.existsById(jsonIds);
if (!existsContainer.isAllFound()) {
final List<MergeRequest> newMergeRequests = mergeRequestJsons.stream()
.filter(json -> existsContainer.getIdNoFound().contains(json.getId()))
.map(json -> conversionService.convert(json, MergeRequest.class))
.collect(Collectors.toList());
mergeRequestsService.createAll(newMergeRequests);
}
}
projectProcessing(project);
}
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()
.map(MergeRequestJson::getId)
.collect(Collectors.toSet());
final ExistsContainer<MergeRequest, Long> existsContainer = mergeRequestsService.existsById(jsonIds);
if (!existsContainer.isAllFound()) {
final List<MergeRequest> newMergeRequests = mergeRequestJsons.stream()
.filter(json -> existsContainer.getIdNoFound().contains(json.getId()))
.map(json -> conversionService.convert(json, MergeRequest.class))
.collect(Collectors.toList());
mergeRequestsService.createAll(newMergeRequests);
}
mergeRequestJsons = getMergeRequestJsons(project, page++);
}
}
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.util.List;
import java.util.stream.Collectors;
import static org.sadtech.haiti.utils.network.HttpParse.ACCEPT;
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()))
.header(ACCEPT)
.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) {
int page = 0;
int page = 1;
List<ProjectJson> projectJsons = getProjectJsons(page, param);
while (!projectJsons.isEmpty()) {

View File

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

View File

@ -4,6 +4,7 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.sadtech.bot.gitlab.context.domain.PersonInformation;
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.social.core.domain.BoxAnswer;
import org.sadtech.social.core.service.sender.Sending;
@ -21,10 +22,11 @@ public class MessageSendTelegramService implements MessageSendService {
private final Sending sending;
private final PersonInformation personInformation;
private final AppSettingService settingService;
@Override
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.content.Message;
import java.text.MessageFormat;
/**
* // TODO: 17.09.2020 Добавить описание.
*
@ -42,10 +40,11 @@ public class TaskProcessing implements ProcessingData<Message> {
}
private String createTaskString(Task task) {
return MessageFormat.format(
"- [{0}]({1})",
task.getDescription(), task.getUrl()
);
// return MessageFormat.format(
// "- [{0}]({1})",
// 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
public AnswerCheck checkFirstStart(
AppSettingService settingService,
AnswerText textCheckLanguage
AnswerText textCheckLanguage,
AnswerText menu
) {
return AnswerCheck.builder()
.check(
message -> settingService.isFirstStart()
)
.unitFalse(menu)
.unitTrue(textCheckLanguage)
.build();
}

View File

@ -1,43 +1,14 @@
package org.sadtech.bot.gitlab.telegram.utils;
import lombok.AccessLevel;
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;
import org.springframework.context.annotation.Configuration;
/**
* // TODO: 20.09.2020 Добавить описание.
*
* @author upagge 20.09.2020
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Configuration
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();
}
}