package com.juick.api; import com.juick.json.MessageSerializer; import com.neovisionaries.ws.client.*; import com.pengrad.telegrambot.BotUtils; import com.pengrad.telegrambot.Callback; import com.pengrad.telegrambot.TelegramBot; import com.pengrad.telegrambot.TelegramBotAdapter; import com.pengrad.telegrambot.model.Message; import com.pengrad.telegrambot.request.SendMessage; import com.pengrad.telegrambot.response.SendResponse; import org.json.JSONObject; import org.springframework.jdbc.core.JdbcTemplate; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by vt on 12/05/16. */ public class TelegramBotHook { private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName()); TelegramBot bot; WebSocket ws; MessageSerializer ms = new MessageSerializer(); JdbcTemplate jdbc; public TelegramBotHook(JdbcTemplate jdbc, String token) { this.jdbc = jdbc; bot = TelegramBotAdapter.build(token); bot.setWebhook("https://api.juick.com/tlgmbtwbhk"); try { ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all"); ws.addHeader("Origin", "ws.juick.com"); ws.addHeader("Host", "ws.juick.com"); //TODO: remove from server ws.setPingInterval(60 * 1000); ws.addListener(new WebSocketAdapter() { @Override public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception { logger.info("ws disconnected"); } @Override public void onConnected(WebSocket websocket, Map> headers) { logger.info("ws connected"); } @Override public void onTextMessage(WebSocket websocket, String text) throws Exception { super.onTextMessage(websocket, text); com.juick.Message jmsg = ms.deserialize(new JSONObject(text)); logger.info("got jmsg: " + ms.serialize(jmsg).toString()); StringBuilder sb = new StringBuilder(); sb.append("@").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n"); if (jmsg.getAttachmentURL() != null) { sb.append(jmsg.getAttachmentURL()); } sb.append("https://juick.com/").append(jmsg.getMID()); String msg = sb.toString(); List chats = getChats(); chats.stream().forEach(c -> { bot.execute(new SendMessage(c, msg), new Callback() { @Override public void onResponse(SendMessage request, SendResponse response) { logger.info("got response: " + response.message().toString()); } @Override public void onFailure(SendMessage request, IOException e) { logger.log(Level.WARNING, "telegram failure", e); } }); }); } }); ws.connect(); } catch (IOException | WebSocketException e) { logger.log(Level.SEVERE, "couldn't create ws connection", e); } } List getChats() { return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class); } void addChat(Long id) { jdbc.update("INSERT IGNORE TO telegram_chats(chat_id) VALUES(?)", id); } public void doPost(HttpServletRequest request) throws IOException { try (BufferedReader reader = request.getReader()) { Message message = BotUtils.parseUpdate(reader).message(); logger.info("got telegram msg: " + message.toString()); List chats = getChats(); if (!chats.contains(message.chat().id())) { addChat(message.chat().id()); logger.info("added chat with " + message.from().firstName()); bot.execute(new SendMessage(message.chat().id(), "Subscribed!"), new Callback() { @Override public void onResponse(SendMessage request, SendResponse response) { logger.info("got response: " + response.message().toString()); } @Override public void onFailure(SendMessage request, IOException e) { logger.log(Level.WARNING, "telegram failure", e); } }); } } } }