aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/jabber/ws/XMPPConnection.java
blob: 8c187a36d35e59a395df8a9fa1aefe92adf18786 (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
package com.juick.jabber.ws;

import com.juick.User;
import com.juick.json.MessageSerializer;
import com.juick.server.MessagesQueries;
import com.juick.server.SubscriptionsQueries;
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.springframework.jdbc.core.JdbcTemplate;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

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

    JdbcTemplate sql;
    Stream xmpp;
    String xmppPassword;
    MessageSerializer ms;

    public XMPPConnection(JdbcTemplate sql, String password) {
        this.sql = sql;
        xmppPassword = password;
        ms = new MessageSerializer();
    }

    @Override
    public void run() {
        try {
            Socket socket = new Socket("localhost", 5347);
            xmpp = new StreamComponent(new JID("", "ws.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), xmppPassword);
            xmpp.addChildParser(new JuickMessage());
            xmpp.addListener((Stream.StreamListener) this);
            xmpp.addListener((Message.MessageListener) this);
            xmpp.startParsing();
        } catch (IOException e) {
            logger.log(Level.SEVERE, "XMPPConnection error", e);
        }
    }

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

    @Override
    public void onStreamFail(String msg) {
        logger.severe("XMPP stream failed: " + msg);
    }

    @Override
    public void onMessage(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 {
                onJuickMessageReply(jmsg);
            }
        }
    }

    MessageSerializer messageSerializer = new MessageSerializer();

    private void onJuickPM(int uid_to, com.juick.Message jmsg) {
        String json = messageSerializer.serialize(jmsg).toString();
        ByteBuffer bbMsg = buildTextFrame(json);

        synchronized (Main.clients) {
            for (Iterator<SocketSubscribed> i = Main.clients.iterator(); i.hasNext();) {
                SocketSubscribed s = i.next();
                if (s.VUID == uid_to && s.MID == 0 && s.allMessages == false && s.allReplies == false) {
                    if (!s.sendByteBuffer(bbMsg)) {
                        i.remove();
                    }
                }
            }
        }
    }

    private void onJuickMessagePost(com.juick.Message jmsg) {
        String json = messageSerializer.serialize(jmsg).toString();
        ByteBuffer bbMsg = buildTextFrame(json);

        List<Integer> uids = SubscriptionsQueries.getSubscribedUsers(sql, jmsg.getUser().getUID(), jmsg.getMID())
                .stream().map(User::getUID).collect(Collectors.toList());

        synchronized (Main.clients) {
            for (Iterator<SocketSubscribed> i = Main.clients.iterator(); i.hasNext();) {
                SocketSubscribed s = i.next();
                if (s.MID == 0 && s.allReplies == false && ((jmsg.Privacy >= 0
                        && (s.allMessages || s.UID == jmsg.getUser().getUID())) || uids.contains(s.VUID))) {
                    if (!s.sendByteBuffer(bbMsg)) {
                        i.remove();
                    }
                }
            }
        }
    }

    private void onJuickMessageReply(com.juick.Message jmsg) {
        String json = messageSerializer.serialize(jmsg).toString();
        ByteBuffer bbMsg = buildTextFrame(json);

        int privacy = MessagesQueries.getMessagePrivacy(sql, jmsg.getMID());

        synchronized (Main.clients) {
            for (Iterator<SocketSubscribed> i = Main.clients.iterator(); i.hasNext();) {
                SocketSubscribed s = i.next();
                if ((privacy >= 0 && s.allReplies) || s.MID == jmsg.getMID()) {
                    if (!s.sendByteBuffer(bbMsg)) {
                        i.remove();
                    }
                }
            }
        }
    }

    private ByteBuffer buildTextFrame(String json) {
        ByteBuffer jsonbytes = Charset.forName("UTF-8").encode(json);
        ByteBuffer bbMsg = ByteBuffer.allocate(jsonbytes.limit() + 8);
        bbMsg.put((byte) 0x81);
        if (jsonbytes.limit() <= 125) {
            bbMsg.put((byte) jsonbytes.limit());
        } else {
            bbMsg.put((byte) 126);
            bbMsg.putShort((short) jsonbytes.limit());
        }
        bbMsg.put(jsonbytes);
        bbMsg.flip();
        return bbMsg;
    }
}