aboutsummaryrefslogtreecommitdiff
path: root/juick-ws/src/main/java/com/juick/ws/XMPPConnection.java
blob: 04ea53781ce8f70e17a5b745534ddfef3f43274e (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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package com.juick.ws;

import com.juick.User;
import com.juick.json.MessageSerializer;
import com.juick.server.MessagesQueries;
import com.juick.server.SubscriptionsQueries;
import com.juick.util.ThreadHelper;
import com.juick.xmpp.JID;
import com.juick.xmpp.Message;
import com.juick.xmpp.Stream;
import com.juick.xmpp.StreamComponent;
import com.juick.xmpp.extensions.JuickMessage;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * @author ugnich
 */
public class XMPPConnection implements InitializingBean, DisposableBean, Stream.StreamListener, Message.MessageListener {
    private static final Logger logger = LoggerFactory.getLogger(XMPPConnection.class);

    private final JdbcTemplate jdbc;
    private final ExecutorService service;
    private final WebsocketComponent wsHandler;
    private final String xmppPassword;
    private final MessageSerializer ms;
    private final int xmppPort;
    private final String wsJid;

    private Stream xmpp;


    public XMPPConnection(
            final Environment env, final ExecutorService service, final WebsocketComponent wsHandler, final JdbcTemplate jdbc) {
        Assert.notNull(env);
        Assert.notNull(service);
        Assert.notNull(wsHandler);
        Assert.notNull(jdbc);

        this.service = service;
        this.wsHandler = wsHandler;
        this.jdbc = jdbc;

        xmppPassword = env.getProperty("xmpp_password");
        xmppPort = NumberUtils.toInt(env.getProperty("xmpp_port"), 5347);
        wsJid = env.getProperty("ws_jid", "ws.juick.local");

        ms = new MessageSerializer();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            Socket socket = new Socket("localhost", xmppPort);
            xmpp = new StreamComponent(new JID(wsJid), socket.getInputStream(), socket.getOutputStream(), xmppPassword);
            xmpp.addChildParser(new JuickMessage());
            xmpp.addListener((Stream.StreamListener) this);
            xmpp.addListener((Message.MessageListener) this);

            service.submit(() -> xmpp.startParsing());

            logger.info("XMPPConnection initialized");
        } catch (IOException e) {
            logger.error("XMPPConnection initialization error", e);
        }
    }

    @Override
    public void destroy() throws Exception {
        ThreadHelper.shutdownAndAwaitTermination(service);

        logger.info("XMPPConnection destroyed");
    }

    @Override
    public void onStreamReady() {
        logger.info("XMPP stream ready");
    }

    @Override
    public void onStreamFail(final Exception ex) {
        logger.error("XMPP stream failed", ex);
    }

    @Override
    public void onMessage(final com.juick.xmpp.Message msg) {
        JuickMessage jmsg = (JuickMessage) msg.getChild(JuickMessage.XMLNS);
        if (jmsg != null) {
            logger.info("got jmsg: " + ms.serialize(jmsg).toString());
            if (jmsg.getMID() == 0) {
                int uid_to = 0;
                try {
                    uid_to = Integer.parseInt(msg.to.Username);
                } catch (Exception e) {
                }
                if (uid_to > 0) {
                    onJuickPM(uid_to, jmsg);
                }
            } else if (jmsg.getRID() == 0) {
                onJuickMessagePost(jmsg);
            } else {
                // to get quote
                com.juick.Message reply = MessagesQueries.getReply(jdbc, jmsg.getMID(), jmsg.getRID());
                onJuickMessageReply(reply);
            }
        }
    }

    MessageSerializer messageSerializer = new MessageSerializer();

    private void onJuickPM(final int uid_to, final com.juick.Message jmsg) {
        String json = messageSerializer.serialize(jmsg).toString();
        synchronized (wsHandler.getClients()) {
            wsHandler.getClients().stream().filter(c -> !c.legacy && c.visitor.getUID() == uid_to).forEach(c -> {
                try {
                    logger.info("sending pm to " + c.visitor.getUID());
                    c.session.sendMessage(new TextMessage(json));
                } catch (IOException e) {
                    logger.warn("ws error", e);
                }
            });
        }
    }

    private void onJuickMessagePost(final com.juick.Message jmsg) {
        String json = messageSerializer.serialize(jmsg).toString();
        List<Integer> uids = SubscriptionsQueries.getSubscribedUsers(jdbc, jmsg.getUser().getUID(), jmsg.getMID())
                .stream().map(User::getUID).collect(Collectors.toList());
        synchronized (wsHandler.getClients()) {
            wsHandler.getClients().stream().filter(c ->
                    (!c.legacy && c.visitor.getUID() == 0) // anonymous users
                            || (!c.legacy && uids.contains(c.visitor.getUID()))) // subscriptions
                    .forEach(c -> {
                        try {
                            logger.info("sending message to " + c.visitor.getUID());
                            c.session.sendMessage(new TextMessage(json));
                        } catch (IOException e) {
                            logger.warn("ws error", e);
                        }
                    });
            wsHandler.getClients().stream().filter(c ->
                    c.legacy && c.allMessages) // legacy all posts
                    .forEach(c -> {
                        try {
                            logger.info("sending message to legacy client " + c.visitor.getUID());
                            c.session.sendMessage(new TextMessage(json));
                        } catch (IOException e) {
                            logger.warn("ws error", e);
                        }
                    });
        }
    }

    private void onJuickMessageReply(final com.juick.Message jmsg) {
        String json = messageSerializer.serialize(jmsg).toString();
        List<Integer> threadUsers =
                SubscriptionsQueries.getUsersSubscribedToComments(jdbc, jmsg.getMID(), jmsg.getUser().getUID())
                        .stream().map(User::getUID).collect(Collectors.toList());
        synchronized (wsHandler.getClients()) {
            wsHandler.getClients().stream().filter(c ->
                    (!c.legacy && c.visitor.getUID() == 0) // anonymous users
                            || (!c.legacy && threadUsers.contains(c.visitor.getUID()))) // subscriptions
                    .forEach(c -> {
                        try {
                            logger.info("sending reply to " + c.visitor.getUID());
                            c.session.sendMessage(new TextMessage(json));
                        } catch (IOException e) {
                            logger.warn("ws error", e);
                        }
                    });
            wsHandler.getClients().stream().filter(c ->
                    (c.legacy && c.allReplies) || (c.legacy && c.MID == jmsg.getMID())) // legacy replies
                    .forEach(c -> {
                        try {
                            logger.info("sending reply to legacy client " + c.visitor.getUID());
                            c.session.sendMessage(new TextMessage(json));
                        } catch (IOException e) {
                            logger.warn("ws error", e);
                        }
                    });
        }
    }
}