aboutsummaryrefslogtreecommitdiff
path: root/juick-server/src/main/java/com/juick
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2018-08-15 00:02:13 +0300
committerGravatar Vitaly Takmazov2018-08-15 00:10:16 +0300
commitc8487940bfd0e796e7fd572e543fe2cf88e191b1 (patch)
tree7dd8fea69b4f2362470479add1d545d62f0220d9 /juick-server/src/main/java/com/juick
parent2c0cdf69f7273ffd2c2120e93ca9388cb2ec0fcd (diff)
Migrate telegram_chats to telegram table
Diffstat (limited to 'juick-server/src/main/java/com/juick')
-rw-r--r--juick-server/src/main/java/com/juick/server/TelegramBotManager.java189
-rw-r--r--juick-server/src/main/java/com/juick/service/TelegramServiceImpl.java18
2 files changed, 98 insertions, 109 deletions
diff --git a/juick-server/src/main/java/com/juick/server/TelegramBotManager.java b/juick-server/src/main/java/com/juick/server/TelegramBotManager.java
index 012a3e38..50fe40e1 100644
--- a/juick-server/src/main/java/com/juick/server/TelegramBotManager.java
+++ b/juick-server/src/main/java/com/juick/server/TelegramBotManager.java
@@ -123,115 +123,112 @@ public class TelegramBotManager implements NotificationListener {
User user_from = userService.getUserByUID(telegramService.getUser(message.chat().id())).orElse(AnonymousUser.INSTANCE);
logger.info("Found juick user {}", user_from.getUid());
- List<Long> chats = telegramService.getChats();
String username = message.from().username();
if (username == null) {
username = message.from().firstName();
}
- if (!chats.contains(message.chat().id())) {
- telegramService.addChat(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));
- } else {
- if (user_from.isAnonymous()) {
- telegramSignupNotify(message.from().id().longValue(), userService.getSignUpHashByTelegramID(message.from().id().longValue(), username));
- } else {
- 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);
- }
- logger.info("received {}", attachment);
+ 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);
}
+ 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 = Integer.valueOf(path.substring(3));
- 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);
- }
- } else {
- logger.warn("invalid path: {}", path);
+ }
+ 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 = Integer.valueOf(path.substring(3));
+ 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);
}
} else {
- logger.warn("invalid entity: {}", juickLink);
+ logger.warn("invalid path: {}", path);
}
} else {
- telegramNotify(message.from().id().longValue(),
- "Can not reply to this message", replyMessage.messageId(), new com.juick.Message());
+ logger.warn("invalid entity: {}", juickLink);
}
} 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);
- }
+ 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);
}
}
}
}
+ } 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));
}
}
@@ -256,6 +253,7 @@ public class TelegramBotManager implements NotificationListener {
public void onResponse(SendMessage request, SendResponse response) {
processTelegramResponse(chatId, response, source);
}
+
@Override
public void onFailure(SendMessage request, IOException e) {
logger.warn("telegram failure", e);
@@ -274,6 +272,7 @@ public class TelegramBotManager implements NotificationListener {
public void onResponse(SendPhoto request, SendResponse response) {
processTelegramResponse(chatId, response, source);
}
+
@Override
public void onFailure(SendPhoto request, IOException e) {
logger.warn("telegram failure", e);
@@ -286,10 +285,10 @@ public class TelegramBotManager implements NotificationListener {
int userId = telegramService.getUser(chatId);
if (!response.isOk()) {
if (response.errorCode() == 403) {
- // remove from anonymous chat
- telegramService.getChats().stream().filter(c -> c.equals(chatId)).findFirst().ifPresent(
+ // remove from anonymous users
+ telegramService.getAnonymous().stream().filter(c -> c.equals(chatId)).findFirst().ifPresent(
d -> {
- telegramService.deleteChat(d);
+ telegramService.deleteAnonymous(d);
logger.info("deleted {} chat", d);
}
);
@@ -298,8 +297,6 @@ public class TelegramBotManager implements NotificationListener {
.orElseThrow(IllegalStateException::new);
boolean status = telegramService.deleteTelegramUser(userToDelete.getUid());
logger.info("deleting telegram id of @{} : {}", userToDelete.getName(), status);
- boolean chatStatus = telegramService.deleteChat(chatId);
- logger.info("deleting telegram chat {} : {}", chatId, chatStatus);
}
} else {
logger.warn("error response, isOk: {}, errorCode: {}, description: {}",
@@ -332,6 +329,7 @@ public class TelegramBotManager implements NotificationListener {
}
});
}
+
@Override
public void processMessageEvent(MessageEvent messageEvent) {
com.juick.Message jmsg = messageEvent.getMessage();
@@ -353,7 +351,7 @@ public class TelegramBotManager implements NotificationListener {
String msg = String.format("[%s](%s) %s", MSG_LINK, msgUrl, formatPost(jmsg, true));
List<Long> users = telegramService.getTelegramIdentifiers(subscribedUsers);
- List<Long> chats = telegramService.getChats();
+ List<Long> chats = telegramService.getAnonymous();
// registered subscribed users
users.forEach(c -> telegramNotify(c, msg, jmsg));
@@ -361,6 +359,7 @@ public class TelegramBotManager implements NotificationListener {
chats.stream().filter(u -> telegramService.getUser(u) == 0).forEach(c -> telegramNotify(c, msg, jmsg));
}
}
+
@Override
public void processLikeEvent(LikeEvent likeEvent) {
User liker = likeEvent.getUser();
diff --git a/juick-server/src/main/java/com/juick/service/TelegramServiceImpl.java b/juick-server/src/main/java/com/juick/service/TelegramServiceImpl.java
index 4e37bfac..99cbabf6 100644
--- a/juick-server/src/main/java/com/juick/service/TelegramServiceImpl.java
+++ b/juick-server/src/main/java/com/juick/service/TelegramServiceImpl.java
@@ -36,24 +36,14 @@ public class TelegramServiceImpl extends BaseJdbcService implements TelegramServ
@Transactional
@Override
- public boolean addChat(final Long id) {
- try {
- return getJdbcTemplate().update("INSERT INTO telegram_chats(chat_id) VALUES(?)", id) > 0;
- } catch (DuplicateKeyException e) {
- return true;
- }
- }
-
- @Transactional
- @Override
- public boolean deleteChat(Long id) {
- return getJdbcTemplate().update("DELETE FROM telegram_chats WHERE chat_id=?", id) > 0;
+ public boolean deleteAnonymous(Long id) {
+ return getJdbcTemplate().update("DELETE FROM telegram WHERE tg_id=? AND user_id IS NULL", id) > 0;
}
@Transactional(readOnly = true)
@Override
- public List<Long> getChats() {
- return getJdbcTemplate().queryForList("SELECT chat_id FROM telegram_chats", Long.class);
+ public List<Long> getAnonymous() {
+ return getJdbcTemplate().queryForList("SELECT tg_id FROM telegram WHERE user_id IS NULL", Long.class);
}
@Transactional(readOnly = true)