Переход на string вместо long для telegramId

This commit is contained in:
Struchkov Mark 2022-12-04 11:46:36 +03:00
parent 0ac055b488
commit 3a46f953ee
41 changed files with 479 additions and 86 deletions

View File

@ -5,7 +5,7 @@
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId> <artifactId>telegram-bot</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<modules> <modules>
@ -38,8 +38,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<godfather.core.ver>0.0.27</godfather.core.ver> <godfather.core.ver>0.0.29</godfather.core.ver>
<telegrambots.ver>6.1.0</telegrambots.ver> <telegrambots.ver>6.3.0</telegrambots.ver>
<haiti.version>1.4.0</haiti.version> <haiti.version>1.4.0</haiti.version>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>telegram-bot</artifactId> <artifactId>telegram-bot</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-consumer</artifactId> <artifactId>telegram-consumer</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -1,6 +1,7 @@
package dev.struchkov.godfather.telegram.main.consumer; package dev.struchkov.godfather.telegram.main.consumer;
import dev.struchkov.godfather.main.domain.content.Mail; import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.telegram.domain.attachment.ButtonClickAttachment;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery; import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.User;
@ -14,10 +15,15 @@ import java.time.LocalDateTime;
public class CallbackQueryConvert { public class CallbackQueryConvert {
public static Mail apply(CallbackQuery callbackQuery) { public static Mail apply(CallbackQuery callbackQuery) {
final String callbackData = callbackQuery.getData();
final Mail mail = new Mail(); final Mail mail = new Mail();
mail.setCreateDate(LocalDateTime.now()); mail.setCreateDate(LocalDateTime.now());
mail.setText(callbackQuery.getData()); mail.setText(callbackData);
mail.setPersonId(callbackQuery.getMessage().getChatId()); mail.addAttachment(convertToButtonClick(callbackData));
final Long chatId = callbackQuery.getMessage().getChatId();
mail.setPersonId(chatId != null ? chatId.toString() : null);
final User user = callbackQuery.getFrom(); final User user = callbackQuery.getFrom();
mail.setFirstName(user.getFirstName()); mail.setFirstName(user.getFirstName());
@ -25,4 +31,19 @@ public class CallbackQueryConvert {
return mail; return mail;
} }
private static ButtonClickAttachment convertToButtonClick(String callbackData) {
final ButtonClickAttachment buttonClickAttachment = new ButtonClickAttachment();
buttonClickAttachment.setRawCallBackData(callbackData);
if (callbackData.charAt(0) == '[' && callbackData.charAt(callbackData.length() - 1) == ']') {
final String[] args = callbackData.substring(1, callbackData.length() - 1).split(";");
for (String arg : args) {
final String[] oneArg = arg.split(":");
final String key = oneArg[0];
final String value = oneArg[1];
buttonClickAttachment.addClickArg(key, value);
}
}
return buttonClickAttachment;
}
} }

View File

@ -38,7 +38,8 @@ public final class MessageMailConvert {
public static Mail apply(Message message) { public static Mail apply(Message message) {
final Mail mail = new Mail(); final Mail mail = new Mail();
mail.setPersonId(message.getChatId()); final Long chatId = message.getChatId();
mail.setPersonId(chatId != null ? chatId.toString() : null);
mail.setText(message.getText()); mail.setText(message.getText());
mail.setCreateDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(message.getDate()), ZoneId.systemDefault())); mail.setCreateDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(message.getDate()), ZoneId.systemDefault()));
mail.setFirstName(message.getChat().getFirstName()); mail.setFirstName(message.getChat().getFirstName());

View File

