diff options
author | 2017-09-27 15:19:06 +0300 | |
---|---|---|
committer | 2017-09-28 12:54:39 +0300 | |
commit | 751b2a9b0fc523d17c9f7a410fadcc82eaaa1fb7 (patch) | |
tree | 1be25ccef6d38b4ec45084e389aed3045c1cdd70 /juick-api/src/main | |
parent | e6e25791d6b9c8360247d92340b0dccda33c86ed (diff) |
api: Telegram posting
Diffstat (limited to 'juick-api/src/main')
-rw-r--r-- | juick-api/src/main/java/com/juick/api/ApiServer.java | 37 | ||||
-rw-r--r-- | juick-api/src/main/java/com/juick/api/TelegramBotManager.java (renamed from juick-api/src/main/java/com/juick/api/TGBot.java) | 15 | ||||
-rw-r--r-- | juick-api/src/main/java/com/juick/api/configuration/ApiAppConfiguration.java | 6 | ||||
-rw-r--r-- | juick-api/src/main/java/com/juick/api/controllers/PM.java | 6 | ||||
-rw-r--r-- | juick-api/src/main/java/com/juick/api/controllers/Post.java | 79 | ||||
-rw-r--r-- | juick-api/src/main/java/com/juick/api/controllers/TelegramWebhook.java | 52 |
6 files changed, 113 insertions, 82 deletions
diff --git a/juick-api/src/main/java/com/juick/api/ApiServer.java b/juick-api/src/main/java/com/juick/api/ApiServer.java index 4305387b..a5bf5d38 100644 --- a/juick-api/src/main/java/com/juick/api/ApiServer.java +++ b/juick-api/src/main/java/com/juick/api/ApiServer.java @@ -16,16 +16,23 @@ */ package com.juick.api; +import com.juick.User; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import rocks.xmpp.addr.Jid; import rocks.xmpp.core.XmppException; import rocks.xmpp.core.session.Extension; import rocks.xmpp.core.session.XmppSessionConfiguration; import rocks.xmpp.core.session.debug.LogbackDebugger; +import rocks.xmpp.core.stanza.model.Message; import rocks.xmpp.extensions.component.accept.ExternalComponent; +import rocks.xmpp.extensions.oob.model.x.OobX; import javax.annotation.PostConstruct; +import java.net.URI; +import java.net.URISyntaxException; /** * @author Ugnich Anton @@ -56,8 +63,8 @@ public class ApiServer implements AutoCloseable { @Override public void close() { try { - if (getXmpp() != null) - getXmpp().close(); + if (xmpp != null) + xmpp.close(); logger.info("ExternalComponent on juick-api destroyed"); } catch (Exception e) { @@ -70,19 +77,33 @@ public class ApiServer implements AutoCloseable { .debugger(LogbackDebugger.class) .extensions(Extension.of(com.juick.Message.class)) .build(); - setXmpp(ExternalComponent.create(jid, password, configuration, host, port)); + xmpp = ExternalComponent.create(jid, password, configuration, host, port); try { - getXmpp().connect(); + xmpp.connect(); } catch (XmppException e) { logger.warn("xmpp extension", e); } } - public ExternalComponent getXmpp() { - return xmpp; + public void sendMessage(Message message) { + if (!isXmppDisabled) { + xmpp.sendMessage(message); + } } - public void setXmpp(ExternalComponent xmpp) { - this.xmpp = xmpp; + public void processMessage(User visitor, String body, String attachmentName) { + Message xmsg = new Message(); + xmsg.setFrom(Jid.of(String.valueOf(visitor.getUid()), "uid.juick.com", "perl")); + xmsg.setTo(Jid.of("juick@juick.com/Juick")); + xmsg.setBody(body); + try { + if (StringUtils.isNotEmpty(attachmentName)) { + String attachmentUrl = String.format("juick://%s", attachmentName); + xmsg.addExtension(new OobX(new URI(attachmentUrl), "!!!!Juick!!")); + } + sendMessage(xmsg); + } catch (URISyntaxException e1) { + logger.warn("attachment error", e1); + } } } diff --git a/juick-api/src/main/java/com/juick/api/TGBot.java b/juick-api/src/main/java/com/juick/api/TelegramBotManager.java index aa912b29..e1910949 100644 --- a/juick-api/src/main/java/com/juick/api/TGBot.java +++ b/juick-api/src/main/java/com/juick/api/TelegramBotManager.java @@ -17,7 +17,6 @@ package com.juick.api; -import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.juick.service.MessagesService; import com.juick.service.TelegramService; @@ -39,7 +38,6 @@ import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.PingMessage; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; -import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.handler.TextWebSocketHandler; import javax.annotation.PostConstruct; @@ -54,8 +52,8 @@ import static com.juick.formatters.PlainTextFormatter.formatUrl; * Created by vt on 12/05/16. */ @Component -public class TGBot extends TextWebSocketHandler { - private static final Logger logger = LoggerFactory.getLogger(TGBot.class); +public class TelegramBotManager extends TextWebSocketHandler { + private static final Logger logger = LoggerFactory.getLogger(TelegramBotManager.class); private TelegramBot bot; @@ -66,8 +64,6 @@ public class TGBot extends TextWebSocketHandler { @Inject private MessagesService messagesService; @Inject - static WebSocketConnectionManager connectionManager; - @Inject private ObjectMapper jsonMapper; private WebSocketSession session; @@ -97,8 +93,7 @@ public class TGBot extends TextWebSocketHandler { @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { - logger.info("WebSocket disconnected with code {}: {}, trying to reconnect", status.getCode(), status.getReason()); - connectionManager.start(); + logger.info("WebSocket disconnected with code {}: {}", status.getCode(), status.getReason()); } @Scheduled(fixedRate = 30000) @@ -179,4 +174,8 @@ public class TGBot extends TextWebSocketHandler { } }); } + + public TelegramBot getBot() { + return bot; + } } diff --git a/juick-api/src/main/java/com/juick/api/configuration/ApiAppConfiguration.java b/juick-api/src/main/java/com/juick/api/configuration/ApiAppConfiguration.java index ad376594..f77611e2 100644 --- a/juick-api/src/main/java/com/juick/api/configuration/ApiAppConfiguration.java +++ b/juick-api/src/main/java/com/juick/api/configuration/ApiAppConfiguration.java @@ -18,7 +18,7 @@ package com.juick.api.configuration; import com.juick.api.ApiServer; -import com.juick.api.TGBot; +import com.juick.api.TelegramBotManager; import com.juick.server.configuration.BaseWebConfiguration; import org.springframework.context.annotation.*; import org.springframework.scheduling.annotation.EnableAsync; @@ -49,13 +49,13 @@ import java.util.Collections; @ComponentScan(basePackages = "com.juick.api") public class ApiAppConfiguration extends BaseWebConfiguration { @Inject - TGBot tgBot; + TelegramBotManager telegramBotManager; private static final String WS_URI = "wss://ws.juick.com/"; @Bean public WebSocketConnectionManager connectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), tgBot, WS_URI); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), telegramBotManager, WS_URI); manager.setAutoStartup(true); return manager; } diff --git a/juick-api/src/main/java/com/juick/api/controllers/PM.java b/juick-api/src/main/java/com/juick/api/controllers/PM.java index e909a4b5..b72e0a0f 100644 --- a/juick-api/src/main/java/com/juick/api/controllers/PM.java +++ b/juick-api/src/main/java/com/juick/api/controllers/PM.java @@ -98,10 +98,10 @@ public class PM { jmsg.setUser(userService.getUserByUID(vuid).get()); jmsg.setText(body); msg.addExtension(jmsg); - apiServer.getXmpp().send(msg); + apiServer.sendMessage(msg); msg.setTo(Jid.of(String.format("%d@ws.juick.com", uid))); - apiServer.getXmpp().send(msg); + apiServer.sendMessage(msg); List<String> jids = userService.getJIDsbyUID(uid); for (String jid : jids) { @@ -115,7 +115,7 @@ public class PM { mm.setFrom(Jid.of("juick", "juick.com", "Juick")); mm.setBody("Private message from @" + jmsg.getUser().getName() + ":\n" + body); } - apiServer.getXmpp().send(mm); + apiServer.sendMessage(mm); } return jmsg; diff --git a/juick-api/src/main/java/com/juick/api/controllers/Post.java b/juick-api/src/main/java/com/juick/api/controllers/Post.java index 5a32ade0..33d83d2c 100644 --- a/juick-api/src/main/java/com/juick/api/controllers/Post.java +++ b/juick-api/src/main/java/com/juick/api/controllers/Post.java @@ -101,22 +101,7 @@ public class Post { throw new HttpBadRequestException(); } } - - if (apiServer.getXmpp() != null) { - Message xmsg = new Message(); - xmsg.setFrom(Jid.of(String.valueOf(visitor.getUid()), "uid.juick.com", "perl")); - xmsg.setTo(Jid.of("juick@juick.com/Juick")); - xmsg.setBody(body); - try { - if (StringUtils.isNotEmpty(attachmentFName)) { - String attachmentUrl = String.format("juick://%s", attachmentFName); - xmsg.addExtension(new OobX(new URI(attachmentUrl), "!!!!Juick!!")); - } - apiServer.getXmpp().sendMessage(xmsg); - } catch (URISyntaxException e1) { - logger.warn("attachment error", e1); - } - } + apiServer.processMessage(visitor, body, attachmentFName); } @RequestMapping(value = "/comment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @@ -175,48 +160,44 @@ public class Post { com.juick.Message jmsg = messagesService.getReply(mid, ridnew); - if (apiServer.getXmpp() != null) { - Message xmsg = new Message(); - xmsg.setFrom(Jid.of("juick@juick.com")); - xmsg.setType(Message.Type.CHAT); - xmsg.setThread("juick-" + mid); - xmsg.addExtension(jmsg); + Message xmsg = new Message(); + xmsg.setFrom(Jid.of("juick@juick.com")); + xmsg.setType(Message.Type.CHAT); + xmsg.setThread("juick-" + mid); + xmsg.addExtension(jmsg); - String quote = reply != null ? reply.getText() : msg.getText(); - if (quote.length() >= 50) { - quote = quote.substring(0, 47) + "..."; - } + String quote = reply != null ? reply.getText() : msg.getText(); + if (quote.length() >= 50) { + quote = quote.substring(0, 47) + "..."; + } - xmsg.addExtension(new Nickname("@" + jmsg.getUser().getName())); + xmsg.addExtension(new Nickname("@" + jmsg.getUser().getName())); - if (StringUtils.isNotEmpty(attachmentFName)) { - String fname = mid + "-" + ridnew + "." + attachmentType; - String attachmentURL = "http://i.juick.com/photos-1024/" + fname; + if (StringUtils.isNotEmpty(attachmentFName)) { + String fname = mid + "-" + ridnew + "." + attachmentType; + String attachmentURL = "http://i.juick.com/photos-1024/" + fname; - ImageUtils.saveImageWithPreviews(attachmentFName, fname, tmpDir, imgDir); + ImageUtils.saveImageWithPreviews(attachmentFName, fname, tmpDir, imgDir); - body = attachmentURL + "\n" + body; - try { - xmsg.addExtension(new OobX(new URI(attachmentURL))); - } catch (URISyntaxException e) { - logger.error("invalid uri: {}, exception {}", attachmentURL, e); - } + body = attachmentURL + "\n" + body; + try { + xmsg.addExtension(new OobX(new URI(attachmentURL))); + } catch (URISyntaxException e) { + logger.error("invalid uri: {}, exception {}", attachmentURL, e); } + } - xmsg.setBody("Reply by @" + jmsg.getUser().getName() + ":\n>" + quote + "\n" + body + "\n\n#" + - mid + "/" + ridnew + " http://juick.com/" + mid + "#" + ridnew); + xmsg.setBody("Reply by @" + jmsg.getUser().getName() + ":\n>" + quote + "\n" + body + "\n\n#" + + mid + "/" + ridnew + " http://juick.com/" + mid + "#" + ridnew); - xmsg.setTo(Jid.of("juick@s2s.juick.com")); - apiServer.getXmpp().send(xmsg); + xmsg.setTo(Jid.of("juick@s2s.juick.com")); + apiServer.sendMessage(xmsg); - xmsg.setTo(Jid.of("juick@ws.juick.com")); - apiServer.getXmpp().send(xmsg); + xmsg.setTo(Jid.of("juick@ws.juick.com")); + apiServer.sendMessage(xmsg); - xmsg.setTo(Jid.of("juick@push.juick.com")); - apiServer.getXmpp().send(xmsg); - } else { - logger.error("XMPP unavailable"); - } + xmsg.setTo(Jid.of("juick@push.juick.com")); + apiServer.sendMessage(xmsg); return jmsg; } @@ -277,7 +258,7 @@ public class Post { String attachmentUrl = String.format("juick://%s", attachmentFName[0]); xmsg.addExtension(new OobX(new URI(attachmentUrl), "!!!!Juick!!")); } - apiServer.getXmpp().sendMessage(xmsg); + apiServer.sendMessage(xmsg); } catch (URISyntaxException e1) { logger.warn("attachment error", e1); } diff --git a/juick-api/src/main/java/com/juick/api/controllers/TelegramWebhook.java b/juick-api/src/main/java/com/juick/api/controllers/TelegramWebhook.java index ae436b22..1141d6d8 100644 --- a/juick-api/src/main/java/com/juick/api/controllers/TelegramWebhook.java +++ b/juick-api/src/main/java/com/juick/api/controllers/TelegramWebhook.java @@ -18,14 +18,21 @@ package com.juick.api.controllers; import com.juick.User; -import com.juick.api.TGBot; +import com.juick.api.ApiServer; +import com.juick.api.TelegramBotManager; +import com.juick.server.util.HttpUtils; import com.juick.service.TelegramService; import com.juick.service.UserService; import com.pengrad.telegrambot.BotUtils; import com.pengrad.telegrambot.model.Message; +import com.pengrad.telegrambot.model.PhotoSize; import com.pengrad.telegrambot.model.Update; +import com.pengrad.telegrambot.request.GetFile; +import com.pengrad.telegrambot.response.GetFileResponse; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -37,7 +44,10 @@ import javax.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.net.URL; import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Comparator; import java.util.List; /** @@ -52,12 +62,16 @@ public class TelegramWebhook { @Inject private TelegramService telegramService; @Inject - private TGBot tgBot; + private TelegramBotManager telegramBotManager; + @Inject + private ApiServer apiServer; + @Value("${upload_tmp_dir:/var/www/juick.com/i/tmp/}") + private String tmpDir; @RequestMapping(value = "/tlgmbtwbhk", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) - public void processUpdate(InputStream body) throws IOException { + public void processUpdate(InputStream body) throws Exception { Update update = BotUtils.parseUpdate(new InputStreamReader(body, StandardCharsets.UTF_8)); Message message = update.message(); if (update.message() == null) { @@ -67,6 +81,7 @@ public class TelegramWebhook { return; } } + logger.info("got telegram msg {}", message); User user_from = usersService.getUserByUID(telegramService.getUser(message.chat().id())).orElse(new User()); logger.info("Found juick user {}", user_from.getUid()); @@ -80,21 +95,36 @@ public class TelegramWebhook { telegramService.addChat(message.chat().id()); logger.info("added chat with {}", username); telegramService.createTelegramUser(message.from().id(), username); - tgBot.telegramSignupNotify(message.from().id().longValue(), usersService.getSignUpHashByTelegramID(message.from().id().longValue(), username)); + telegramBotManager.telegramSignupNotify(message.from().id().longValue(), usersService.getSignUpHashByTelegramID(message.from().id().longValue(), username)); } else { if (user_from.getUid() == 0) { - tgBot.telegramSignupNotify(message.from().id().longValue(), usersService.getSignUpHashByTelegramID(message.from().id().longValue(), username)); + telegramBotManager.telegramSignupNotify(message.from().id().longValue(), usersService.getSignUpHashByTelegramID(message.from().id().longValue(), username)); } else { + String attachment = 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 = telegramBotManager.getBot().execute(request); + logger.info("got file {}", response.file()); + URL fileURL = new URL(telegramBotManager.getBot().getFullFilePath(response.file())); + attachment = HttpUtils.downloadImage(fileURL, tmpDir); + logger.info("received {}", attachment); + } + } String text = message.text(); - if (text != null) { + if (StringUtils.isBlank(text)) { + text = message.caption(); + } + if (StringUtils.isNotEmpty(text)) { if (text.equalsIgnoreCase("/login")) { String msg = String.format("Hi, %s!\nTap to log in", user_from.getName()); String msgUrl = "http://juick.com/login?" + usersService.getHashByUID(user_from.getUid()); - tgBot.telegramNotify(message.from().id().longValue(), msg, msgUrl); - } /* else { - ProtocolReply reply = protocol.getReply(user_from, text); - telegramNotify(message.from().id().longValue(), reply.getResult(), null); - }*/ + telegramBotManager.telegramNotify(message.from().id().longValue(), msg, msgUrl); + } else if (text.toLowerCase().startsWith("/post ")) { + apiServer.processMessage(user_from, text.substring(6), attachment); + } } } } |