aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2019-04-07 03:49:09 +0300
committerGravatar Vitaly Takmazov2019-04-07 03:49:09 +0300
commitf1278ae7119fcb77326c6d520915ecaa1527d39c (patch)
tree3d0c5eac7cef2c3e08ab9f5260f2f0dfc14d4532 /src
parent97b37acdaee5d1665c2393254bc764bb4562729c (diff)
Edit telegram messages
Diffstat (limited to 'src')
-rw-r--r--src/main/java/com/juick/server/TelegramBotManager.java224
-rw-r--r--src/main/java/com/juick/service/MessagesService.java1
-rw-r--r--src/main/java/com/juick/service/MessagesServiceImpl.java12
-rw-r--r--src/main/resources/db/migration/V1.21__recreate messages_properties with correct index.sql8
-rw-r--r--src/test/java/com/juick/server/tests/ServerTests.java7
5 files changed, 153 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);
}
}
diff --git a/src/main/java/com/juick/service/MessagesService.java b/src/main/java/com/juick/service/MessagesService.java
index 8f8c3e62..e98b2b1d 100644
--- a/src/main/java/com/juick/service/MessagesService.java
+++ b/src/main/java/com/juick/service/MessagesService.java
@@ -144,4 +144,5 @@ public interface MessagesService {
String getMessageProperty(Integer mid, Integer rid, String key);
void setMessageProperty(Integer mid, Integer rid, String key, String value);
+ Optional<Pair<Integer, Integer>> findMessageByProperty(String key, String value);
}
diff --git a/src/main/java/com/juick/service/MessagesServiceImpl.java b/src/main/java/com/juick/service/MessagesServiceImpl.java
index 798502b3..0cf321b6 100644
--- a/src/main/java/com/juick/service/MessagesServiceImpl.java
+++ b/src/main/java/com/juick/service/MessagesServiceImpl.java
@@ -1217,4 +1217,16 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ
"WHERE message_id=:mid AND reply_id=:rid AND property_key=:key", parameterSource);
}
}
+
+ @Transactional(readOnly = true)
+ @Override
+ public Optional<Pair<Integer, Integer>> findMessageByProperty(String key, String value) {
+ List<Pair<Integer, Integer>> results = jdbcTemplate.query("SELECT message_id, reply_id FROM messages_properties " +
+ "WHERE property_key=? AND property_value=?",
+ (rs, rowNum) -> Pair.of(rs.getInt(1), rs.getInt(2)), key, value);
+ if (results.size() > 0) {
+ return Optional.of(results.get(0));
+ }
+ return Optional.empty();
+ }
}
diff --git a/src/main/resources/db/migration/V1.21__recreate messages_properties with correct index.sql b/src/main/resources/db/migration/V1.21__recreate messages_properties with correct index.sql
new file mode 100644
index 00000000..685318af
--- /dev/null
+++ b/src/main/resources/db/migration/V1.21__recreate messages_properties with correct index.sql
@@ -0,0 +1,8 @@
+DROP TABLE messages_properties;
+CREATE TABLE messages_properties (
+ message_id int(10) unsigned NOT NULL,
+ reply_id smallint(5) unsigned NOT NULL,
+ property_key varchar(255) NOT NULL,
+ property_value mediumtext NOT NULL,
+ UNIQUE KEY message_key(message_id, reply_id, property_key)
+) \ No newline at end of file
diff --git a/src/test/java/com/juick/server/tests/ServerTests.java b/src/test/java/com/juick/server/tests/ServerTests.java
index cc0044b9..0039d378 100644
--- a/src/test/java/com/juick/server/tests/ServerTests.java
+++ b/src/test/java/com/juick/server/tests/ServerTests.java
@@ -55,6 +55,7 @@ import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IteratorUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.text.StringEscapeUtils;
import org.junit.After;
import org.junit.Assert;
@@ -2027,7 +2028,13 @@ public class ServerTests {
assertThat(messagesService.getMessageProperty(mid, 0,"tg_id"), is("YO"));
messagesService.setMessageProperty(mid, 0,"tg_id", "YO2");
assertThat(messagesService.getMessageProperty(mid, 0,"tg_id"), is("YO2"));
+ Pair<Integer, Integer> messageId = messagesService.findMessageByProperty("tg_id", "YO2").orElseThrow();
+ assertThat(messageId.getLeft(), is(mid));
messagesService.setMessageProperty(mid, 0, "tg_id", "");
assertThat(messagesService.getMessageProperty(mid, 0,"tg_id"), is(StringUtils.EMPTY));
+ int rid = messagesService.createReply(mid, 0, ugnich, "EOPLE", null);
+ messagesService.setMessageProperty(mid, rid, "tg_id", "hrhr");
+ Pair<Integer, Integer> replyId = messagesService.findMessageByProperty("tg_id", "hrhr").orElseThrow();
+ assertThat(replyId.getRight(), is(rid));
}
}