@ -1,13 +1,11 @@
package dev.struchkov.godfather.telegram.main.consumer; package dev.struchkov.godfather.telegram.main.consumer;
import dev.struchkov.godfather.telegram.domain.event.Subscribe; import dev.struchkov.godfather.telegram.domain.event.Subscribe;
import dev.struchkov.haiti.utils.Exceptions;
import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated; import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import static dev.struchkov.haiti.utils.Exceptions.*;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass; import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
public final class SubscribeConvert { public final class SubscribeConvert {
@ -20,7 +18,7 @@ public final class SubscribeConvert {
final Chat chat = updated.getChat(); final Chat chat = updated.getChat();
final Subscribe subscribe = new Subscribe(); final Subscribe subscribe = new Subscribe();
subscribe.setTelegramId(chat.getId()); subscribe.setTelegramId(chat.getId().toString());
subscribe.setLastName(chat.getLastName()); subscribe.setLastName(chat.getLastName());
subscribe.setFirstName(chat.getFirstName()); subscribe.setFirstName(chat.getFirstName());
subscribe.setSubscriptionDate(LocalDateTime.now()); subscribe.setSubscriptionDate(LocalDateTime.now());

View File

@ -18,7 +18,7 @@ public final class UnsubscribeConvert {
final Chat chat = updated.getChat(); final Chat chat = updated.getChat();
final Unsubscribe unsubscribe = new Unsubscribe(); final Unsubscribe unsubscribe = new Unsubscribe();
unsubscribe.setTelegramId(chat.getId()); unsubscribe.setTelegramId(chat.getId().toString());
unsubscribe.setLastName(chat.getLastName()); unsubscribe.setLastName(chat.getLastName());
unsubscribe.setFirstName(chat.getFirstName()); unsubscribe.setFirstName(chat.getFirstName());
unsubscribe.setSubscriptionDate(LocalDateTime.now()); unsubscribe.setSubscriptionDate(LocalDateTime.now());

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-consumer</artifactId> <artifactId>telegram-consumer</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-consumer</artifactId> <artifactId>telegram-consumer</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>telegram-bot</artifactId> <artifactId>telegram-bot</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context</artifactId> <artifactId>telegram-context</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context</artifactId> <artifactId>telegram-context</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -7,6 +7,6 @@ import org.jetbrains.annotations.NotNull;
public interface TelegramSending extends Sending { public interface TelegramSending extends Sending {
Uni<Void> sendNotSave(@NotNull Long personId, @NotNull BoxAnswer boxAnswer); Uni<Void> sendNotSave(@NotNull String personId, @NotNull BoxAnswer boxAnswer);
} }

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>telegram-context</artifactId> <artifactId>telegram-context</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -4,10 +4,10 @@ import java.util.Optional;
public interface SenderStorageService { public interface SenderStorageService {
Optional<Integer> getLastSendMessage(Long telegramId); Optional<Integer> getLastSendMessage(String telegramId);
void saveLastSendMessage(Long telegramId, Integer messageId); void saveLastSendMessage(String telegramId, Integer messageId);
void removeLastSendMessage(Long telegramId); void removeLastSendMessage(String telegramId);
} }

View File

@ -6,6 +6,6 @@ import org.jetbrains.annotations.NotNull;
public interface TelegramSending extends Sending { public interface TelegramSending extends Sending {
void sendNotSave(@NotNull Long personId, @NotNull BoxAnswer boxAnswer); void sendNotSave(@NotNull String personId, @NotNull BoxAnswer boxAnswer);
} }

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId> <artifactId>telegram-bot</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modules> <modules>
<module>telegram-core-main</module> <module>telegram-core-main</module>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core</artifactId> <artifactId>telegram-core</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -1,19 +1,56 @@
package dev.struchkov.godfather.telegram.main.core; package dev.struchkov.godfather.telegram.main.core;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig;
import dev.struchkov.godfather.telegram.domain.config.TelegramConnectConfig; import dev.struchkov.godfather.telegram.domain.config.TelegramConnectConfig;
import dev.struchkov.godfather.telegram.main.context.TelegramConnect; import dev.struchkov.godfather.telegram.main.context.TelegramConnect;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.bots.DefaultAbsSender; import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.bots.DefaultBotOptions; import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.meta.bots.AbsSender; import org.telegram.telegrambots.meta.bots.AbsSender;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class TelegramDefaultConnect implements TelegramConnect { public class TelegramDefaultConnect implements TelegramConnect {
private final String botToken; private final String botToken;
private final AbsSender absSender; private final AbsSender absSender;
public TelegramDefaultConnect(TelegramConnectConfig telegramConnectConfig) { public TelegramDefaultConnect(TelegramConnectConfig connectConfig) {
this.botToken = telegramConnectConfig.getBotToken(); this.botToken = connectConfig.getBotToken();
this.absSender = new DefaultAbsSender(new DefaultBotOptions()) { this.absSender = createAbsSender(connectConfig);
}
@NotNull
private DefaultAbsSender createAbsSender(TelegramConnectConfig connectConfig) {
final DefaultBotOptions botOptions = new DefaultBotOptions();
final ProxyConfig proxyConfig = connectConfig.getProxyConfig();
if (proxyConfig != null && proxyConfig.getPassword() != null) {
try {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
proxyConfig.getUser(),
proxyConfig.getPassword().toCharArray()
);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
if (proxyConfig != null && proxyConfig.getHost() != null) {
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
System.setProperty("javax.net.debug", "all");
botOptions.setProxyHost(proxyConfig.getHost());
botOptions.setProxyPort(proxyConfig.getPort());
botOptions.setProxyType(convertProxyType(proxyConfig.getType()));
}
return new DefaultAbsSender(botOptions) {
@Override @Override
public String getBotToken() { public String getBotToken() {
return botToken; return botToken;
@ -21,6 +58,19 @@ public class TelegramDefaultConnect implements TelegramConnect {
}; };
} }
private DefaultBotOptions.ProxyType convertProxyType(ProxyConfig.Type type) {
switch (type) {
case SOCKS5:
return DefaultBotOptions.ProxyType.SOCKS5;
case SOCKS4:
return DefaultBotOptions.ProxyType.SOCKS4;
case HTTP:
return DefaultBotOptions.ProxyType.HTTP;
default:
return DefaultBotOptions.ProxyType.NO_PROXY;
}
}
@Override @Override
public AbsSender getAbsSender() { public AbsSender getAbsSender() {
return absSender; return absSender;

View File

@ -1,6 +1,7 @@
package dev.struchkov.godfather.telegram.main.core.util; package dev.struchkov.godfather.telegram.main.core.util;
import dev.struchkov.godfather.main.domain.content.Attachment; import dev.struchkov.godfather.main.domain.content.Attachment;
import dev.struchkov.godfather.telegram.domain.attachment.ButtonClickAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.CommandAttachment; import dev.struchkov.godfather.telegram.domain.attachment.CommandAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.ContactAttachment; import dev.struchkov.godfather.telegram.domain.attachment.ContactAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment; import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
@ -45,6 +46,17 @@ public final class Attachments {
return Optional.empty(); return Optional.empty();
} }
public static Optional<ButtonClickAttachment> findFirstButtonClick(Collection<Attachment> attachments) {
if (checkNotEmpty(attachments)) {
for (Attachment attachment : attachments) {
if (isButtonClick(attachment)) {
return Optional.of((ButtonClickAttachment) attachment);
}
}
}
return Optional.empty();
}
public static Optional<PictureGroupAttachment> findFirstPictureGroup(Collection<Attachment> attachments) { public static Optional<PictureGroupAttachment> findFirstPictureGroup(Collection<Attachment> attachments) {
if (checkNotEmpty(attachments)) { if (checkNotEmpty(attachments)) {
for (Attachment attachment : attachments) { for (Attachment attachment : attachments) {
@ -136,4 +148,9 @@ public final class Attachments {
return TelegramAttachmentType.LINK.name().equals(attachment.getType()); return TelegramAttachmentType.LINK.name().equals(attachment.getType());
} }
public static boolean isButtonClick(Attachment attachment) {
isNotNull(attachment);
return TelegramAttachmentType.BUTTON_CLICK.name().equals(attachment.getType());
}
} }

View File

@ -93,27 +93,35 @@ public final class InlineKeyBoards {
return keyBoard.build(); return keyBoard.build();
} }
public static InlineKeyBoard verticalDuoMenu(KeyBoardButton... buttons) { public static void verticalDuoMenu(InlineKeyBoard.Builder builder, List<? extends KeyBoardButton> buttons) {
final InlineKeyBoard.Builder keyBoard = InlineKeyBoard.builder();
boolean flag = true; boolean flag = true;
SimpleKeyBoardLine.Builder keyBoardLine = SimpleKeyBoardLine.builder(); SimpleKeyBoardLine.Builder keyBoardLine = SimpleKeyBoardLine.builder();
for (int i = 0; i <= buttons.length - 1; i++) { for (int i = 0; i <= buttons.size() - 1; i++) {
keyBoardLine.button(buttons[i]); keyBoardLine.button(buttons.get(i));
if (flag) { if (flag) {
if (i == buttons.length - 1) { if (i == buttons.size() - 1) {
keyBoard.line(keyBoardLine.build()); builder.line(keyBoardLine.build());
} else { } else {
flag = false; flag = false;
} }
} else { } else {
keyBoard.line(keyBoardLine.build()); builder.line(keyBoardLine.build());
keyBoardLine = SimpleKeyBoardLine.builder(); keyBoardLine = SimpleKeyBoardLine.builder();
flag = true; flag = true;
} }
} }
}
public static InlineKeyBoard verticalDuoMenu(List<? extends KeyBoardButton> buttons) {
final InlineKeyBoard.Builder keyBoard = InlineKeyBoard.builder();
verticalDuoMenu(keyBoard, buttons);
return keyBoard.build(); return keyBoard.build();
} }
public static InlineKeyBoard verticalDuoMenu(KeyBoardButton... buttons) {
return verticalDuoMenu(Arrays.stream(buttons).toList());
}
/** /**
* Возвращает клавиатуру формата 1xN сформированную из списка кнопок, где N - количество кнопок в списке * Возвращает клавиатуру формата 1xN сформированную из списка кнопок, где N - количество кнопок в списке
* *

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>telegram-core</artifactId> <artifactId>telegram-core</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core</artifactId> <artifactId>telegram-core</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -34,21 +34,6 @@ public class TelegramConnectBot implements TelegramConnect {
initLongPolling(telegramConnectConfig); initLongPolling(telegramConnectConfig);
} }
// public TelegramConnect(TelegramWebHookConfig telegramWebHookConfig) {
// initWebHook(telegramWebHookConfig);
// }
//
// private void initWebHook(TelegramWebHookConfig telegramWebHookConfig) {
// TelegramBotsApi botapi = new TelegramBotsApi();
// final TelegramWebhookBot telegramWebhookBot = new TelegramHookBot(telegramWebHookConfig);
// try {
// botapi.registerBot(telegramWebhookBot);
// this.telegramBot = (TelegramBot) telegramWebhookBot;
// } catch (TelegramApiRequestException e) {
// e.printStackTrace();
// }
// }
private void initLongPolling(TelegramConnectConfig telegramConnectConfig) { private void initLongPolling(TelegramConnectConfig telegramConnectConfig) {
final ProxyConfig proxyConfig = telegramConnectConfig.getProxyConfig(); final ProxyConfig proxyConfig = telegramConnectConfig.getProxyConfig();
@ -79,7 +64,6 @@ public class TelegramConnectBot implements TelegramConnect {
botOptions.setProxyPort(proxyConfig.getPort()); botOptions.setProxyPort(proxyConfig.getPort());
botOptions.setProxyType(convertProxyType(proxyConfig.getType())); botOptions.setProxyType(convertProxyType(proxyConfig.getType()));
final TelegramPollingBot bot = new TelegramPollingBot(telegramConnectConfig, botOptions); final TelegramPollingBot bot = new TelegramPollingBot(telegramConnectConfig, botOptions);
botapi = new TelegramBotsApi(DefaultBotSession.class); botapi = new TelegramBotsApi(DefaultBotSession.class);

View File

@ -11,21 +11,21 @@ import static dev.struchkov.haiti.utils.Inspector.isNotNull;
public class SenderMapStorageService implements SenderStorageService { public class SenderMapStorageService implements SenderStorageService {
private final Map<Long, Integer> lastMessageId = new HashMap<>(); private final Map<String, Integer> lastMessageId = new HashMap<>();
@Override @Override
public Optional<Integer> getLastSendMessage(Long telegramId) { public Optional<Integer> getLastSendMessage(String telegramId) {
return Optional.ofNullable(lastMessageId.get(telegramId)); return Optional.ofNullable(lastMessageId.get(telegramId));
} }
@Override @Override
public void saveLastSendMessage(@NotNull Long telegramId, @NotNull Integer messageId) { public void saveLastSendMessage(@NotNull String telegramId, @NotNull Integer messageId) {
isNotNull(telegramId); isNotNull(telegramId);
lastMessageId.put(telegramId, messageId); lastMessageId.put(telegramId, messageId);
} }
@Override @Override
public void removeLastSendMessage(Long telegramId) { public void removeLastSendMessage(String telegramId) {
lastMessageId.remove(telegramId); lastMessageId.remove(telegramId);
} }

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId> <artifactId>telegram-bot</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -0,0 +1,147 @@
package dev.struchkov.godfather.telegram.domain;
import dev.struchkov.godfather.main.domain.BoxAnswer;
import dev.struchkov.godfather.main.domain.keyboard.KeyBoardButton;
import dev.struchkov.godfather.main.domain.keyboard.KeyBoardLine;
import dev.struchkov.godfather.telegram.domain.keyboard.InlineKeyBoard;
import dev.struchkov.haiti.utils.Inspector;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import static dev.struchkov.godfather.main.domain.keyboard.simple.SimpleKeyBoardLine.simpleLine;
import static dev.struchkov.godfather.telegram.domain.UnitPaginationUtil.navigableLine;
public class UnitPage<T> {
/**
* Дополнительные линии клавиатуры. Выводятся после кнопок навигации.
*/
private final List<KeyBoardLine> additionalLines = new ArrayList<>();
/**
* Элементы, которые будут выводиться.
*/
private List<T> elements;
/**
* Номер текущей страницы.
*/
private Integer currentOffset;
/**
* Общее количество элементов на всех страницах.
*/
private Integer countAllElements;
/**
* Функция преобразования элементов с линии.
*/
private Function<T, KeyBoardLine> function;
/**
* Сообщение, которое выводится над результатами
*/
private String message;
/**
* Флаг, определяющий нужно ли заменить старое сообщение или вывести новое (по умолчанию заменять)
*/
private boolean replace;
/**
* Флаг, исключающий добавление строки с навигацией
*/
private boolean removeDefaultNavigableLine;
/**
* Сообщение, которое будет отправлено, если коллекция элементов пустая.
*/
private BoxAnswer emptyElements;
public static <T> UnitPage<T> builder() {
return new UnitPage<>();
}
public UnitPage<T> elements(List<T> elements) {
this.elements = elements;
return this;
}
public UnitPage<T> countAllElements(Integer countAllElements) {
this.countAllElements = countAllElements;
return this;
}
public UnitPage<T> currentOffset(Integer currentOffset) {
this.currentOffset = currentOffset;
return this;
}
public UnitPage<T> additionLine(KeyBoardLine line) {
additionalLines.add(line);
return this;
}
public UnitPage<T> additionLine(KeyBoardButton button) {
additionalLines.add(simpleLine(button));
return this;
}
public UnitPage<T> mapper(Function<T, KeyBoardLine> function) {
this.function = function;
return this;
}
public UnitPage<T> message(String message) {
this.message = message;
return this;
}
public UnitPage<T> replace(boolean replace) {
this.replace = replace;
return this;
}
public UnitPage<T> emptyElements(BoxAnswer boxAnswer) {
this.emptyElements = boxAnswer;
return this;
}
public UnitPage<T> removeDefaultNavigableLine() {
this.removeDefaultNavigableLine = true;
return this;
}
public BoxAnswer build() {
Inspector.isNotNull(currentOffset, countAllElements, function);
if (elements.isEmpty()) {
return emptyElements != null ? emptyElements : BoxAnswer.boxAnswer("Данные не найдены.");
} else {
final List<KeyBoardLine> lines = elements.stream()
.map(function)
.toList();
final InlineKeyBoard.Builder builder = InlineKeyBoard.builder();
lines.forEach(builder::line);
if (!removeDefaultNavigableLine) {
navigableLine(currentOffset, countAllElements).ifPresent(builder::line);
}
additionalLines.forEach(builder::line);
final InlineKeyBoard keyBoard = builder.build();
final BoxAnswer.Builder boxAnswer = BoxAnswer.builder()
.keyBoard(keyBoard)
.replace(true);
if (message != null) {
boxAnswer.message(message);
}
boxAnswer.replace(replace);
return boxAnswer.build();
}
}
}

View File

@ -0,0 +1,88 @@
package dev.struchkov.godfather.telegram.domain;
import dev.struchkov.godfather.main.domain.keyboard.KeyBoardButton;
import dev.struchkov.godfather.main.domain.keyboard.KeyBoardLine;
import dev.struchkov.godfather.main.domain.keyboard.simple.SimpleKeyBoardLine;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static dev.struchkov.godfather.main.domain.keyboard.button.SimpleButton.simpleButton;
public final class UnitPaginationUtil {
public static final String PAGE_REGEX = "^page\\s\\d*$";
private static final String PAGINATION_SCHEMA = "page %s";
private static final Pattern PATTERN_FOR_SEARCH_OFFSET = Pattern.compile("\\d++$");
/**
* Создание строки пагинации для передачи ее в payload кнопки
*/
public static String getStringForOffset(Integer offset) {
return PAGINATION_SCHEMA.formatted(offset);
}
/**
* Разбор передаваемой строки пагинации
*/
public static Optional<Integer> getOffsetFromString(String offsetString) {
if (!Pattern.matches(PAGE_REGEX, offsetString)) {
return Optional.empty();
}
final Matcher matcher = PATTERN_FOR_SEARCH_OFFSET.matcher(offsetString);
if (matcher.find()) {
final String offsetNumber = offsetString.substring(matcher.start(), matcher.end());
return Optional.of(Integer.valueOf(offsetNumber));
} else {
return Optional.empty();
}
}
/**
* Получение строки для клавиатуры, в которой содержатся кнопки навигации.
*
* @param currentOffset - текущее смещение, используемое для запроса
* @param countElements - общее количество элементов которое может вернуть запрос
*/
public static Optional<KeyBoardLine> navigableLine(Integer currentOffset, Integer countElements) {
final SimpleKeyBoardLine.Builder lineBuilder = SimpleKeyBoardLine.builder();
final Optional<KeyBoardButton> optPrevButton = getPrevPageButton(currentOffset);
final Optional<KeyBoardButton> optNextButton = getNextPageButton(currentOffset, countElements);
if (optPrevButton.isPresent() || optNextButton.isPresent()) {
optPrevButton.ifPresent(lineBuilder::button);
optNextButton.ifPresent(lineBuilder::button);
return Optional.of(lineBuilder.build());
}
return Optional.empty();
}
/**
* Получение кнопки навигации на прошлую страницу, т.к. пользователь находится на самой первой странице, то
* кнопки перехода на предыдущую страницу может и не быть
*/
private static Optional<KeyBoardButton> getPrevPageButton(Integer currentOffset) {
if (!currentOffset.equals(0)) {
int prevOffset = currentOffset < 5 ? 0 : currentOffset - 5;
return Optional.of(simpleButton("", getStringForOffset(prevOffset)));
}
return Optional.empty();
}
/**
* Получение кнопки навигации на следующую страницу, т.к. пользователь может находиться на последней странице,
* то кнопки навигации вперед может и не быть
*/
private static Optional<KeyBoardButton> getNextPageButton(Integer currentOffset, Integer countElements) {
final Integer nextOffset = currentOffset + 5;
if (nextOffset.compareTo(countElements) < 0) {
return Optional.of(simpleButton("", getStringForOffset(nextOffset)));
}
return Optional.empty();
}
}

View File

@ -0,0 +1,69 @@
package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static dev.struchkov.haiti.context.exception.NotFoundException.notFoundException;
import static dev.struchkov.haiti.utils.Inspector.isNotNull;
public class ButtonClickAttachment extends Attachment {
private String rawCallBackData;
private final Map<String, Arg> args = new HashMap<>();
public String getRawCallBackData() {
return rawCallBackData;
}
public void setRawCallBackData(String rawCallBackData) {
this.rawCallBackData = rawCallBackData;
}
public void addClickArg(String type, String value) {
isNotNull(type, value);
args.put(type, new Arg(type, value));
}
public Optional<Arg> getArgByType(String type) {
isNotNull(type);
return Optional.ofNullable(args.get(type));
}
public Arg getArgByTypeOrThrow(String type) {
isNotNull(type);
return Optional.of(args.get(type)).orElseThrow(notFoundException("Аргумент типа {0} не найден.", type));
}
public Collection<Arg> getClickArgs() {
return args.values();
}
@Override
public String getType() {
return TelegramAttachmentType.BUTTON_CLICK.name();
}
public static class Arg {
private final String type;
private final String value;
private Arg(String type, String value) {
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public String getValue() {
return value;
}
}
}

View File

@ -4,6 +4,8 @@ import dev.struchkov.godfather.main.domain.content.Attachment;
import java.util.Optional; import java.util.Optional;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
public class CommandAttachment extends Attachment { public class CommandAttachment extends Attachment {
private String value; private String value;
@ -39,6 +41,13 @@ public class CommandAttachment extends Attachment {
return commandType; return commandType;
} }
public boolean isCommandType(String type) {
if (checkNotNull(type)) {
return type.equals(commandType);
}
return false;
}
public String getRawValue() { public String getRawValue() {
return rawValue; return rawValue;
} }

View File

@ -6,6 +6,7 @@ public enum TelegramAttachmentType {
CONTACT, CONTACT,
PICTURE, PICTURE,
LINK, LINK,
COMMAND COMMAND,
BUTTON_CLICK
} }

View File

@ -8,16 +8,16 @@ public class Subscribe implements Event {
public static final String TYPE = "SUBSCRIBE"; public static final String TYPE = "SUBSCRIBE";
private Long telegramId; private String telegramId;
private String firstName; private String firstName;
private String lastName; private String lastName;
private LocalDateTime subscriptionDate; private LocalDateTime subscriptionDate;
public Long getTelegramId() { public String getTelegramId() {
return telegramId; return telegramId;
} }
public void setTelegramId(Long telegramId) { public void setTelegramId(String telegramId) {
this.telegramId = telegramId; this.telegramId = telegramId;
} }

View File

@ -8,16 +8,16 @@ public class Unsubscribe implements Event {
public static final String TYPE = "UNSUBSCRIBE"; public static final String TYPE = "UNSUBSCRIBE";
private Long telegramId; private String telegramId;
private String firstName; private String firstName;
private String lastName; private String lastName;
private LocalDateTime subscriptionDate; private LocalDateTime subscriptionDate;
public Long getTelegramId() { public String getTelegramId() {
return telegramId; return telegramId;
} }
public void setTelegramId(Long telegramId) { public void setTelegramId(String telegramId) {
this.telegramId = telegramId; this.telegramId = telegramId;
} }

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId> <artifactId>telegram-bot</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-sender</artifactId> <artifactId>telegram-sender</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-sender</artifactId> <artifactId>telegram-sender</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -4,10 +4,10 @@ import io.smallrye.mutiny.Uni;
public interface SenderStorageService { public interface SenderStorageService {
Uni<Integer> getLastSendMessage(Long telegramId); Uni<Integer> getLastSendMessage(String telegramId);
Uni<Void> saveLastSendMessage(Long telegramId, Integer messageId); Uni<Void> saveLastSendMessage(String telegramId, Integer messageId);
Uni<Void> removeLastSendMessage(Long telegramId); Uni<Void> removeLastSendMessage(String telegramId);
} }

View File

@ -50,16 +50,16 @@ public class TelegramSender implements TelegramSending {
} }
@Override @Override
public Uni<Void> send(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer) { public Uni<Void> send(@NotNull String telegramId, @NotNull BoxAnswer boxAnswer) {
return sendBoxAnswer(telegramId, boxAnswer, true); return sendBoxAnswer(telegramId, boxAnswer, true);
} }
@Override @Override
public Uni<Void> sendNotSave(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer) { public Uni<Void> sendNotSave(@NotNull String telegramId, @NotNull BoxAnswer boxAnswer) {
return sendBoxAnswer(telegramId, boxAnswer, false); return sendBoxAnswer(telegramId, boxAnswer, false);
} }
private Uni<Void> sendBoxAnswer(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) { private Uni<Void> sendBoxAnswer(@NotNull String telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) {
return Uni.createFrom().voidItem() return Uni.createFrom().voidItem()
.onItem().transformToUni( .onItem().transformToUni(
v -> { v -> {
@ -83,7 +83,7 @@ public class TelegramSender implements TelegramSending {
); );
} }
private Uni<Void> replaceMessage(@NotNull Long telegramId, @NotNull Integer lastMessageId, @NotNull BoxAnswer boxAnswer) { private Uni<Void> replaceMessage(@NotNull String telegramId, @NotNull Integer lastMessageId, @NotNull BoxAnswer boxAnswer) {
return Uni.createFrom().voidItem() return Uni.createFrom().voidItem()
.onItem().transformToUni( .onItem().transformToUni(
v -> { v -> {
@ -103,13 +103,13 @@ public class TelegramSender implements TelegramSending {
); );
} }
private Uni<Void> sendMessage(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) { private Uni<Void> sendMessage(@NotNull String telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) {
return Uni.createFrom().voidItem() return Uni.createFrom().voidItem()
.onItem().transformToUni( .onItem().transformToUni(
v -> { v -> {
final SendMessage sendMessage = new SendMessage(); final SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(String.valueOf(telegramId)); sendMessage.setChatId(telegramId);
sendMessage.setText( sendMessage.setText(
sendPreProcessing != null sendPreProcessing != null
? sendPreProcessing.pretreatment(boxAnswer.getMessage()) ? sendPreProcessing.pretreatment(boxAnswer.getMessage())

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-sender</artifactId> <artifactId>telegram-sender</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -51,16 +51,16 @@ public class TelegramSender implements TelegramSending {
} }
@Override @Override
public void send(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer) { public void send(@NotNull String telegramId, @NotNull BoxAnswer boxAnswer) {
sendBoxAnswer(telegramId, boxAnswer, true); sendBoxAnswer(telegramId, boxAnswer, true);
} }
@Override @Override
public void sendNotSave(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer) { public void sendNotSave(@NotNull String telegramId, @NotNull BoxAnswer boxAnswer) {
sendBoxAnswer(telegramId, boxAnswer, false); sendBoxAnswer(telegramId, boxAnswer, false);
} }
private void sendBoxAnswer(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) { private void sendBoxAnswer(@NotNull String telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) {
isNotNull(telegramId, boxAnswer); isNotNull(telegramId, boxAnswer);
try { try {
if (boxAnswer.isReplace() && checkNotNull(senderStorageService)) { if (boxAnswer.isReplace() && checkNotNull(senderStorageService)) {
@ -83,9 +83,9 @@ public class TelegramSender implements TelegramSending {
} }
} }
private void replaceMessage(@NotNull Long telegramId, @NotNull Integer lastMessageId, @NotNull BoxAnswer boxAnswer) throws TelegramApiException { private void replaceMessage(@NotNull String telegramId, @NotNull Integer lastMessageId, @NotNull BoxAnswer boxAnswer) throws TelegramApiException {
final EditMessageText editMessageText = new EditMessageText(); final EditMessageText editMessageText = new EditMessageText();
editMessageText.setChatId(String.valueOf(telegramId)); editMessageText.setChatId(telegramId);
editMessageText.setMessageId(lastMessageId); editMessageText.setMessageId(lastMessageId);
editMessageText.enableMarkdown(true); editMessageText.enableMarkdown(true);
editMessageText.setText(boxAnswer.getMessage()); editMessageText.setText(boxAnswer.getMessage());
@ -93,10 +93,10 @@ public class TelegramSender implements TelegramSending {
absSender.execute(editMessageText); absSender.execute(editMessageText);
} }
private void sendMessage(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) { private void sendMessage(@NotNull String telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) {
final SendMessage sendMessage = new SendMessage(); final SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(String.valueOf(telegramId)); sendMessage.setChatId(telegramId);
sendMessage.setText( sendMessage.setText(
sendPreProcessing != null sendPreProcessing != null
? sendPreProcessing.pretreatment(boxAnswer.getMessage()) ? sendPreProcessing.pretreatment(boxAnswer.getMessage())

View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId> <artifactId>telegram-bot</artifactId>
<version>0.0.34</version> <version>0.0.38</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>