Добавил новый тип триггера

This commit is contained in:
Struchkov Mark 2022-07-26 09:27:18 +03:00
parent eaeb220515
commit 0bbdcaae07
34 changed files with 651 additions and 907 deletions

View File

@ -6,7 +6,7 @@
<parent>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>godfather-bot</artifactId>
<version>0.0.17</version>
<version>0.0.18</version>
</parent>
<artifactId>bot-context</artifactId>

View File

@ -19,7 +19,7 @@ public class UnitRequest<U extends MainUnit, M extends Message> {
this.message = message;
}
public static <U extends MainUnit, M extends Message> UnitRequest<U, M> of(U mainUnit, M message) {
public static <U extends MainUnit<M>, M extends Message> UnitRequest<U, M> of(U mainUnit, M message) {
return new UnitRequest<>(mainUnit, message);
}

View File

@ -1,5 +1,6 @@
package dev.struchkov.godfather.context.domain.content;
import dev.struchkov.autoresponder.entity.DeliverableText;
import dev.struchkov.godfather.context.domain.BasicEntity;
import javax.persistence.Column;
@ -16,7 +17,7 @@ import java.util.Objects;
* @author upagge [08/07/2019]
*/
@MappedSuperclass
public abstract class Message extends BasicEntity {
public abstract class Message extends BasicEntity implements DeliverableText {
/**
* Тип сообщения.

View File

@ -6,7 +6,6 @@ import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.service.Accessibility;
import dev.struchkov.godfather.context.service.usercode.CheckData;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
@ -22,7 +21,7 @@ import static dev.struchkov.haiti.utils.Inspector.isNotNull;
*
* @author upagge [08/07/2019]
*/
public class AnswerCheck extends MainUnit {
public class AnswerCheck<M extends Message> extends MainUnit<M> {
/**
* Unit для true.
@ -37,15 +36,15 @@ public class AnswerCheck extends MainUnit {
/**
* Условие проверки.
*/
private final CheckData<Message> check;
private final CheckData<M> check;
private AnswerCheck(Builder builder) {
private AnswerCheck(Builder<M> builder) {
super(
builder.name,
builder.keyWords,
builder.phrases,
builder.triggerWords,
builder.triggerPhrases,
builder.triggerCheck,
builder.pattern,
builder.triggerPatterns,
builder.matchThreshold,
builder.priority,
new HashSet<>(),
@ -59,8 +58,8 @@ public class AnswerCheck extends MainUnit {
check = builder.check;
}
public static Builder builder() {
return new Builder();
public static <M extends Message> Builder<M> builder() {
return new Builder<>();
}
public MainUnit getUnitTrue() {
@ -71,117 +70,144 @@ public class AnswerCheck extends MainUnit {
return unitFalse;
}
public CheckData<Message> getCheck() {
public CheckData<M> getCheck() {
return check;
}
public static final class Builder {
public static final class Builder<M extends Message> {
private String name;
private final Set<KeyWord> keyWords = new HashSet<>();
private final Set<String> phrases = new HashSet<>();
private Predicate<String> triggerCheck;
private Pattern pattern;
private Set<KeyWord> triggerWords;
private Set<String> triggerPhrases;
private Predicate<M> triggerCheck;
private Set<Pattern> triggerPatterns;
private Integer matchThreshold;
private Integer priority;
private MainUnit unitTrue;
private MainUnit unitFalse;
private CheckData<Message> check;
private UnitActiveType activeType;
private Accessibility accessibility;
private boolean notSaveHistory;
private MainUnit unitTrue;
private MainUnit unitFalse;
private CheckData<M> check;
private Builder() {
}
public Builder name(String name) {
public Builder<M> name(String name) {
this.name = name;
return this;
}
public Builder keyWords(Set<KeyWord> val) {
keyWords.addAll(val);
public Builder<M> triggerWords(Set<KeyWord> val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val);
return this;
}
public Builder keyWord(KeyWord val) {
keyWords.add(val);
public Builder<M> triggerWord(KeyWord val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.add(val);
return this;
}
public Builder stringKeyWords(Set<String> val) {
keyWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
public Builder<M> triggerStringWords(Set<String> val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
return this;
}
public Builder keyWord(String val) {
keyWords.add(KeyWord.of(val));
public Builder<M> triggerWord(String val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.add(KeyWord.of(val));
return this;
}
public Builder phrase(String val) {
phrases.add(val);
public Builder<M> triggerPhrase(String... val) {
if (triggerPhrases == null) {
triggerPhrases = new HashSet<>();
}
if (val.length == 1) {
triggerPhrases.add(val[0]);
} else {
triggerPhrases.addAll(Set.of(val));
}
triggerPhrases.addAll(Set.of(val));
return this;
}
public Builder phrases(Collection<String> val) {
phrases.addAll(val);
public Builder<M> triggerPattern(Pattern... val) {
if (triggerPatterns == null) {
triggerPatterns = new HashSet<>();
}
if (val.length == 1) {
triggerPatterns.add(val[0]);
} else {
triggerPatterns.addAll(Set.of(val));
}
triggerPatterns.addAll(Set.of(val));
return this;
}
public Builder pattern(Pattern val) {
pattern = val;
return this;
}
private Builder triggerCheck(Predicate<String> trigger) {
private Builder<M> triggerCheck(Predicate<M> trigger) {
triggerCheck = trigger;
return this;
}
public Builder matchThreshold(Integer val) {
public Builder<M> matchThreshold(Integer val) {
matchThreshold = val;
return this;
}
public Builder priority(Integer val) {
public Builder<M> priority(Integer val) {
priority = val;
return this;
}
public Builder unitTrue(MainUnit unitTrue) {
public Builder<M> unitTrue(MainUnit unitTrue) {
this.unitTrue = unitTrue;
return this;
}
public Builder unitFalse(MainUnit unitFalse) {
public Builder<M> unitFalse(MainUnit unitFalse) {
this.unitFalse = unitFalse;
return this;
}
public Builder check(CheckData<Message> check) {
public Builder<M> check(CheckData<M> check) {
this.check = check;
return this;
}
public Builder accessibility(Accessibility val) {
public Builder<M> accessibility(Accessibility val) {
accessibility = val;
return this;
}
public Builder activeType(UnitActiveType val) {
public Builder<M> activeType(UnitActiveType val) {
activeType = val;
return this;
}
public Builder notSaveHistory() {
public Builder<M> notSaveHistory() {
notSaveHistory = true;
return this;
}
public AnswerCheck build() {
public AnswerCheck<M> build() {
isNotNull(check, unitConfigException("Необходимо установить параметр проверки."));
isAnyNotNull(unitConfigException("Необходимо задать хотя бы один unit результата проверки."));
return new AnswerCheck(this);
return new AnswerCheck<>(this);
}
}

View File

@ -24,7 +24,7 @@ import static dev.struchkov.haiti.utils.Inspector.isNotNull;
*
* @author upagge [08/07/2019]
*/
public class AnswerSave<D> extends MainUnit {
public class AnswerSave<M extends Message, D> extends MainUnit<M> {
/**
* Объект отвечающий за сохранение - репозиторий.
@ -44,22 +44,22 @@ public class AnswerSave<D> extends MainUnit {
/**
* Данные для скрытого сохранения.
*/
private final PreservableData<D, ? super Message> preservableData;
private final PreservableData<D, M> preservableData;
/**
* Скрытое сохранение.
*/
private final boolean hidden;
private final CheckSave<? super Message> checkSave;
private final CheckSave<M> checkSave;
private AnswerSave(Builder<D> builder) {
private AnswerSave(Builder<M, D> builder) {
super(
builder.name,
builder.keyWords,
builder.phrases,
builder.triggerWords,
builder.triggerPhrases,
builder.triggerCheck,
builder.pattern,
builder.triggerPatterns,
builder.matchThreshold,
builder.priority,
builder.nextUnits,
@ -77,11 +77,11 @@ public class AnswerSave<D> extends MainUnit {
checkSave = builder.checkSave;
}
public static <D> Builder<D> builder() {
public static <M extends Message, D> Builder<M, D> builder() {
return new Builder<>();
}
private void maintenanceNextUnit(Collection<MainUnit> units) {
private void maintenanceNextUnit(Collection<MainUnit<M>> units) {
if (units != null) {
units.forEach(mainUnit -> mainUnit.setActiveType(UnitActiveType.AFTER));
}
@ -99,7 +99,7 @@ public class AnswerSave<D> extends MainUnit {
return pusher;
}
public PreservableData<D, ? super Message> getPreservableData() {
public PreservableData<D, M> getPreservableData() {
return preservableData;
}
@ -107,137 +107,162 @@ public class AnswerSave<D> extends MainUnit {
return hidden;
}
public CheckSave<? super Message> getCheckSave() {
public CheckSave<M> getCheckSave() {
return checkSave;
}
public static final class Builder<D> {
public static final class Builder<M extends Message, D> {
private String name;
private final Set<KeyWord> keyWords = new HashSet<>();
private final Set<String> phrases = new HashSet<>();
private Predicate<String> triggerCheck;
private Pattern pattern;
private Set<MainUnit<M>> nextUnits;
private Set<KeyWord> triggerWords;
private Set<String> triggerPhrases;
private Set<Pattern> triggerPatterns;
private Predicate<M> triggerCheck;
private Integer matchThreshold;
private Integer priority;
private Set<MainUnit> nextUnits = new HashSet<>();
private Accessibility accessibility;
private boolean notSaveHistory;
private AnswerSavePreservable<D> preservable;
private String key;
private Pusher<D> pusher;
private PreservableData<D, ? super Message> preservableData;
private PreservableData<D, M> preservableData;
private boolean hidden;
private CheckSave<? super Message> checkSave;
private Accessibility accessibility;
private boolean notSaveHistory;
private CheckSave<M> checkSave;
private Builder() {
}
public Builder<D> name(String name) {
public Builder<M, D> name(String name) {
this.name = name;
return this;
}
public Builder<D> keyWords(Set<KeyWord> val) {
keyWords.addAll(val);
public Builder<M, D> triggerWords(Set<KeyWord> val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val);
return this;
}
public Builder<D> keyWord(KeyWord val) {
keyWords.add(val);
public Builder<M, D> triggerWord(KeyWord val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.add(val);
return this;
}
public Builder<D> stringKeyWords(Set<String> val) {
keyWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
public Builder<M, D> triggerStringWords(Set<String> val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
return this;
}
public Builder<D> keyWord(String val) {
keyWords.add(KeyWord.of(val));
public Builder<M, D> triggerWord(String val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.add(KeyWord.of(val));
return this;
}
public Builder<D> phrase(String val) {
phrases.add(val);
public Builder<M, D> triggerPhrase(String... val) {
if (checkNull(triggerPhrases)) {
triggerPhrases = new HashSet<>();
}
if (val.length == 1) {
triggerPhrases.add(val[0]);
} else {
triggerPhrases.addAll(Set.of(val));
}
triggerPhrases.addAll(Set.of(val));
return this;
}
public Builder<D> phrases(Collection<String> val) {
phrases.addAll(val);
public Builder<M, D> triggerPattern(Pattern... val) {
if (checkNull(triggerPatterns)) {
triggerPatterns = new HashSet<>();
}
if (val.length == 1) {
triggerPatterns.add(val[0]);
} else {
triggerPatterns.addAll(Set.of(val));
}
triggerPatterns.addAll(Set.of(val));
return this;
}
public Builder<D> pattern(Pattern val) {
pattern = val;
return this;
}
public Builder<D> triggerCheck(Predicate<String> trigger) {
public Builder<M, D> triggerCheck(Predicate<M> trigger) {
triggerCheck = trigger;
return this;
}
public Builder<D> matchThreshold(Integer val) {
public Builder<M, D> matchThreshold(Integer val) {
matchThreshold = val;
return this;
}
public Builder<D> priority(Integer val) {
public Builder<M, D> priority(Integer val) {
priority = val;
return this;
}
public Builder<D> nextUnits(Set<MainUnit> val) {
nextUnits = val;
return this;
}
public Builder<D> nextUnit(MainUnit val) {
public Builder<M, D> next(MainUnit<M> val) {
if (checkNull(nextUnits)) {
nextUnits = new HashSet<>();
}
nextUnits.add(val);
return this;
}
public Builder<D> preservable(AnswerSavePreservable<D> val) {
public Builder<M, D> preservable(AnswerSavePreservable<D> val) {
this.preservable = val;
return this;
}
public Builder<D> key(String val) {
public Builder<M, D> key(String val) {
this.key = val;
return this;
}
public Builder<D> pusher(Pusher<D> val) {
public Builder<M, D> pusher(Pusher<D> val) {
this.pusher = val;
return this;
}
public Builder<D> preservableData(PreservableData<D, ? super Message> val) {
public Builder<M, D> preservableData(PreservableData<D, M> val) {
this.preservableData = val;
return this;
}
public Builder<D> hidden(boolean val) {
public Builder<M, D> hidden(boolean val) {
this.hidden = val;
return this;
}
public Builder<D> checkSave(CheckSave<? super Message> val) {
public Builder<M, D> checkSave(CheckSave<M> val) {
this.checkSave = val;
return this;
}
public Builder<D> accessibility(Accessibility val) {
public Builder<M, D> accessibility(Accessibility val) {
accessibility = val;
return this;
}
public Builder<D> notSaveHistory() {
public Builder<M, D> notSaveHistory() {
notSaveHistory = true;
return this;
}
public AnswerSave<D> build() {
public AnswerSave<M, D> build() {
isNotNull(preservable, "Не указан репозиторий для сохранения формы пользователя");
if (checkNull(pusher)) {
isNotNull(preservableData, "Не указаны данные для сохранения");

View File

@ -10,10 +10,14 @@ import dev.struchkov.godfather.context.service.sender.Sending;
import dev.struchkov.godfather.context.service.usercode.Insert;
import dev.struchkov.godfather.context.service.usercode.ProcessingData;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ -24,12 +28,12 @@ import static dev.struchkov.haiti.utils.Inspector.isNotNull;
*
* @author upagge [08/07/2019]
*/
public class AnswerText<M extends Message> extends MainUnit {
public class AnswerText<M extends Message> extends MainUnit<M> {
/**
* Объект, который необходимо отправить пользователю.
*/
private final ProcessingData<M> boxAnswer;
private final ProcessingData<M> answer;
/**
* Информация, которую необходимо вставить вместо маркеров в строку ответа.
@ -39,15 +43,15 @@ public class AnswerText<M extends Message> extends MainUnit {
/**
* Объект нестандартной отправки ответа.
*/
private final Sending sending;
private final Sending sender;
private AnswerText(Builder<M> builder) {
super(
builder.name,
builder.keyWords,
builder.phrases,
builder.triggerWords,
builder.triggerPhrases,
builder.triggerCheck,
builder.pattern,
builder.triggerPatterns,
builder.matchThreshold,
builder.priority,
builder.nextUnits,
@ -56,25 +60,25 @@ public class AnswerText<M extends Message> extends MainUnit {
builder.accessibility,
TypeUnit.TEXT
);
boxAnswer = builder.boxAnswer;
answer = builder.boxAnswer;
insert = builder.insert;
sending = builder.sending;
sender = builder.sending;
}
public static <M extends Message> AnswerText<M> of(String message) {
return AnswerText.<M>builder().boxAnswer(BoxAnswer.boxAnswer(message)).build();
return AnswerText.<M>builder().answer(BoxAnswer.boxAnswer(message)).build();
}
public static <M extends Message> AnswerText<M> of(BoxAnswer boxAnswer) {
return AnswerText.<M>builder().boxAnswer(boxAnswer).build();
return AnswerText.<M>builder().answer(boxAnswer).build();
}
public static <M extends Message> Builder<M> builder() {
return new Builder<>();
}
public ProcessingData<M> getBoxAnswer() {
return boxAnswer;
public ProcessingData<M> getAnswer() {
return answer;
}
public Insert getInsert() {
@ -82,25 +86,29 @@ public class AnswerText<M extends Message> extends MainUnit {
}
public Sending getSending() {
return sending;
return sender;
}
public static final class Builder<M extends Message> {
private final Set<KeyWord> keyWords = new HashSet<>();
private final Set<String> phrases = new HashSet<>();
private Predicate<String> triggerCheck;
private String name;
private ProcessingData<M> boxAnswer;
private Insert insert;
private Sending sending;
private Pattern pattern;
private Set<MainUnit<M>> nextUnits;
private Set<KeyWord> triggerWords;
private Set<String> triggerPhrases;
private Predicate<M> triggerCheck;
private Set<Pattern> triggerPatterns;
private Integer matchThreshold;
private Integer priority;
private Set<MainUnit> nextUnits = new HashSet<>();
private UnitActiveType activeType;
private Accessibility accessibility;
private boolean notSaveHistory;
private ProcessingData<M> boxAnswer;
private Insert insert;
private Sending sending;
private Builder() {
}
@ -109,13 +117,26 @@ public class AnswerText<M extends Message> extends MainUnit {
return this;
}
public Builder<M> message(ProcessingData<M> message) {
this.boxAnswer = message;
public Builder<M> processing(Consumer<M> answer) {
this.boxAnswer = message -> {
answer.accept(message);
return Optional.empty();
};
return this;
}
public Builder<M> boxAnswer(BoxAnswer boxAnswer) {
this.boxAnswer = message -> boxAnswer;
public Builder<M> answer(Function<M, BoxAnswer> answer) {
this.boxAnswer = message -> Optional.of(answer.apply(message));
return this;
}
public Builder<M> answer(BoxAnswer answer) {
this.boxAnswer = message -> Optional.of(answer);
return this;
}
public Builder<M> answer(Supplier<BoxAnswer> answer) {
this.boxAnswer = message -> Optional.of(answer.get());
return this;
}
@ -129,46 +150,69 @@ public class AnswerText<M extends Message> extends MainUnit {
return this;
}
public Builder<M> keyWords(Set<KeyWord> val) {
keyWords.addAll(val);
public Builder<M> triggerWords(Set<KeyWord> val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val);
return this;
}
public Builder<M> keyWord(KeyWord val) {
keyWords.add(val);
public Builder<M> triggerWord(KeyWord val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.add(val);
return this;
}
public Builder<M> stringKeyWords(Set<String> val) {
keyWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
public Builder<M> triggerStringWords(Set<String> val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
return this;
}
public Builder<M> keyWord(String val) {
keyWords.add(KeyWord.of(val));
public Builder<M> triggerWord(String val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.add(KeyWord.of(val));
return this;
}
public Builder<M> phrase(String val) {
phrases.add(val);
public Builder<M> triggerPhrase(String... val) {
if (triggerPhrases == null) {
triggerPhrases = new HashSet<>();
}
if (val.length == 1) {
triggerPhrases.add(val[0]);
} else {
triggerPhrases.addAll(Set.of(val));
}
triggerPhrases.addAll(List.of(val));
return this;
}
public Builder<M> phrases(String... val) {
phrases.addAll(Arrays.asList(val));
public Builder<M> triggerPattern(Pattern... val) {
if (triggerPatterns == null) {
triggerPatterns = new HashSet<>();
}
if (val.length == 1) {
triggerPatterns.add(val[0]);
} else {
triggerPatterns.addAll(Set.of(val));
}
triggerPatterns.addAll(Set.of(val));
return this;
}
public Builder<M> triggerCheck(Predicate<String> trigger) {
public Builder<M> triggerCheck(Predicate<M> trigger) {
triggerCheck = trigger;
return this;
}
public Builder<M> pattern(Pattern val) {
pattern = val;
return this;
}
public Builder<M> matchThreshold(Integer val) {
matchThreshold = val;
return this;
@ -179,12 +223,10 @@ public class AnswerText<M extends Message> extends MainUnit {
return this;
}
public Builder<M> nextUnits(Set<MainUnit> val) {
nextUnits = val;
return this;
}
public Builder<M> nextUnit(MainUnit val) {
public Builder<M> next(MainUnit<M> val) {
if (nextUnits == null) {
nextUnits = new HashSet<>();
}
nextUnits.add(val);
return this;
}

View File

@ -6,7 +6,6 @@ import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.service.Accessibility;
import dev.struchkov.godfather.context.service.usercode.CheckData;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
@ -21,12 +20,12 @@ import static dev.struchkov.haiti.utils.Inspector.isNotNull;
*
* @author upagge [08/07/2019]
*/
public class AnswerTimer<M extends Message> extends MainUnit {
public class AnswerTimer<M extends Message> extends MainUnit<M> {
/**
* Unit обработку которого необходимо отложить.
*/
private final MainUnit unitAnswer;
private final MainUnit<M> unitAnswer;
/**
* Задержка обработки в секундах.
@ -46,10 +45,10 @@ public class AnswerTimer<M extends Message> extends MainUnit {
private AnswerTimer(Builder<M> builder) {
super(
builder.name,
builder.keyWords,
builder.phrases,
builder.triggerWords,
builder.triggerPhrases,
builder.triggerCheck,
builder.pattern,
builder.triggerPatterns,
builder.matchThreshold,
builder.priority,
null,
@ -68,7 +67,7 @@ public class AnswerTimer<M extends Message> extends MainUnit {
return new Builder<>();
}
public MainUnit getUnitAnswer() {
public MainUnit<M> getUnitAnswer() {
return unitAnswer;
}
@ -86,20 +85,23 @@ public class AnswerTimer<M extends Message> extends MainUnit {
public static final class Builder<M extends Message> {
private String name;
private MainUnit unitAnswer;
private Integer timeDelaySec;
private Integer timeDeathSec;
private CheckData<M> checkLoop;
private final Set<KeyWord> keyWords = new HashSet<>();
private final Set<String> phrases = new HashSet<>();
private Predicate<String> triggerCheck;
private Pattern pattern;
private Set<KeyWord> triggerWords;
private Set<String> triggerPhrases;
private Predicate<M> triggerCheck;
private Set<Pattern> triggerPatterns;
private Integer matchThreshold;
private Integer priority;
private UnitActiveType activeType = UnitActiveType.AFTER;
private Accessibility accessibility;
private boolean notSaveHistory;
private MainUnit<M> unitAnswer;
private Integer timeDelaySec;
private Integer timeDeathSec;
private CheckData<M> checkLoop;
private Builder() {
}
@ -108,7 +110,7 @@ public class AnswerTimer<M extends Message> extends MainUnit {
return this;
}
public Builder<M> unitAnswer(MainUnit val) {
public Builder<M> unitAnswer(MainUnit<M> val) {
unitAnswer = val;
return this;
}
@ -128,42 +130,65 @@ public class AnswerTimer<M extends Message> extends MainUnit {
return this;
}
public Builder<M> keyWords(Set<KeyWord> val) {
keyWords.addAll(val);
public Builder<M> triggerWords(Set<KeyWord> val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val);
return this;
}
public Builder<M> keyWord(KeyWord val) {
keyWords.add(val);
public Builder<M> triggerWord(KeyWord val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.add(val);
return this;
}
public Builder<M> stringKeyWords(Set<String> val) {
keyWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
public Builder<M> triggerStringWords(Set<String> val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
return this;
}
public Builder<M> keyWord(String val) {
keyWords.add(KeyWord.of(val));
public Builder<M> triggerWord(String val) {
if (triggerWords == null) {
triggerWords = new HashSet<>();
}
triggerWords.add(KeyWord.of(val));
return this;
}
public Builder<M> phrase(String val) {
phrases.add(val);
public Builder<M> triggerPhrase(String... val) {
if (triggerPhrases == null) {
triggerPhrases = new HashSet<>();
}
if (val.length == 1) {
triggerPhrases.add(val[0]);
} else {
triggerPhrases.addAll(Set.of(val));
}
triggerPhrases.addAll(Set.of(val));
return this;
}
public Builder<M> phrases(Collection<String> val) {
phrases.addAll(val);
public Builder<M> triggerPattern(Pattern... val) {
if (triggerPatterns == null) {
triggerPatterns = new HashSet<>();
}
if (val.length == 1) {
triggerPatterns.add(val[0]);
} else {
triggerPatterns.addAll(Set.of(val));
}
triggerPatterns.addAll(Set.of(val));
return this;
}
public Builder<M> pattern(Pattern val) {
pattern = val;
return this;
}
public Builder<M> triggerCheck(Predicate<String> trigger) {
public Builder<M> triggerCheck(Predicate<M> trigger) {
triggerCheck = trigger;
return this;
}

View File

@ -1,212 +0,0 @@
package dev.struchkov.godfather.context.domain.unit;
import dev.struchkov.autoresponder.entity.KeyWord;
import dev.struchkov.godfather.context.domain.TypeUnit;
import dev.struchkov.godfather.context.repository.preser.AnswerSaveMapPreservable;
import dev.struchkov.godfather.context.repository.preser.Preservable;
import dev.struchkov.godfather.context.service.Accessibility;
import dev.struchkov.godfather.context.service.ClarificationQuestion;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Обработка данных со страницы пользователя.
*
* @author upagge [11/07/2019]
*/
public class AnswerValidity extends MainUnit {
/**
* Unit обрабатывается, если пользователь подтверждает данные.
*/
private final MainUnit unitYes;
/**
* Unit обрабатывается, если пользователь отклоняет данные.
*/
private final MainUnit unitNo;
/**
* Unit обрабатывается, если данные не найдены.
*/
private final MainUnit unitNull;
private final Preservable<String> tempSave = new AnswerSaveMapPreservable<>();
private final ClarificationQuestion clarificationQuestion;
private AnswerValidity(Builder builder) {
super(
builder.name,
builder.keyWords,
builder.phrases,
builder.triggerCheck,
builder.pattern,
builder.matchThreshold,
builder.priority,
builder.nextUnits,
UnitActiveType.DEFAULT,
builder.notSaveHistory,
builder.accessibility,
TypeUnit.VALIDITY
);
unitYes = builder.unitYes;
unitNo = builder.unitNo;
unitNull = builder.unitNull;
clarificationQuestion = builder.clarificationQuestion;
}
public static Builder builder() {
return new Builder();
}
public MainUnit getUnitYes() {
return unitYes;
}
public MainUnit getUnitNo() {
return unitNo;
}
public MainUnit getUnitNull() {
return unitNull;
}
public Preservable<String> getTempSave() {
return tempSave;
}
public ClarificationQuestion getClarificationQuestion() {
return clarificationQuestion;
}
public static final class Builder {
private final Set<KeyWord> keyWords = new HashSet<>();
private final Set<String> phrases = new HashSet<>();
private Predicate<String> triggerCheck;
private String name;
private MainUnit unitYes;
private MainUnit unitNo;
private MainUnit unitNull;
private ClarificationQuestion clarificationQuestion;
private Pattern pattern;
private Integer matchThreshold;
private Integer priority;
private Set<MainUnit> nextUnits = new HashSet<>();
private Accessibility accessibility;
private boolean notSaveHistory;
private Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder unitYes(MainUnit val) {
unitYes = val;
return this;
}
public Builder unitNo(MainUnit val) {
unitNo = val;
return this;
}
public Builder unitNull(MainUnit val) {
unitNull = val;
return this;
}
public Builder clarificationQuestion(ClarificationQuestion val) {
clarificationQuestion = val;
return this;
}
public Builder keyWords(Set<KeyWord> val) {
keyWords.addAll(val);
return this;
}
public Builder keyWord(KeyWord val) {
keyWords.add(val);
return this;
}
public Builder stringKeyWords(Set<String> val) {
keyWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
return this;
}
public Builder keyWord(String val) {
keyWords.add(KeyWord.of(val));
return this;
}
public Builder phrase(String val) {
phrases.add(val);
return this;
}
public Builder phrases(Collection<String> val) {
phrases.addAll(val);
return this;
}
public Builder pattern(Pattern val) {
pattern = val;
return this;
}
public Builder triggerCheck(Predicate<String> trigger) {
triggerCheck = trigger;
return this;
}
public Builder matchThreshold(Integer val) {
matchThreshold = val;
return this;
}
public Builder priority(Integer val) {
priority = val;
return this;
}
public Builder nextUnits(Set<MainUnit> val) {
nextUnits = val;
return this;
}
public Builder nextUnit(MainUnit val) {
nextUnits.add(val);
return this;
}
public Builder clearKeyWords() {
keyWords.clear();
return this;
}
public Builder accessibility(Accessibility val) {
accessibility = val;
return this;
}
public Builder notSaveHistory() {
notSaveHistory = true;
return this;
}
public AnswerValidity build() {
return new AnswerValidity(this);
}
}
}

View File

@ -2,6 +2,7 @@ package dev.struchkov.godfather.context.domain.unit;
import dev.struchkov.autoresponder.entity.KeyWord;
import dev.struchkov.autoresponder.entity.Unit;
import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.service.Accessibility;
import java.util.Objects;
@ -16,7 +17,7 @@ import java.util.regex.Pattern;
*
* @author upagge [08/07/2019]
*/
public abstract class MainUnit extends Unit<MainUnit> {
public abstract class MainUnit<M extends Message> extends Unit<MainUnit<M>, M> {
/**
* Тип Unit-а.
@ -49,17 +50,17 @@ public abstract class MainUnit extends Unit<MainUnit> {
String name,
Set<KeyWord> keyWords,
Set<String> phrases,
Predicate<String> triggerCheck,
Pattern pattern,
Predicate<M> triggerCheck,
Set<Pattern> patterns,
Integer matchThreshold,
Integer priority,
Set<MainUnit> nextUnits,
Set<MainUnit<M>> nextUnits,
UnitActiveType activeType,
boolean notSaveHistory,
Accessibility accessibility,
String type
) {
super(keyWords, phrases, triggerCheck, pattern, matchThreshold, priority, nextUnits);
super(keyWords, phrases, triggerCheck, patterns, matchThreshold, priority, nextUnits);
this.name = name;
this.activeType = Optional.ofNullable(activeType).orElse(UnitActiveType.DEFAULT);
this.accessibility = accessibility;

View File

@ -2,27 +2,28 @@ package dev.struchkov.godfather.context.domain.unit.cmd;
import dev.struchkov.autoresponder.entity.KeyWord;
import dev.struchkov.godfather.context.domain.TypeUnit;
import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.domain.unit.MainUnit;
import dev.struchkov.godfather.context.domain.unit.UnitActiveType;
import dev.struchkov.haiti.utils.Checker;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ReplaceCmd extends MainUnit {
public class ReplaceCmd<M extends Message> extends MainUnit<M> {
private final MainUnit thisUnit;
private ReplaceCmd(Builder builder) {
private ReplaceCmd(Builder<M> builder) {
super(
builder.name,
builder.keyWords,
builder.phrases,
builder.triggerWords,
builder.triggerPhrases,
builder.triggerCheck,
builder.pattern,
builder.triggerPatterns,
builder.matchThreshold,
builder.priority,
new HashSet<>(),
@ -34,21 +35,23 @@ public class ReplaceCmd extends MainUnit {
this.thisUnit = builder.thisUnit;
}
public static Builder builder() {
return new Builder();
public static <M extends Message> Builder<M> builder() {
return new Builder<>();
}
public MainUnit getThisUnit() {
return thisUnit;
}
public static final class Builder {
private final Set<KeyWord> keyWords = new HashSet<>();
public static final class Builder<M extends Message> {
private String name;
private final Set<String> phrases = new HashSet<>();
private Predicate<String> triggerCheck;
private Pattern pattern;
private Set<String> triggerPhrases;
private Predicate<M> triggerCheck;
private Set<Pattern> triggerPatterns;
private Set<KeyWord> triggerWords;
private Integer matchThreshold;
private Integer priority;
private UnitActiveType activeType = UnitActiveType.AFTER;
@ -57,74 +60,95 @@ public class ReplaceCmd extends MainUnit {
private Builder() {
}
public Builder name(String name) {
public Builder<M> name(String name) {
this.name = name;
return this;
}
public Builder keyWords(Set<KeyWord> val) {
keyWords.addAll(val);
public Builder<M> triggerWords(Set<KeyWord> val) {
if (Checker.checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val);
return this;
}
public Builder keyWord(KeyWord val) {
keyWords.add(val);
public Builder<M> triggerWord(KeyWord val) {
if (Checker.checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.add(val);
return this;
}
public Builder stringKeyWords(Set<String> val) {
keyWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
public Builder<M> triggerStringWords(Set<String> val) {
if (Checker.checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
return this;
}
public Builder keyWord(String val) {
keyWords.add(KeyWord.of(val));
public Builder<M> triggerWord(String val) {
if (Checker.checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.add(KeyWord.of(val));
return this;
}
public Builder phrase(String val) {
phrases.add(val);
public Builder<M> triggerPhrase(String... val) {
if (Checker.checkNull(triggerPhrases)) {
triggerPhrases = new HashSet<>();
}
if (val.length == 1) {
triggerPhrases.add(val[0]);
} else {
triggerPhrases.addAll(Set.of(val));
}
return this;
}
public Builder phrases(Collection<String> val) {
phrases.addAll(val);
public Builder<M> triggerPattern(Pattern... val) {
if (Checker.checkNull(triggerPatterns)) {
triggerPatterns = new HashSet<>();
}
if (val.length == 1) {
triggerPatterns.add(val[0]);
} else {
triggerPatterns.addAll(Set.of(val));
}
triggerPatterns.addAll(Set.of(val));
return this;
}
public Builder pattern(Pattern val) {
pattern = val;
return this;
}
public Builder triggerCheck(Predicate<String> trigger) {
public Builder<M> triggerCheck(Predicate<M> trigger) {
triggerCheck = trigger;
return this;
}
public Builder matchThreshold(Integer val) {
public Builder<M> matchThreshold(Integer val) {
matchThreshold = val;
return this;
}
public Builder priority(Integer val) {
public Builder<M> priority(Integer val) {
priority = val;
return this;
}
public Builder activeType(UnitActiveType val) {
public Builder<M> activeType(UnitActiveType val) {
activeType = val;
return this;
}
public Builder thisUnit(MainUnit val) {
public Builder<M> thisUnit(MainUnit val) {
thisUnit = val;
return this;
}
public ReplaceCmd build() {
return new ReplaceCmd(this);
public ReplaceCmd<M> build() {
return new ReplaceCmd<>(this);
}
}

View File

@ -2,21 +2,23 @@ package dev.struchkov.godfather.context.domain.unit.cmd;
import dev.struchkov.autoresponder.entity.KeyWord;
import dev.struchkov.godfather.context.domain.TypeUnit;
import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.domain.unit.MainUnit;
import dev.struchkov.godfather.context.domain.unit.UnitActiveType;
import dev.struchkov.godfather.context.exception.UnitConfigException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNull;
/**
* Юнит, который позволяет откатить пользователя на предыдущие юниты в сценарии с сохранением ранее введенной информации в сообщениях.
*/
public class RollBackCmd extends MainUnit {
public class RollBackCmd<M extends Message> extends MainUnit<M> {
/**
* Количество юнитов, на которые можно откатиться назад.
@ -28,13 +30,13 @@ public class RollBackCmd extends MainUnit {
*/
private final String rollbackUnitName;
private RollBackCmd(Builder builder) {
private RollBackCmd(Builder<M> builder) {
super(
builder.name,
builder.keyWords,
builder.phrases,
builder.triggerWords,
builder.triggerPhrases,
builder.triggerCheck,
builder.pattern,
builder.triggerPatterns,
builder.matchThreshold,
builder.priority,
new HashSet<>(),
@ -47,28 +49,28 @@ public class RollBackCmd extends MainUnit {
this.rollbackUnitName = builder.rollbackUnitName;
}
public static RollBackCmd.Builder builder() {
return new RollBackCmd.Builder();
public static <M extends Message> RollBackCmd.Builder<M> builder() {
return new RollBackCmd.Builder<>();
}
public static RollBackCmd rollBack(int countToBack) {
return RollBackCmd.builder().countBack(countToBack).build();
public static <M extends Message> RollBackCmd<M> rollBack(int countToBack) {
return RollBackCmd.<M>builder().countBack(countToBack).build();
}
public static RollBackCmd singleRollBack() {
return RollBackCmd.builder().countBack(1).build();
public static <M extends Message> RollBackCmd<M> singleRollBack() {
return RollBackCmd.<M>builder().countBack(1).build();
}
public static RollBackCmd doubleRollBack() {
return RollBackCmd.builder().countBack(2).build();
public static <M extends Message> RollBackCmd<M> doubleRollBack() {
return RollBackCmd.<M>builder().countBack(2).build();
}
public static RollBackCmd rollBack(String unitName) {
return RollBackCmd.builder().rollbackUnitName(unitName).build();
public static <M extends Message> RollBackCmd<M> rollBack(String unitName) {
return RollBackCmd.<M>builder().rollbackUnitName(unitName).build();
}
public static RollBackCmd rollBack(String phrase, String unitName) {
return RollBackCmd.builder().phrase(phrase).rollbackUnitName(unitName).build();
public static <M extends Message> RollBackCmd<M> rollBack(String phrase, String unitName) {
return RollBackCmd.<M>builder().triggerPhrase(phrase).rollbackUnitName(unitName).build();
}
public int getCountBack() {
@ -79,96 +81,122 @@ public class RollBackCmd extends MainUnit {
return rollbackUnitName;
}
public static final class Builder {
private final Set<KeyWord> keyWords = new HashSet<>();
public static final class Builder<M extends Message> {
private String name;
private final Set<String> phrases = new HashSet<>();
private Predicate<String> triggerCheck;
private Pattern pattern;
private Set<String> triggerPhrases;
private Predicate<M> triggerCheck;
private Set<Pattern> triggerPatterns;
private Set<KeyWord> triggerWords;
private Integer matchThreshold;
private Integer priority;
private UnitActiveType activeType = UnitActiveType.DEFAULT;
private int countBack;
private String rollbackUnitName;
private Builder() {
}
public Builder name(String name) {
public Builder<M> name(String name) {
this.name = name;
return this;
}
public Builder keyWords(Set<KeyWord> val) {
keyWords.addAll(val);
public Builder<M> triggerWords(Set<KeyWord> val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val);
return this;
}
public Builder keyWord(KeyWord val) {
keyWords.add(val);
public Builder<M> triggerWord(KeyWord val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.add(val);
return this;
}
public Builder stringKeyWords(Set<String> val) {
keyWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
public Builder<M> triggerStringWords(Set<String> val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
return this;
}
public Builder keyWord(String val) {
keyWords.add(KeyWord.of(val));
public Builder<M> triggerWord(String val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.add(KeyWord.of(val));
return this;
}
public Builder phrase(String val) {
phrases.add(val);
public Builder<M> triggerPhrase(String... val) {
if (checkNull(triggerPhrases)) {
triggerPhrases = new HashSet<>();
}
if (val.length == 1) {
triggerPhrases.add(val[0]);
} else {
triggerPhrases.addAll(Set.of(val));
}
triggerPhrases.addAll(Set.of(val));
return this;
}
public Builder triggerCheck(Predicate<String> trigger) {
public Builder<M> triggerCheck(Predicate<M> trigger) {
triggerCheck = trigger;
return this;
}
public Builder phrases(Collection<String> val) {
phrases.addAll(val);
public Builder<M> triggerPattern(Pattern... val) {
if (checkNull(triggerPatterns)) {
triggerPatterns = new HashSet<>();
}
if (val.length == 1) {
triggerPatterns.add(val[0]);
} else {
triggerPatterns.addAll(Set.of(val));
}
triggerPatterns.addAll(Set.of(val));
return this;
}
public Builder pattern(Pattern val) {
pattern = val;
return this;
}
public Builder matchThreshold(Integer val) {
public Builder<M> matchThreshold(Integer val) {
matchThreshold = val;
return this;
}
public Builder priority(Integer val) {
public Builder<M> priority(Integer val) {
priority = val;
return this;
}
public Builder activeType(UnitActiveType val) {
public Builder<M> activeType(UnitActiveType val) {
activeType = val;
return this;
}
public Builder countBack(int val) {
public Builder<M> countBack(int val) {
countBack = val + 1;
return this;
}
public Builder rollbackUnitName(String val) {
public Builder<M> rollbackUnitName(String val) {
rollbackUnitName = val;
return this;
}
public RollBackCmd build() {
public RollBackCmd<M> build() {
if (rollbackUnitName == null && countBack < 2) {
throw new UnitConfigException("Ошибка конфигурирования юнита {0}: Количество юнитов для отката не должно быть меньше 1.", name);
}
return new RollBackCmd(this);
return new RollBackCmd<>(this);
}
}

View File

@ -2,33 +2,35 @@ package dev.struchkov.godfather.context.domain.unit.cmd;
import dev.struchkov.autoresponder.entity.KeyWord;
import dev.struchkov.godfather.context.domain.TypeUnit;
import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.domain.unit.MainUnit;
import dev.struchkov.godfather.context.domain.unit.UnitActiveType;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNull;
/**
* Позволяет перенести пользователя в произвольное место в сценарии.
*/
public class TeleportCmd extends MainUnit {
public class TeleportCmd<M extends Message> extends MainUnit<M> {
/**
* Название юнита, в которое необходимо осуществить перенос.
*/
private final String unitNameToTeleport;
private TeleportCmd(Builder builder) {
private TeleportCmd(Builder<M> builder) {
super(
builder.name,
builder.keyWords,
builder.phrases,
builder.triggerWords,
builder.triggerPhrases,
builder.triggerCheck,
builder.pattern,
builder.triggerPatterns,
builder.matchThreshold,
builder.priority,
new HashSet<>(),
@ -40,21 +42,23 @@ public class TeleportCmd extends MainUnit {
this.unitNameToTeleport = builder.unitNameToTeleport;
}
public static Builder builder() {
return new Builder();
public static <M extends Message> Builder<M> builder() {
return new Builder<>();
}
public String getUnitNameToTeleport() {
return unitNameToTeleport;
}
public static final class Builder {
private final Set<KeyWord> keyWords = new HashSet<>();
private final Set<String> phrases = new HashSet<>();
private Predicate<String> triggerCheck;
public static final class Builder<M extends Message> {
private String name;
private Pattern pattern;
private Set<KeyWord> triggerWords;
private Set<String> triggerPhrases;
private Set<Pattern> triggerPatterns;
private Predicate<M> triggerCheck;
private Integer matchThreshold;
private Integer priority;
private UnitActiveType activeType = UnitActiveType.DEFAULT;
private String unitNameToTeleport;
@ -62,73 +66,96 @@ public class TeleportCmd extends MainUnit {
private Builder() {
}
public Builder name(String name) {
public Builder<M> name(String name) {
this.name = name;
return this;
}
public Builder keyWords(Set<KeyWord> val) {
keyWords.addAll(val);
public Builder<M> triggerWords(Set<KeyWord> val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val);
return this;
}
public Builder keyWord(KeyWord val) {
keyWords.add(val);
public Builder<M> triggerWord(KeyWord val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.add(val);
return this;
}
public Builder stringKeyWords(Set<String> val) {
keyWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
public Builder<M> triggerStringWords(Set<String> val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.addAll(val.stream().map(KeyWord::of).collect(Collectors.toSet()));
return this;
}
public Builder keyWord(String val) {
keyWords.add(KeyWord.of(val));
public Builder<M> triggerWord(String val) {
if (checkNull(triggerWords)) {
triggerWords = new HashSet<>();
}
triggerWords.add(KeyWord.of(val));
return this;
}
public Builder phrase(String val) {
phrases.add(val);
public Builder<M> triggerPhrase(String... val) {
if (checkNull(triggerPhrases)) {
triggerPhrases = new HashSet<>();
}
if (val.length == 1) {
triggerPhrases.add(val[0]);
} else {
triggerPhrases.addAll(Set.of(val));
}
triggerPhrases.addAll(Set.of(val));
return this;
}
public Builder phrases(Collection<String> val) {
phrases.addAll(val);
public Builder<M> triggerPattern(Pattern... val) {
if (checkNull(triggerPatterns)) {
triggerPatterns = new HashSet<>();
}
if (val.length == 1) {
triggerPatterns.add(val[0]);
} else {
triggerPatterns.addAll(Set.of(val));
}
triggerPatterns.addAll(Set.of(val));
return this;
}
public Builder pattern(Pattern val) {
pattern = val;
return this;
}
public Builder triggerCheck(Predicate<String> trigger) {
public Builder<M> triggerCheck(Predicate<M> trigger) {
triggerCheck = trigger;
return this;
}
public Builder matchThreshold(Integer val) {
public Builder<M> matchThreshold(Integer val) {
matchThreshold = val;
return this;
}
public Builder priority(Integer val) {
public Builder<M> priority(Integer val) {
priority = val;
return this;
}
public Builder activeType(UnitActiveType val) {
public Builder<M> activeType(UnitActiveType val) {
activeType = val;
return this;
}
public Builder unitNameToTeleport(String val) {
public Builder<M> unitNameToTeleport(String val) {
unitNameToTeleport = val;
return this;
}
public TeleportCmd build() {
return new TeleportCmd(this);
public TeleportCmd<M> build() {
return new TeleportCmd<>(this);
}
}

View File

@ -8,28 +8,28 @@ import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.Set;
public interface StorylineService<T extends Message> {
public interface StorylineService<M extends Message> {
void save(@NotNull StorylineHistory storylineHistory);
Optional<MainUnit> getUnitNameByPersonId(@NotNull Long personId);
Optional<MainUnit<M>> getUnitNameByPersonId(@NotNull Long personId);
Set<MainUnit> getNextUnitByPersonId(@NotNull Long personId);
Set<MainUnit<M>> getNextUnitByPersonId(@NotNull Long personId);
void save(Long personId, String name, T message);
void save(Long personId, String name, M message);
Optional<StorylineHistory> replaceUserToBack(long personId, int countUnitsToBack);
Optional<StorylineHistory> replaceUserToBack(long personId, String unitName);
Optional<MainUnit> getDefaultUnit();
Optional<MainUnit<M>> getDefaultUnit();
/**
* Ленивая (поздняя) связка юнитов между собой. Осуществляется уже после создания сценария. С помощью данного подхода можно реализовать циклические зависимости юнитов. Либо можно использовать {@link dev.struchkov.godfather.context.domain.unit.cmd.TeleportCmd}
*/
void lazyLink(String firstName, String secondName);
Optional<MainUnit> getUnitByName(String unitName);
Optional<MainUnit<M>> getUnitByName(String unitName);
void setDefaultUnit(String unitName);

View File

@ -9,8 +9,8 @@ import dev.struchkov.godfather.context.domain.unit.MainUnit;
* @author upagge [04/08/2019]
*/
@FunctionalInterface
public interface CheckSave<D extends Message> {
public interface CheckSave<M extends Message> {
MainUnit check(D content);
MainUnit<M> check(M content);
}

View File

@ -3,8 +3,8 @@ package dev.struchkov.godfather.context.service.save;
import dev.struchkov.godfather.context.domain.content.Message;
@FunctionalInterface
public interface PreservableData<E, C extends Message> {
public interface PreservableData<D, M extends Message> {
E getData(C content);
D getData(M content);
}

View File

@ -2,9 +2,11 @@ package dev.struchkov.godfather.context.service.usercode;
import dev.struchkov.godfather.context.domain.BoxAnswer;
import java.util.Optional;
@FunctionalInterface
public interface ProcessingData<C> {
BoxAnswer processing(C content);
Optional<BoxAnswer> processing(C content);
}

View File

@ -6,7 +6,7 @@
<parent>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>godfather-bot</artifactId>
<version>0.0.17</version>
<version>0.0.18</version>
</parent>
<artifactId>bot-core</artifactId>

View File

@ -18,7 +18,6 @@ import dev.struchkov.godfather.core.service.action.AnswerCheckAction;
import dev.struchkov.godfather.core.service.action.AnswerSaveAction;
import dev.struchkov.godfather.core.service.action.AnswerTextAction;
import dev.struchkov.godfather.core.service.action.AnswerTimerAction;
import dev.struchkov.godfather.core.service.action.AnswerValidityAction;
import dev.struchkov.godfather.core.service.action.cmd.ReplaceCmdAction;
import dev.struchkov.godfather.core.service.timer.TimerService;
import dev.struchkov.haiti.context.exception.NotFoundException;
@ -30,18 +29,18 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public class GeneralAutoResponder<T extends Message> {
public class GeneralAutoResponder<M extends Message> {
private final PersonSettingService personSettingService;
private final StorylineService<T> storyLineService;
protected Map<String, ActionUnit<? extends MainUnit, ? extends Message>> actionUnitMap = new HashMap<>();
protected List<Modifiable<T>> modifiable;
private final StorylineService<M> storyLineService;
protected Map<String, ActionUnit> actionUnitMap = new HashMap<>();
protected List<Modifiable<M>> modifiable;
private ErrorHandler errorHandler;
protected GeneralAutoResponder(
Sending sending,
PersonSettingService personSettingService,
StorylineService<T> storyLineService
StorylineService<M> storyLineService
) {
this.personSettingService = personSettingService;
this.storyLineService = storyLineService;
@ -49,17 +48,16 @@ public class GeneralAutoResponder<T extends Message> {
}
private void init(Sending sending) {
actionUnitMap.put(TypeUnit.CHECK, new AnswerCheckAction());
actionUnitMap.put(TypeUnit.CHECK, new AnswerCheckAction<>());
actionUnitMap.put(TypeUnit.TEXT, new AnswerTextAction(sending));
actionUnitMap.put(TypeUnit.VALIDITY, new AnswerValidityAction());
actionUnitMap.put(TypeUnit.REPLACE_CMD, new ReplaceCmdAction());
}
public void initModifiable(List<Modifiable<T>> modifiable) {
public void initModifiable(List<Modifiable<M>> modifiable) {
this.modifiable = modifiable;
}
public void initActionUnit(String typeUnit, ActionUnit<? extends MainUnit, T> actionUnit) {
public void initActionUnit(String typeUnit, ActionUnit<? extends MainUnit<M>, M> actionUnit) {
if (!actionUnitMap.containsKey(typeUnit)) {
actionUnitMap.put(typeUnit, actionUnit);
} else {
@ -67,7 +65,7 @@ public class GeneralAutoResponder<T extends Message> {
}
}
public void initSaveAction(AnswerSaveAction<?> answerSaveAction) {
public void initSaveAction(AnswerSaveAction<M, ?> answerSaveAction) {
actionUnitMap.put(TypeUnit.SAVE, answerSaveAction);
}
@ -86,7 +84,7 @@ public class GeneralAutoResponder<T extends Message> {
storyLineService.setDefaultUnit(unitName);
}
public void processingNewMessage(T newMessage) {
public void processingNewMessage(M newMessage) {
if (newMessage != null) {
final boolean state = personSettingService.getStateProcessingByPersonId(newMessage.getPersonId()).orElse(true);
if (state) {
@ -95,39 +93,39 @@ public class GeneralAutoResponder<T extends Message> {
}
}
public void processingNewMessages(List<T> newMessages) {
public void processingNewMessages(List<M> newMessages) {
if (newMessages != null && !newMessages.isEmpty()) {
final Set<Long> personIds = newMessages.stream()
.map(Message::getPersonId)
.collect(Collectors.toSet());
final Set<Long> disableIds = personSettingService.getAllPersonIdDisableMessages(personIds);
final List<T> allowedMessages = newMessages.stream()
final List<M> allowedMessages = newMessages.stream()
.filter(message -> !disableIds.contains(message.getPersonId()))
.toList();
allowedMessages.parallelStream().forEach(this::processing);
}
}
private void processing(T message) {
private void processing(M message) {
if (modifiable != null) {
modifiable.forEach(m -> m.change(message));
}
final Set<MainUnit> units = storyLineService.getNextUnitByPersonId(message.getPersonId());
final Optional<MainUnit> optAnswer = Responder.nextUnit(message.getText(), units)
final Set<MainUnit<M>> units = storyLineService.getNextUnitByPersonId(message.getPersonId());
final Optional<MainUnit<M>> optAnswer = Responder.nextUnit(message, units)
.or(storyLineService::getDefaultUnit);
if (optAnswer.isPresent()) {
final MainUnit answer = optAnswer.get();
final MainUnit<M> answer = optAnswer.get();
if (checkPermission(answer.getAccessibility(), message)) {
answer(UnitRequest.of(answer, message));
}
}
}
private boolean checkPermission(Optional<Accessibility> accessibility, T message) {
private boolean checkPermission(Optional<Accessibility> accessibility, M message) {
return accessibility.isEmpty() || accessibility.get().check(message);
}
public void answer(UnitRequest<MainUnit, T> unitRequest) {
public void answer(UnitRequest<MainUnit<M>, M> unitRequest) {
try {
unitRequest = getAction(unitRequest);
activeUnitAfter(unitRequest);
@ -140,10 +138,10 @@ public class GeneralAutoResponder<T extends Message> {
}
}
private UnitRequest<MainUnit, T> activeUnitAfter(UnitRequest<MainUnit, T> unitRequest) {
final Set<MainUnit> nextUnits = unitRequest.getUnit().getNextUnits();
private UnitRequest<MainUnit<M>, M> activeUnitAfter(UnitRequest<MainUnit<M>, M> unitRequest) {
final Set<MainUnit<M>> nextUnits = unitRequest.getUnit().getNextUnits();
if (nextUnits != null) {
Optional<MainUnit> first = nextUnits.stream()
Optional<MainUnit<M>> first = nextUnits.stream()
.filter(unit -> UnitActiveType.AFTER.equals(unit.getActiveType()))
.findFirst();
if (first.isPresent()) {
@ -154,18 +152,18 @@ public class GeneralAutoResponder<T extends Message> {
return unitRequest;
}
private UnitRequest<MainUnit, T> getAction(UnitRequest<MainUnit, T> unitRequest) {
final MainUnit unit = unitRequest.getUnit();
final T message = unitRequest.getMessage();
private UnitRequest<MainUnit<M>, M> getAction(UnitRequest<MainUnit<M>, M> unitRequest) {
final MainUnit<M> unit = unitRequest.getUnit();
final M message = unitRequest.getMessage();
final String typeUnit = unit.getType();
if (actionUnitMap.containsKey(typeUnit)) {
ActionUnit actionUnit = actionUnitMap.get(typeUnit);
UnitRequest<MainUnit, T> newUnitRequest = actionUnit.action(unitRequest);
final Optional<MainUnit> optDefaultUnit = storyLineService.getDefaultUnit();
UnitRequest<MainUnit<M>, M> newUnitRequest = actionUnit.action(unitRequest);
final Optional<MainUnit<M>> optDefaultUnit = storyLineService.getDefaultUnit();
if (!unit.isNotSaveHistory() && (optDefaultUnit.isEmpty() || !optDefaultUnit.get().equals(unit))) {
storyLineService.save(message.getPersonId(), unit.getName(), message);
}
final MainUnit newUnit = newUnitRequest.getUnit();
final MainUnit<M> newUnit = newUnitRequest.getUnit();
return !unit.equals(newUnit) ? getAction(newUnitRequest) : unitRequest;
} else {
throw new NotFoundException("ActionUnit для типа {0} не зарегистрирован", unit.getType());

View File

@ -1,5 +1,6 @@
package dev.struchkov.godfather.core;
import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.domain.unit.MainUnit;
import dev.struchkov.haiti.utils.Inspector;
import org.jetbrains.annotations.NotNull;
@ -10,22 +11,22 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class Storyline {
public class Storyline<M extends Message> {
private final Set<MainUnit> startingUnits = new HashSet<>();
private final Set<MainUnit> globalUnits = new HashSet<>();
private final Map<String, MainUnit> units = new HashMap<>();
private final Set<MainUnit<M>> startingUnits = new HashSet<>();
private final Set<MainUnit<M>> globalUnits = new HashSet<>();
private final Map<String, MainUnit<M>> units = new HashMap<>();
public Storyline(Set<MainUnit> startingUnits, Map<String, MainUnit> units) {
public Storyline(Set<MainUnit<M>> startingUnits, Map<String, MainUnit<M>> units) {
this.startingUnits.addAll(startingUnits);
this.units.putAll(units);
}
public void addGlobalUnits(Set<MainUnit> globalUnits) {
public void addGlobalUnits(Set<MainUnit<M>> globalUnits) {
this.globalUnits.addAll(globalUnits);
}
public Set<MainUnit> getGlobalUnits() {
public Set<MainUnit<M>> getGlobalUnits() {
return globalUnits;
}
@ -34,20 +35,20 @@ public class Storyline {
*
* @param unitName Название юнита.
*/
public Optional<MainUnit> getUnit(String unitName) {
public Optional<MainUnit<M>> getUnit(String unitName) {
Inspector.isNotNull(unitName);
return Optional.ofNullable(units.get(unitName));
}
public Set<MainUnit> getStartingUnits() {
public Set<MainUnit<M>> getStartingUnits() {
return startingUnits;
}
//TODO [22.06.2022]: Временное решение ленивой связки юнитов, пока не будет реализован нормальный механизм.
public void link(@NotNull String firstName, @NotNull String secondName) {
Inspector.isNotNull(firstName, secondName);
final MainUnit firstUnit = units.get(firstName);
final MainUnit secondUnit = units.get(secondName);
final MainUnit<M> firstUnit = units.get(firstName);
final MainUnit<M> secondUnit = units.get(secondName);
Inspector.isNotNull(firstUnit, secondUnit);
firstUnit.getNextUnits().add(secondUnit);
}

View File

@ -2,6 +2,7 @@ package dev.struchkov.godfather.core;
import dev.struchkov.godfather.context.domain.UnitDefinition;
import dev.struchkov.godfather.context.domain.annotation.Unit;
import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.domain.unit.MainUnit;
import dev.struchkov.godfather.context.exception.UnitConfigException;
import dev.struchkov.haiti.utils.Inspector;
@ -22,14 +23,14 @@ import java.util.stream.Collectors;
import static dev.struchkov.godfather.context.exception.UnitConfigException.unitConfigException;
public class StorylineMaker {
public class StorylineMaker<M extends Message> {
private static final Logger log = LoggerFactory.getLogger(StorylineMaker.class);
private final List<Object> configurations = new ArrayList<>();
private final Map<String, UnitDefinition> unitDefinitions = new HashMap<>();
private final Map<String, MainUnit> unitMap = new HashMap<>();
private final Map<String, MainUnit<M>> unitMap = new HashMap<>();
private final Set<String> mainUnits = new HashSet<>();
private final Set<String> globalUnits = new HashSet<>();
@ -42,17 +43,17 @@ public class StorylineMaker {
return unitDefinitions;
}
public Map<String, MainUnit> getUnitMap() {
public Map<String, MainUnit<M>> getUnitMap() {
return unitMap;
}
public Storyline createStoryLine() {
public Storyline<M> createStoryLine() {
generateUnitDefinitions();
try {
createUnitMap();
final Set<MainUnit> mainUnit = getMainUnit();
final Set<MainUnit> globalUnit = getGlobalUnit();
final Storyline storyline = new Storyline(mainUnit, unitMap);
final Set<MainUnit<M>> mainUnit = getMainUnit();
final Set<MainUnit<M>> globalUnit = getGlobalUnit();
final Storyline<M> storyline = new Storyline<>(mainUnit, unitMap);
storyline.addGlobalUnits(globalUnit);
return storyline;
} catch (IllegalAccessException | InvocationTargetException e) {
@ -61,14 +62,14 @@ public class StorylineMaker {
throw new UnitConfigException("Ошибка построения StoryLine");
}
private Set<MainUnit> getMainUnit() {
private Set<MainUnit<M>> getMainUnit() {
Inspector.isNotEmpty(mainUnits, unitConfigException("Не задан ни один mainUnit. Установите хотя бы для одного Unit флаг mainUnit"));
return mainUnits.stream()
.map(unitMap::get)
.collect(Collectors.toSet());
}
private Set<MainUnit> getGlobalUnit() {
private Set<MainUnit<M>> getGlobalUnit() {
return globalUnits.stream()
.map(unitMap::get)
.collect(Collectors.toSet());
@ -85,7 +86,7 @@ public class StorylineMaker {
}
}
private MainUnit createUnit(UnitDefinition unitDefinition) throws IllegalAccessException, InvocationTargetException {
private MainUnit<M> createUnit(UnitDefinition unitDefinition) throws IllegalAccessException, InvocationTargetException {
final Object objectConfig = unitDefinition.getObjectConfig();
final String currentUnitName = unitDefinition.getName();
final Method method = unitDefinition.getMethod();
@ -95,7 +96,7 @@ public class StorylineMaker {
.map(Unit::value)
.map(unitMap::get)
.toArray();
MainUnit newUnit = (MainUnit) method.invoke(objectConfig, nextUnits);
MainUnit<M> newUnit = (MainUnit<M>) method.invoke(objectConfig, nextUnits);
newUnit.setName(currentUnitName);
unitMap.put(currentUnitName, newUnit);

View File

@ -1,32 +0,0 @@
//package dev.struchkov.godfather.core.domain.question;
//
//import dev.struchkov.godfather.context.domain.BoxAnswer;
//import lombok.Builder;
//import lombok.Getter;
//import lombok.Setter;
//import lombok.Singular;
//
//import java.util.List;
//
///**
// * Используется для конфигурации генерации цепочки Unit-ов в виде тестов для прохождения пользователем.
// *
// * @author upagge [14/07/2019]
// */
//@Getter
//@Setter
//@Builder
//public class Question {
//
// /**
// * Вопрос.
// */
// private BoxAnswer boxAnswer;
//
// /**
// * Список предполагаемых ответов.
// */
// @Singular
// private List<QuestionAnswer> questionAnswers;
//
//}

View File

@ -1,35 +0,0 @@
//package dev.struchkov.godfather.core.domain.question;
//
//import lombok.Getter;
//import lombok.Setter;
//
///**
// * Используется для конфигурации генерации цепочки Unit-ов в виде тестов для прохождения пользователем.
// * Отвечает за варианты ответов.
// *
// * @author upagge [14/07/2019]
// */
//@Getter
//@Setter
//public class QuestionAnswer {
//
// /**
// * Текстовый ответ.
// */
// private String text;
//
// /**
// * Количество балов за ответ.
// */
// private int points;
//
// public QuestionAnswer(String text, Integer points) {
// this.text = text;
// this.points = points;
// }
//
// public QuestionAnswer(String text) {
// this.text = text;
// }
//
//}

View File

@ -1,32 +0,0 @@
//package dev.struchkov.godfather.core.domain.question;
//
//import lombok.AllArgsConstructor;
//import lombok.Getter;
//import lombok.Setter;
//
///**
// * Используется для сохранения результатов ответов на вопросы.
// *
// * @author upagge [14/07/2019]
// */
//@Getter
//@Setter
//@AllArgsConstructor
//public class QuestionResult {
//
// /**
// * Вопрос.
// */
// private String question;
//
// /**
// * Ответ.
// */
// private String answer;
//
// /**
// * Количество баллов за ответ.
// */
// private Integer points;
//
//}

View File

@ -26,7 +26,7 @@ public class StorylineMailService implements StorylineService<Mail> {
private final UnitPointerService unitPointerService;
private final StorylineRepository storylineRepository;
private final Storyline storyLine;
private final Storyline<Mail> storyLine;
private String defaultUnitName;
public StorylineMailService(
@ -34,7 +34,7 @@ public class StorylineMailService implements StorylineService<Mail> {
StorylineRepository storylineRepository,
List<Object> unitConfigurations
) {
this.storyLine = new StorylineMaker(unitConfigurations).createStoryLine();
this.storyLine = new StorylineMaker<Mail>(unitConfigurations).createStoryLine();
this.unitPointerService = unitPointerService;
this.storylineRepository = storylineRepository;
}
@ -47,21 +47,21 @@ public class StorylineMailService implements StorylineService<Mail> {
}
@Override
public Optional<MainUnit> getUnitNameByPersonId(@NotNull Long personId) {
public Optional<MainUnit<Mail>> getUnitNameByPersonId(@NotNull Long personId) {
Inspector.isNotNull(personId);
return unitPointerService.getUnitNameByPersonId(personId)
.flatMap(storyLine::getUnit);
}
@Override
public Set<MainUnit> getNextUnitByPersonId(@NotNull Long personId) {
final Optional<Set<MainUnit>> optMainUnits = getUnitNameByPersonId(personId)
public Set<MainUnit<Mail>> getNextUnitByPersonId(@NotNull Long personId) {
final Optional<Set<MainUnit<Mail>>> optMainUnits = getUnitNameByPersonId(personId)
.map(Unit::getNextUnits)
.filter(mainUnits -> !mainUnits.isEmpty());
if (optMainUnits.isEmpty()) {
storylineRepository.cleanHistoryByPersonId(personId);
}
final Set<MainUnit> nextUnits = optMainUnits.orElse(storyLine.getStartingUnits());
final Set<MainUnit<Mail>> nextUnits = optMainUnits.orElse(storyLine.getStartingUnits());
nextUnits.addAll(storyLine.getGlobalUnits());
return nextUnits;
}
@ -89,7 +89,7 @@ public class StorylineMailService implements StorylineService<Mail> {
}
@Override
public Optional<MainUnit> getDefaultUnit() {
public Optional<MainUnit<Mail>> getDefaultUnit() {
if (defaultUnitName == null) return Optional.empty();
return storyLine.getUnit(defaultUnitName);
}
@ -106,7 +106,7 @@ public class StorylineMailService implements StorylineService<Mail> {
}
@Override
public Optional<MainUnit> getUnitByName(String unitName) {
public Optional<MainUnit<Mail>> getUnitByName(String unitName) {
return storyLine.getUnit(unitName);
}

View File

@ -10,13 +10,13 @@ import dev.struchkov.godfather.context.domain.unit.MainUnit;
* @author upagge [11/07/2019]
*/
@FunctionalInterface
public interface ActionUnit<M extends MainUnit, C extends Message> {
public interface ActionUnit<U extends MainUnit, M extends Message> {
/**
* Метод обработки Unit-а.
*
* @return Новый Unit, который может нуждаться в обработке
*/
UnitRequest<MainUnit, C> action(UnitRequest<M, C> unitRequest);
UnitRequest<MainUnit, M> action(UnitRequest<U, M> unitRequest);
}

View File

@ -8,23 +8,22 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
import java.util.Optional;
/**
* Обработчик Unit-а {@link AnswerCheck}.
*
* @author upagge [11/07/2019]
*/
public class AnswerCheckAction implements ActionUnit<AnswerCheck, Message> {
public class AnswerCheckAction<M extends Message> implements ActionUnit<AnswerCheck<M>, M> {
private static final Logger log = LoggerFactory.getLogger(AnswerCheckAction.class);
@Override
public UnitRequest<MainUnit, Message> action(UnitRequest<AnswerCheck, Message> unitRequest) {
final AnswerCheck unit = unitRequest.getUnit();
final Message message = unitRequest.getMessage();
public UnitRequest<MainUnit, M> action(UnitRequest<AnswerCheck<M>, M> unitRequest) {
final AnswerCheck<M> unit = unitRequest.getUnit();
final M message = unitRequest.getMessage();
MainUnit unitAnswer;
MainUnit<M> unitAnswer;
if (unit.getCheck().checked(message)) {
log.info("Проверка пройдена");
unitAnswer = unit.getUnitTrue();

View File

@ -16,25 +16,25 @@ import static dev.struchkov.haiti.utils.Checker.checkNotNull;
*
* @author upagge [11/07/2019]
*/
public class AnswerSaveAction<D> implements ActionUnit<AnswerSave<D>, Message> {
public class AnswerSaveAction<M extends Message, D> implements ActionUnit<AnswerSave<M, D>, M> {
@Override
public UnitRequest<MainUnit, Message> action(UnitRequest<AnswerSave<D>, Message> unitRequest) {
final AnswerSave<D> answerSave = unitRequest.getUnit();
final Message message = unitRequest.getMessage();
public UnitRequest<MainUnit, M> action(UnitRequest<AnswerSave<M, D>, M> unitRequest) {
final AnswerSave<M, D> answerSave = unitRequest.getUnit();
final M message = unitRequest.getMessage();
final AnswerSavePreservable<D> preservable = answerSave.getPreservable();
final Long personId = message.getPersonId();
final CheckSave<? super Message> checkSave = answerSave.getCheckSave();
final CheckSave<M> checkSave = answerSave.getCheckSave();
if (checkNotNull(checkSave)) {
MainUnit unit = checkSave.check(message);
MainUnit<M> unit = checkSave.check(message);
if (checkNotNull(unit)) {
return UnitRequest.of(unit, message);
}
}
final PreservableData<D, ? super Message> preservableData = answerSave.getPreservableData();
final PreservableData<D, M> preservableData = answerSave.getPreservableData();
if (checkNotNull(preservableData)) {
D data = preservableData.getData(message);
if (checkNotNull(data)) {

View File

@ -10,6 +10,7 @@ import dev.struchkov.godfather.context.utils.InsertWords;
import dev.struchkov.godfather.context.utils.Sender;
import java.util.List;
import java.util.Optional;
/**
* Обработчик Unit-а {@link AnswerText}.
@ -29,14 +30,17 @@ public class AnswerTextAction implements ActionUnit<AnswerText<Message>, Message
final AnswerText<Message> unit = unitRequest.getUnit();
final Message message = unitRequest.getMessage();
final BoxAnswer boxAnswer = unit.getBoxAnswer().processing(message);
replaceMarkers(unit, message, boxAnswer);
final Optional<BoxAnswer> optAnswer = unit.getAnswer().processing(message);
if (optAnswer.isPresent()) {
final BoxAnswer answer = optAnswer.get();
replaceMarkers(unit, message, answer);
final Sending answerTextSending = unit.getSending();
if (answerTextSending != null) {
Sender.sends(message, boxAnswer, answerTextSending);
} else {
Sender.sends(message, boxAnswer, this.sending);
final Sending answerTextSending = unit.getSending();
if (answerTextSending != null) {
Sender.sends(message, answer, answerTextSending);
} else {
Sender.sends(message, answer, this.sending);
}
}
return UnitRequest.of(unit, message);

View File

@ -2,11 +2,11 @@ package dev.struchkov.godfather.core.service.action;
import dev.struchkov.godfather.context.domain.UnitRequest;
import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.domain.unit.AnswerTimer;
import dev.struchkov.godfather.context.domain.unit.MainUnit;
import dev.struchkov.godfather.context.exception.TimerSettingException;
import dev.struchkov.godfather.core.GeneralAutoResponder;
import dev.struchkov.godfather.core.domain.Timer;
import dev.struchkov.godfather.context.domain.unit.AnswerTimer;
import dev.struchkov.godfather.context.domain.unit.MainUnit;
import dev.struchkov.godfather.core.service.timer.TimerActionTask;
import dev.struchkov.godfather.core.service.timer.TimerService;
@ -20,9 +20,9 @@ import java.util.Optional;
*
* @author upagge [11/07/2019]
*/
public class AnswerTimerAction implements ActionUnit<AnswerTimer, Message> {
public class AnswerTimerAction<M extends Message> implements ActionUnit<AnswerTimer<M>, M> {
private TimerService timerService;
private final TimerService timerService;
private Long verificationPeriodSec = 15L;
public AnswerTimerAction(TimerService timerService, GeneralAutoResponder generalAutoresponder) {
@ -41,9 +41,9 @@ public class AnswerTimerAction implements ActionUnit<AnswerTimer, Message> {
}
@Override
public UnitRequest<MainUnit, Message> action(UnitRequest<AnswerTimer, Message> unitRequest) {
final AnswerTimer unit = unitRequest.getUnit();
final Message message = unitRequest.getMessage();
public UnitRequest<MainUnit, M> action(UnitRequest<AnswerTimer<M>, M> unitRequest) {
final AnswerTimer<M> unit = unitRequest.getUnit();
final M message = unitRequest.getMessage();
final LocalDateTime timeActive = LocalDateTime
.now(Clock.tickSeconds(ZoneId.systemDefault()))

View File

@ -1,57 +0,0 @@
package dev.struchkov.godfather.core.service.action;
import dev.struchkov.godfather.context.domain.Clarification;
import dev.struchkov.godfather.context.domain.UnitRequest;
import dev.struchkov.godfather.context.domain.content.Message;
import dev.struchkov.godfather.context.domain.unit.AnswerText;
import dev.struchkov.godfather.context.domain.unit.AnswerValidity;
import dev.struchkov.godfather.context.domain.unit.MainUnit;
import java.util.Set;
/**
* Обработчик Unit-а {@link AnswerValidity}.
*
* @author upagge [11/07/2019]
*/
public class AnswerValidityAction implements ActionUnit<AnswerValidity, Message> {
public static final Set<String> WORDS_YES = Set.of("да", "ага");
public static final Set<String> WORDS_NO = Set.of("нет", "неа");
public static final Set<String> WORDS_YES_NO = Set.of("да", "ага", "нет", "неа");
@Override
public UnitRequest<MainUnit, Message> action(UnitRequest<AnswerValidity, Message> unitRequest) {
final AnswerValidity unit = unitRequest.getUnit();
final Message content = unitRequest.getMessage();
String message = content.getText();
Long personId = content.getPersonId();
if (WORDS_YES.contains(message.toLowerCase())) {
unit.getTempSave().getByKey(personId, "temp").ifPresent(content::setText);
return UnitRequest.of(unit.getUnitYes(), content);
} else if (WORDS_NO.contains(message.toLowerCase())) {
unit.getTempSave().getByKey(personId, "temp").ifPresent(content::setText);
return UnitRequest.of(unit.getUnitNo(), content);
} else {
Clarification clarification = unit.getClarificationQuestion().getClarification(content);
final String value = clarification.getValue();
if (value == null) {
return UnitRequest.of(unit.getUnitNull(), content);
} else {
unit.getTempSave().save(personId, "temp", value);
AnswerValidity newValidity = unit.builder()
.clearKeyWords()
.stringKeyWords(WORDS_YES_NO)
.build();
return UnitRequest.of(
AnswerText.builder()
.message(mes -> clarification.getQuestion())
.nextUnit(newValidity)
.build(),
content
);
}
}
}
}

View File

@ -10,18 +10,18 @@ import dev.struchkov.godfather.core.service.action.ActionUnit;
import static dev.struchkov.godfather.context.exception.RollBackException.rollBackException;
public class RollBackCmdAction<T extends Message> implements ActionUnit<RollBackCmd, T> {
public class RollBackCmdAction<M extends Message> implements ActionUnit<RollBackCmd<M>, M> {
private final StorylineService<T> storyLineService;
private final StorylineService<M> storyLineService;
public RollBackCmdAction(StorylineService<T> storyLineService) {
public RollBackCmdAction(StorylineService<M> storyLineService) {
this.storyLineService = storyLineService;
}
@Override
public UnitRequest<MainUnit, T> action(UnitRequest<RollBackCmd, T> unitRequest) {
final RollBackCmd unit = unitRequest.getUnit();
final T message = unitRequest.getMessage();
public UnitRequest<MainUnit, M> action(UnitRequest<RollBackCmd<M>, M> unitRequest) {
final RollBackCmd<M> unit = unitRequest.getUnit();
final M message = unitRequest.getMessage();
final int countToBack = unit.getCountBack();
final String rollbackUnitName = unit.getRollbackUnitName();
@ -30,8 +30,9 @@ public class RollBackCmdAction<T extends Message> implements ActionUnit<RollBack
? storyLineService.replaceUserToBack(message.getPersonId(), rollbackUnitName).orElseThrow(rollBackException("Юнит для возвращения не был найден"))
: storyLineService.replaceUserToBack(message.getPersonId(), countToBack).orElseThrow(rollBackException("Юнит для возвращения не был найден"));
final String unitName = history.getUnitName();
final MainUnit nextUnit = storyLineService.getUnitByName(unitName).orElse(unit);
final T oldMessage = (T) history.getMessage();
final MainUnit<M> nextUnit = storyLineService.getUnitByName(unitName).orElse(unit);
final M oldMessage = (M) history.getMessage();
return UnitRequest.of(nextUnit, oldMessage);
}
}

View File

@ -9,22 +9,24 @@ import dev.struchkov.godfather.core.service.action.ActionUnit;
import java.util.Optional;
public class TeleportCmdAction<T extends Message> implements ActionUnit<TeleportCmd, T> {
public class TeleportCmdAction<M extends Message> implements ActionUnit<TeleportCmd<M>, M> {
private final StorylineService<T> storyLineService;
private final StorylineService<M> storyLineService;
public TeleportCmdAction(StorylineService<T> storyLineService) {
public TeleportCmdAction(StorylineService<M> storyLineService) {
this.storyLineService = storyLineService;
}
@Override
public UnitRequest<MainUnit, T> action(UnitRequest<TeleportCmd, T> unitRequest) {
final TeleportCmd unit = unitRequest.getUnit();
final T message = unitRequest.getMessage();
final Optional<MainUnit> optNextUnit = storyLineService.getUnitByName(unit.getUnitNameToTeleport());
return optNextUnit
.map(mainUnit -> UnitRequest.of(mainUnit, message))
.orElseGet(() -> UnitRequest.of(unit, message));
public UnitRequest<MainUnit, M> action(UnitRequest<TeleportCmd<M>, M> unitRequest) {
final TeleportCmd<M> unit = unitRequest.getUnit();
final M message = unitRequest.getMessage();
final Optional<MainUnit<M>> optNextUnit = storyLineService.getUnitByName(unit.getUnitNameToTeleport());
if (optNextUnit.isPresent()) {
return UnitRequest.of(optNextUnit.get(), message);
} else {
return UnitRequest.of(unit, message);
}
}
}

View File

@ -1,95 +0,0 @@
//package dev.struchkov.godfather.core.utils;
//
//import dev.struchkov.godfather.context.domain.BoxAnswer;
//import dev.struchkov.godfather.context.utils.KeyBoards;
//import dev.struchkov.godfather.core.domain.question.Question;
//import dev.struchkov.godfather.core.domain.question.QuestionAnswer;
//import dev.struchkov.godfather.core.domain.question.QuestionResult;
//import dev.struchkov.godfather.core.domain.unit.AnswerSave;
//import dev.struchkov.godfather.core.domain.unit.AnswerText;
//import dev.struchkov.godfather.core.domain.unit.MainUnit;
//import dev.struchkov.godfather.core.domain.unit.UnitActiveType;
//import dev.struchkov.godfather.context.repository.preser.Preservable;
//import dev.struchkov.godfather.context.service.save.Pusher;
//
//import java.util.List;
//import java.util.Optional;
//import java.util.stream.Collectors;
//
///**
// * Утилита для быстрой генерации цепочки Unit-ов, образующих сценарий "Тестирование".
// *
// * @author upagge [14/07/2019]
// */
//public class QuestionUtils {
//
// private final Preservable<QuestionResult> preservable;
// private final List<Question> questions;
// private Pusher<QuestionResult> pusher;
//
// private QuestionUtils(List<Question> questions, Preservable<QuestionResult> preservable) {
// this.questions = questions;
// this.preservable = preservable;
// }
//
// private QuestionUtils(List<Question> questions, Preservable<QuestionResult> preservable, Pusher<QuestionResult> pusher) {
// this.questions = questions;
// this.preservable = preservable;
// this.pusher = pusher;
// }
//
// public static QuestionUtils builder(Preservable<QuestionResult> preservable, List<Question> questions) {
// return new QuestionUtils(questions, preservable);
// }
//
// public static QuestionUtils builder(Preservable<QuestionResult> preservable, Pusher<QuestionResult> pusher, List<Question> list) {
// return new QuestionUtils(list, preservable, pusher);
// }
//
// public MainUnit build(MainUnit finishUnit) {
// return generateTest(finishUnit);
// }
//
// public MainUnit build() {
// return generateTest(null);
// }
//
// private MainUnit generateTest(MainUnit finishUnit) {
// AnswerText previousUnit = null;
// for (int i = questions.size() - 1; i >= 0; i--) {
// Question question = this.questions.get(i);
// List<String> collectAnswer = question.getQuestionAnswers().stream()
// .map(QuestionAnswer::getText)
// .collect(Collectors.toList());
// BoxAnswer boxAnswer = question.getBoxAnswer().toBuilder()
// .keyBoard(KeyBoards.verticalDuoMenuString(collectAnswer)).build();
//
// AnswerText.Builder answerTextBuilder = AnswerText.builder()
// .boxAnswer(message -> boxAnswer);
//
// for (QuestionAnswer questionAnswer : question.getQuestionAnswers()) {
// AnswerSave.AnswerSaveBuilder answerSaveBuilder = AnswerSave.<QuestionResult>builder()
// .preservable(preservable)
// .preservableData(
// message -> new QuestionResult(
// question.getBoxAnswer().getMessage(),
// questionAnswer.getText(),
// questionAnswer.getPoints()
// )
// )
// .phrase(questionAnswer.getText());
// if (i != this.questions.size() - 1) {
// answerSaveBuilder.nextUnit(previousUnit).build();
// } else {
// answerSaveBuilder.pusher(pusher);
// Optional.of(finishUnit).ifPresent(answerSaveBuilder::nextUnit);
// }
// answerTextBuilder.nextUnit(answerSaveBuilder.build());
// }
// if (i == 0) answerTextBuilder.activeType(UnitActiveType.AFTER);
// previousUnit = answerTextBuilder.build();
// }
// return previousUnit;
// }
//
//}

View File

@ -6,7 +6,7 @@
<groupId>dev.struchkov.godfather</groupId>
<artifactId>godfather-bot</artifactId>
<version>0.0.17</version>
<version>0.0.18</version>
<packaging>pom</packaging>
<modules>
@ -32,13 +32,13 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<godfather.ver>0.0.17</godfather.ver>
<godfather.ver>0.0.18</godfather.ver>
<godfather.context.ver>${godfather.ver}</godfather.context.ver>
<godfather.core.ver>${godfather.ver}</godfather.core.ver>
<autoresponder.ver>3.3.0</autoresponder.ver>
<haiti.utils>1.0.3</haiti.utils>
<autoresponder.ver>3.4.0</autoresponder.ver>
<haiti.utils>1.2.0</haiti.utils>
<javax.persistence.api.ver>2.2</javax.persistence.api.ver>
<validation.api.ver>2.0.1.Final</validation.api.ver>