aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/server/TelegramBotManager.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/com/juick/server/TelegramBotManager.java')
-rw-r--r--src/main/java/com/juick/server/TelegramBotManager.java224
1 files changed, 125 insertions, 99 deletions
diff --git a/src/main/java/com/juick/server/TelegramBotManager.java b/src/main/java/com/juick/server/TelegramBotManager.java
index 22864af8..1adf16f7 100644
--- a/src/main/java/com/juick/server/TelegramBotManager.java
+++ b/src/main/java/com/juick/server/TelegramBotManager.java
@@ -47,6 +47,7 @@ import com.pengrad.telegrambot.request.SetWebhook;
import com.pengrad.telegrambot.response.GetFileResponse;
import com.pengrad.telegrambot.response.SendResponse;
import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
@@ -100,8 +101,11 @@ public class TelegramBotManager implements NotificationListener {
@PostConstruct
public void init() {
- bot = new TelegramBot.Builder(telegramToken)
- .apiUrl(apiUrl).fileApiUrl(fileApiUrl).build();
+ TelegramBot.Builder tgBuilder = new TelegramBot.Builder(telegramToken);
+ if (StringUtils.isNotEmpty(apiUrl)) {
+ tgBuilder.apiUrl(apiUrl).fileApiUrl(fileApiUrl);
+ }
+ bot = tgBuilder.build();
if (!telegramDebug) {
try {
SetWebhook webhook = new SetWebhook().url(webhookUrl);
@@ -113,6 +117,7 @@ public class TelegramBotManager implements NotificationListener {
}
} else {
bot.setUpdatesListener(updates -> {
+ logger.info("got updates: {}", updates);
updates.forEach(this::processUpdate);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
});
@@ -127,123 +132,144 @@ public class TelegramBotManager implements NotificationListener {
logger.error("error parsing telegram update: {}", update);
return;
}
- }
- User user_from = userService.getUserByUID(telegramService.getUser(message.chat().id())).orElse(AnonymousUser.INSTANCE);
- logger.info("Found juick user {}", user_from.getUid());
-
- String username = message.from().username();
- if (username == null) {
- username = message.from().firstName();
- }
- if (!user_from.isAnonymous()) {
- URI attachment = URI.create(StringUtils.EMPTY);
- if (message.photo() != null) {
- String fileId = Arrays.stream(message.photo()).max(Comparator.comparingInt(PhotoSize::fileSize))
- .orElse(new PhotoSize()).fileId();
- if (StringUtils.isNotEmpty(fileId)) {
- GetFile request = new GetFile(fileId);
- GetFileResponse response = bot.execute(request);
- logger.info("got file {}", response.file());
- try {
- URL fileURL = new URL(bot.getFullFilePath(response.file()));
- attachment = HttpUtils.downloadImage(fileURL, tmpDir);
- } catch (Exception e) {
- logger.warn("attachment exception", e);
+ User user_from = userService.getUserByUID(telegramService.getUser(message.chat().id())).orElse(AnonymousUser.INSTANCE);
+ logger.info("Found juick user {}", user_from.getUid());
+ Optional<Pair<Integer, Integer>> originalMessage = messagesService.findMessageByProperty("durovId",
+ String.valueOf(message.messageId()));
+ if (originalMessage.isPresent()) {
+ int mid = originalMessage.get().getLeft();
+ int rid = originalMessage.get().getRight();
+ // TODO: this is copypaste from api, need switch to api
+ User author = rid == 0 ? messagesService.getMessageAuthor(mid) : messagesService.getReply(mid, rid).getUser();
+ if (user_from.equals(author)) {
+ if (messagesService.updateMessage(mid, rid, message.text())) {
+ telegramNotify(message.chat().id(), "Message updated", new com.juick.Message());
+ return;
}
- logger.info("received {}", attachment);
}
+ telegramNotify(message.chat().id(), "Error updating message", new com.juick.Message());
}
- String text = message.text();
- if (StringUtils.isBlank(text)) {
- text = message.caption();
- }
- if (StringUtils.isBlank(text)) {
- text = StringUtils.EMPTY;
+ } else {
+ User user_from = userService.getUserByUID(telegramService.getUser(message.chat().id())).orElse(AnonymousUser.INSTANCE);
+ logger.info("Found juick user {}", user_from.getUid());
+
+ String username = message.from().username();
+ if (username == null) {
+ username = message.from().firstName();
}
- if (StringUtils.isNotEmpty(text) || StringUtils.isNotEmpty(attachment.toString())) {
- if (text.equalsIgnoreCase("LOGIN")
- || text.equalsIgnoreCase("PING")
- || text.equalsIgnoreCase("HELP")
- || text.equalsIgnoreCase("/login")
- || text.equalsIgnoreCase("/logout")
- || text.equalsIgnoreCase("/start")
- || text.equalsIgnoreCase("/help")) {
- String msgUrl = "http://juick.com/login?hash=" + userService.getHashByUID(user_from.getUid());
- String msg = String.format("Hi, %s!\nYou can post messages and images to Juick there.\n" +
- "Tap to [log into website](%s) to get more info", user_from.getName(), msgUrl);
- telegramNotify(message.from().id().longValue(), msg, new com.juick.Message());
- } else {
- Message replyMessage = message.replyToMessage();
- if (replyMessage != null) {
- MessageEntity[] entities = replyMessage.entities();
- if (entities == null) {
- entities = replyMessage.captionEntities();
+ if (!user_from.isAnonymous()) {
+ URI attachment = URI.create(StringUtils.EMPTY);
+ if (message.photo() != null) {
+ String fileId = Arrays.stream(message.photo()).max(Comparator.comparingInt(PhotoSize::fileSize))
+ .orElse(new PhotoSize()).fileId();
+ if (StringUtils.isNotEmpty(fileId)) {
+ GetFile request = new GetFile(fileId);
+ GetFileResponse response = bot.execute(request);
+ logger.info("got file {}", response.file());
+ try {
+ URL fileURL = new URL(bot.getFullFilePath(response.file()));
+ attachment = HttpUtils.downloadImage(fileURL, tmpDir);
+ } catch (Exception e) {
+ logger.warn("attachment exception", e);
}
- if (entities != null) {
- Optional<MessageEntity> juickLink = Arrays.stream(entities)
- .filter(this::isJuickLink)
- .findFirst();
- if (juickLink.isPresent()) {
- if (StringUtils.isNotEmpty(juickLink.get().url())) {
- UriComponents uriComponents = UriComponentsBuilder.fromUriString(
- juickLink.get().url()).build();
- String path = uriComponents.getPath();
- if (StringUtils.isNotEmpty(path) && path.length() > 1) {
- int mid = 0;
- try {
- mid = Integer.valueOf(path.substring(3));
- } catch (NumberFormatException e) {
- logger.warn("wrong mid received");
- return;
- }
- String prefix = String.format("#%d ", mid);
- if (StringUtils.isNotEmpty(uriComponents.getFragment())) {
- int rid = Integer.valueOf(uriComponents.getFragment());
- prefix = String.format("#%d/%d ", mid, rid);
- }
- CommandResult result = null;
- try {
- result = commandsManager.processCommand(user_from, prefix + text, attachment);
- String messageTxt = StringUtils.isNotEmpty(result.getMarkdown()) ? result.getMarkdown()
- : "Unknown error or unsupported command";
- telegramNotify(message.from().id().longValue(), messageTxt, new com.juick.Message());
- } catch (Exception e) {
- logger.warn("telegram exception", e);
+ logger.info("received {}", attachment);
+ }
+ }
+ String text = message.text();
+ if (StringUtils.isBlank(text)) {
+ text = message.caption();
+ }
+ if (StringUtils.isBlank(text)) {
+ text = StringUtils.EMPTY;
+ }
+ if (StringUtils.isNotEmpty(text) || StringUtils.isNotEmpty(attachment.toString())) {
+ if (text.equalsIgnoreCase("LOGIN")
+ || text.equalsIgnoreCase("PING")
+ || text.equalsIgnoreCase("HELP")
+ || text.equalsIgnoreCase("/login")
+ || text.equalsIgnoreCase("/logout")
+ || text.equalsIgnoreCase("/start")
+ || text.equalsIgnoreCase("/help")) {
+ String msgUrl = "http://juick.com/login?hash=" + userService.getHashByUID(user_from.getUid());
+ String msg = String.format("Hi, %s!\nYou can post messages and images to Juick there.\n" +
+ "Tap to [log into website](%s) to get more info", user_from.getName(), msgUrl);
+ telegramNotify(message.from().id().longValue(), msg, new com.juick.Message());
+ } else {
+ Message replyMessage = message.replyToMessage();
+ if (replyMessage != null) {
+ MessageEntity[] entities = replyMessage.entities();
+ if (entities == null) {
+ entities = replyMessage.captionEntities();
+ }
+ if (entities != null) {
+ Optional<MessageEntity> juickLink = Arrays.stream(entities)
+ .filter(this::isJuickLink)
+ .findFirst();
+ if (juickLink.isPresent()) {
+ if (StringUtils.isNotEmpty(juickLink.get().url())) {
+ UriComponents uriComponents = UriComponentsBuilder.fromUriString(
+ juickLink.get().url()).build();
+ String path = uriComponents.getPath();
+ if (StringUtils.isNotEmpty(path) && path.length() > 1) {
+ int mid = 0;
+ try {
+ mid = Integer.valueOf(path.substring(3));
+ } catch (NumberFormatException e) {
+ logger.warn("wrong mid received");
+ return;
+ }
+ String prefix = String.format("#%d ", mid);
+ if (StringUtils.isNotEmpty(uriComponents.getFragment())) {
+ int rid = Integer.valueOf(uriComponents.getFragment());
+ prefix = String.format("#%d/%d ", mid, rid);
+ }
+ executeCommand(message.messageId(), message.from().id().longValue(),
+ user_from, prefix + text, attachment);
+ } else {
+ logger.warn("invalid path: {}", path);
}
} else {
- logger.warn("invalid path: {}", path);
+ logger.warn("invalid entity: {}", juickLink);
}
} else {
- logger.warn("invalid entity: {}", juickLink);
+ telegramNotify(message.from().id().longValue(),
+ "Can not reply to this message", replyMessage.messageId(), new com.juick.Message());
}
} else {
telegramNotify(message.from().id().longValue(),
"Can not reply to this message", replyMessage.messageId(), new com.juick.Message());
}
} else {
- telegramNotify(message.from().id().longValue(),
- "Can not reply to this message", replyMessage.messageId(), new com.juick.Message());
- }
- } else {
- try {
- CommandResult result = commandsManager.processCommand(user_from, text, attachment);
- String messageTxt = StringUtils.isNotEmpty(result.getMarkdown()) ? result.getMarkdown()
- : "Unknown error or unsupported command";
- telegramNotify(message.from().id().longValue(), messageTxt, new com.juick.Message());
- } catch (Exception e) {
- logger.warn("telegram reply exception", e);
+ executeCommand(message.messageId(), message.from().id().longValue(),
+ user_from, text, attachment);
}
}
}
+ messagesService.getUnread(user_from).forEach(mid -> messagesService.setRead(user_from, mid));
+ } else {
+ List<Long> chats = telegramService.getAnonymous();
+ if (!chats.contains(message.chat().id())) {
+ logger.info("added chat with {}", username);
+ telegramService.createTelegramUser(message.from().id(), username);
+ }
+ telegramSignupNotify(message.from().id().longValue(), userService.getSignUpHashByTelegramID(message.from().id().longValue(), username));
}
- messagesService.getUnread(user_from).forEach(mid -> messagesService.setRead(user_from, mid));
- } else {
- List<Long> chats = telegramService.getAnonymous();
- if (!chats.contains(message.chat().id())) {
- logger.info("added chat with {}", username);
- telegramService.createTelegramUser(message.from().id(), username);
+ }
+ }
+
+ private void executeCommand(Integer messageId, Long userId, User user_from, String text, URI attachment) {
+ try {
+ CommandResult result = commandsManager.processCommand(user_from, text, attachment);
+ if (result.getNewMessage().isPresent()) {
+ com.juick.Message newMessage = result.getNewMessage().get();
+ messagesService.setMessageProperty(newMessage.getMid(), newMessage.getRid(), "durovId",
+ String.valueOf(messageId));
}
- telegramSignupNotify(message.from().id().longValue(), userService.getSignUpHashByTelegramID(message.from().id().longValue(), username));
+ String messageTxt = StringUtils.isNotEmpty(result.getMarkdown()) ? result.getMarkdown()
+ : "Unknown error or unsupported command";
+ telegramNotify(userId, messageTxt, new com.juick.Message());
+ } catch (Exception e) {
+ logger.warn("telegram exception", e);
}
}