From 751b2a9b0fc523d17c9f7a410fadcc82eaaa1fb7 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Wed, 27 Sep 2017 15:19:06 +0300
Subject: api: Telegram posting
---
.../src/main/java/com/juick/api/ApiServer.java | 37 ++++-
juick-api/src/main/java/com/juick/api/TGBot.java | 182 ---------------------
.../java/com/juick/api/TelegramBotManager.java | 181 ++++++++++++++++++++
.../api/configuration/ApiAppConfiguration.java | 6 +-
.../main/java/com/juick/api/controllers/PM.java | 6 +-
.../main/java/com/juick/api/controllers/Post.java | 79 ++++-----
.../com/juick/api/controllers/TelegramWebhook.java | 52 ++++--
7 files changed, 287 insertions(+), 256 deletions(-)
delete mode 100644 juick-api/src/main/java/com/juick/api/TGBot.java
create mode 100644 juick-api/src/main/java/com/juick/api/TelegramBotManager.java
(limited to 'juick-api/src/main/java')
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/TGBot.java
deleted file mode 100644
index aa912b29..00000000
--- a/juick-api/src/main/java/com/juick/api/TGBot.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2008-2017, Juick
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see .
- */
-
-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;
-import com.pengrad.telegrambot.Callback;
-import com.pengrad.telegrambot.TelegramBot;
-import com.pengrad.telegrambot.TelegramBotAdapter;
-import com.pengrad.telegrambot.model.request.InlineKeyboardButton;
-import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
-import com.pengrad.telegrambot.request.SendMessage;
-import com.pengrad.telegrambot.request.SetWebhook;
-import com.pengrad.telegrambot.response.SendResponse;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Component;
-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;
-import javax.inject.Inject;
-import java.io.IOException;
-import java.util.List;
-
-import static com.juick.formatters.PlainTextFormatter.formatPost;
-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);
-
- private TelegramBot bot;
-
- @Value("${telegram_token}")
- private String telegramToken;
- @Inject
- private TelegramService telegramService;
- @Inject
- private MessagesService messagesService;
- @Inject
- static WebSocketConnectionManager connectionManager;
- @Inject
- private ObjectMapper jsonMapper;
-
- private WebSocketSession session;
-
- @PostConstruct
- public void init() {
- if (StringUtils.isBlank(telegramToken)) {
- logger.info("telegram token is not set, exiting");
- return;
- }
- bot = TelegramBotAdapter.build(telegramToken);
- try {
- SetWebhook webhook = new SetWebhook().url("https://api.juick.com/tlgmbtwbhk");
- if (!bot.execute(webhook).isOk()) {
- logger.error("error setting webhook");
- }
- } catch (Exception e) {
- logger.warn("couldn't initialize telegram bot", e);
- }
- }
-
- @Override
- public void afterConnectionEstablished(WebSocketSession session) throws Exception {
- logger.info("WebSocket connected");
- this.session = session;
- }
-
- @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();
- }
-
- @Scheduled(fixedRate = 30000)
- public void ping() throws IOException {
- if (session != null) {
- logger.debug("Sending WebSocket ping");
- session.sendMessage(new PingMessage());
- }
- }
-
- @Override
- protected void handleTextMessage(WebSocketSession session, TextMessage text) throws Exception {
- com.juick.Message jmsg = jsonMapper.readValue(text.asBytes(), com.juick.Message.class);
-
- if (logger.isInfoEnabled()) // prevent writeValueAsString execution if logger disabled
- logger.info("got jmsg: {}", jsonMapper.writeValueAsString(jmsg));
-
- String msgUrl = formatUrl(jmsg);
- if (jmsg.getRid() == 0) {
- String msg = formatPost(jmsg);
-
- List users = telegramService.getSubscribers(jmsg.getUser().getUid());
- List chats = telegramService.getChats();
- // registered subscribed users
-
- users.forEach(c -> telegramNotify(c, msg, msgUrl));
- // anonymous
- chats.stream().filter(u -> telegramService.getUser(u) == 0).forEach(c -> telegramNotify(c, msg, msgUrl));
- } else {
- // get quote
- com.juick.Message msg = messagesService.getReply(jmsg.getMid(), jmsg.getRid());
- String fmsg = formatPost(msg);
- telegramService.getSubscribersToComments(jmsg.getMid(), jmsg.getUser().getUid()).forEach(c -> telegramNotify(c, fmsg, msgUrl));
- }
- }
-
- public void telegramNotify(Long c, String msg, String msgUrl) {
- SendMessage telegramMessage = new SendMessage(c, msg);
- if (msgUrl != null) {
- telegramMessage.replyMarkup(
- new InlineKeyboardMarkup(
- new InlineKeyboardButton[]{
- new InlineKeyboardButton("See on Juick").url(msgUrl)
- }
- ));
- }
- bot.execute(telegramMessage, new Callback() {
- @Override
- public void onResponse(SendMessage request, SendResponse response) {
- logger.info("got response: {}", response.message());
- }
-
- @Override
- public void onFailure(SendMessage request, IOException e) {
- logger.warn("telegram failure", e);
- }
- });
- }
-
- public void telegramSignupNotify(Long telegramId, String hash) {
- bot.execute(new SendMessage(telegramId,
- "You are subscribed to all Juick messages. " +
- "Create or link an existing Juick account to control " +
- "what do you want to receive").replyMarkup(
- new InlineKeyboardMarkup(
- new InlineKeyboardButton[]{
- new InlineKeyboardButton("SIGNUP").url("http://juick.com/signup?type=durov&hash=" +
- hash)
- })), new Callback() {
- @Override
- public void onResponse(SendMessage request, SendResponse response) {
- logger.info("got response: {}", response.message());
- }
-
- @Override
- public void onFailure(SendMessage request, IOException e) {
- logger.warn("telegram failure", e);
- }
- });
- }
-}
diff --git a/juick-api/src/main/java/com/juick/api/TelegramBotManager.java b/juick-api/src/main/java/com/juick/api/TelegramBotManager.java
new file mode 100644
index 00000000..e1910949
--- /dev/null
+++ b/juick-api/src/main/java/com/juick/api/TelegramBotManager.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2008-2017, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.api;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.juick.service.MessagesService;
+import com.juick.service.TelegramService;
+import com.pengrad.telegrambot.Callback;
+import com.pengrad.telegrambot.TelegramBot;
+import com.pengrad.telegrambot.TelegramBotAdapter;
+import com.pengrad.telegrambot.model.request.InlineKeyboardButton;
+import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
+import com.pengrad.telegrambot.request.SendMessage;
+import com.pengrad.telegrambot.request.SetWebhook;
+import com.pengrad.telegrambot.response.SendResponse;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+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.handler.TextWebSocketHandler;
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import java.io.IOException;
+import java.util.List;
+
+import static com.juick.formatters.PlainTextFormatter.formatPost;
+import static com.juick.formatters.PlainTextFormatter.formatUrl;
+
+/**
+ * Created by vt on 12/05/16.
+ */
+@Component
+public class TelegramBotManager extends TextWebSocketHandler {
+ private static final Logger logger = LoggerFactory.getLogger(TelegramBotManager.class);
+
+ private TelegramBot bot;
+
+ @Value("${telegram_token}")
+ private String telegramToken;
+ @Inject
+ private TelegramService telegramService;
+ @Inject
+ private MessagesService messagesService;
+ @Inject
+ private ObjectMapper jsonMapper;
+
+ private WebSocketSession session;
+
+ @PostConstruct
+ public void init() {
+ if (StringUtils.isBlank(telegramToken)) {
+ logger.info("telegram token is not set, exiting");
+ return;
+ }
+ bot = TelegramBotAdapter.build(telegramToken);
+ try {
+ SetWebhook webhook = new SetWebhook().url("https://api.juick.com/tlgmbtwbhk");
+ if (!bot.execute(webhook).isOk()) {
+ logger.error("error setting webhook");
+ }
+ } catch (Exception e) {
+ logger.warn("couldn't initialize telegram bot", e);
+ }
+ }
+
+ @Override
+ public void afterConnectionEstablished(WebSocketSession session) throws Exception {
+ logger.info("WebSocket connected");
+ this.session = session;
+ }
+
+ @Override
+ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
+ logger.info("WebSocket disconnected with code {}: {}", status.getCode(), status.getReason());
+ }
+
+ @Scheduled(fixedRate = 30000)
+ public void ping() throws IOException {
+ if (session != null) {
+ logger.debug("Sending WebSocket ping");
+ session.sendMessage(new PingMessage());
+ }
+ }
+
+ @Override
+ protected void handleTextMessage(WebSocketSession session, TextMessage text) throws Exception {
+ com.juick.Message jmsg = jsonMapper.readValue(text.asBytes(), com.juick.Message.class);
+
+ if (logger.isInfoEnabled()) // prevent writeValueAsString execution if logger disabled
+ logger.info("got jmsg: {}", jsonMapper.writeValueAsString(jmsg));
+
+ String msgUrl = formatUrl(jmsg);
+ if (jmsg.getRid() == 0) {
+ String msg = formatPost(jmsg);
+
+ List users = telegramService.getSubscribers(jmsg.getUser().getUid());
+ List chats = telegramService.getChats();
+ // registered subscribed users
+
+ users.forEach(c -> telegramNotify(c, msg, msgUrl));
+ // anonymous
+ chats.stream().filter(u -> telegramService.getUser(u) == 0).forEach(c -> telegramNotify(c, msg, msgUrl));
+ } else {
+ // get quote
+ com.juick.Message msg = messagesService.getReply(jmsg.getMid(), jmsg.getRid());
+ String fmsg = formatPost(msg);
+ telegramService.getSubscribersToComments(jmsg.getMid(), jmsg.getUser().getUid()).forEach(c -> telegramNotify(c, fmsg, msgUrl));
+ }
+ }
+
+ public void telegramNotify(Long c, String msg, String msgUrl) {
+ SendMessage telegramMessage = new SendMessage(c, msg);
+ if (msgUrl != null) {
+ telegramMessage.replyMarkup(
+ new InlineKeyboardMarkup(
+ new InlineKeyboardButton[]{
+ new InlineKeyboardButton("See on Juick").url(msgUrl)
+ }
+ ));
+ }
+ bot.execute(telegramMessage, new Callback() {
+ @Override
+ public void onResponse(SendMessage request, SendResponse response) {
+ logger.info("got response: {}", response.message());
+ }
+
+ @Override
+ public void onFailure(SendMessage request, IOException e) {
+ logger.warn("telegram failure", e);
+ }
+ });
+ }
+
+ public void telegramSignupNotify(Long telegramId, String hash) {
+ bot.execute(new SendMessage(telegramId,
+ "You are subscribed to all Juick messages. " +
+ "Create or link an existing Juick account to control " +
+ "what do you want to receive").replyMarkup(
+ new InlineKeyboardMarkup(
+ new InlineKeyboardButton[]{
+ new InlineKeyboardButton("SIGNUP").url("http://juick.com/signup?type=durov&hash=" +
+ hash)
+ })), new Callback() {
+ @Override
+ public void onResponse(SendMessage request, SendResponse response) {
+ logger.info("got response: {}", response.message());
+ }
+
+ @Override
+ public void onFailure(SendMessage request, IOException e) {
+ logger.warn("telegram failure", e);
+ }
+ });
+ }
+
+ 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 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);
+ }
}
}
}
--
cgit v1.2.3