aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/api/TelegramBotHook.java
blob: 907898f230eb5055bd5c81e18ed96b7f107c6338 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package com.juick.api;

import com.juick.User;
import com.juick.json.MessageSerializer;
import com.juick.server.UserQueries;
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.model.request.InlineKeyboardButton;
import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import org.json.JSONObject;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
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<String, List<String>> 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());
                    }
                    String msg = sb.toString();
                    List<Long> users = getSubscribers(jmsg.getUser().getUID());
                    List<Long> chats = getChats();
                    // registered subscribed users
                    users.stream().forEach(c -> telegramNotify(c, msg, jmsg.getMID()));
                    // anonymous
                    chats.stream().filter(u -> !getUser(u).isPresent()).forEach(c -> telegramNotify(c, msg, jmsg.getMID()));
                }
            });
            ws.connect();
        } catch (IOException | WebSocketException e) {
            logger.log(Level.SEVERE, "couldn't create ws connection", e);
        }
    }

    private void telegramNotify(Long c, String msg, int mid) {
        bot.execute(new SendMessage(c, msg).replyMarkup(
                new InlineKeyboardMarkup(
                        new InlineKeyboardButton[] {
                                new InlineKeyboardButton("See on Juick").url("https://juick.com/" + mid)
                        }
                )), new Callback<SendMessage, SendResponse>() {
            @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);
            }
        });
    }

    List<Long> getChats() {
        return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class);
    }
    void addChat(Long id) {
        jdbc.update("INSERT IGNORE INTO 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<Long> chats = getChats();
            if (!chats.contains(message.chat().id())) {
                addChat(message.chat().id());
                logger.info("added chat with " + message.from().firstName());
                createTelegramUser(message.from().id(), message.from().username());
                bot.execute(new SendMessage(message.chat().id(),
                        "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("LOGIN").url("http://juick.com/signup?type=durov&hash=" +
                                                UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue()))
                                })), new Callback<SendMessage, SendResponse>() {
                    @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);
                    }
                });
            }
        }
    }
    private boolean createTelegramUser(long tgID, String tgName) {
        return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)",
                tgID, tgName, UUID.randomUUID().toString()) > 0;
    }
    private Optional<User> getUser(long tgId) {
        try {
            return Optional.of(jdbc.queryForObject("SELECT id, name, banned FROM users INNER JOIN telegram" +
                    "ON telegram.user_id = users.id WHERE telegram.tg_id=?", new UserQueries.UserMapper(), tgId));
        } catch (EmptyResultDataAccessException e) {
            return Optional.empty();
        }
    }
    private List<Long> getSubscribers(int uid) {
        return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " +
                "ON (subscr_users.user_id=? AND telegram.tg_id=subscr_users.suser_id)", Long.class, uid, uid);
    }
}