aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/irc/MonitorPresenceWatcher.java
blob: be33967f84c8dd50d600a3f19b1025acfb777636 (plain)
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.protocol.irc;

import java.util.*;

import net.java.sip.communicator.util.*;

import com.ircclouds.irc.api.*;
import com.ircclouds.irc.api.domain.messages.*;
import com.ircclouds.irc.api.state.*;

/**
 * MONITOR presence watcher.
 *
 * @author Danny van Heumen
 */
class MonitorPresenceWatcher
    implements PresenceWatcher
{
    /**
     * Static overhead in message payload required for 'MONITOR +' command.
     */
    private static final int MONITOR_ADD_CMD_STATIC_OVERHEAD = 10;

    /**
     * Logger.
     */
    private static final Logger LOGGER = Logger
        .getLogger(MonitorPresenceWatcher.class);

    /**
     * IRCApi instance.
     */
    private final IRCApi irc;

    /**
     * IRC connection state.
     */
    private final IIRCState connectionState;

    /**
     * Complete nick watch list.
     */
    private final Set<String> nickWatchList;

    /**
     * List of monitored nicks.
     *
     * The instance is stored here only for access in order to remove a nick
     * from the list, since 'MONITOR - ' command does not reply so we cannot
     * manage list removals from the reply listener.
     */
    private final Set<String> monitoredList;

    /**
     * Constructor.
     *
     * @param irc the IRCApi instance
     * @param connectionState the connection state
     * @param nickWatchList SYNCHRONIZED the nick watch list
     * @param monitored SYNCHRONIZED The shared collection which contains all
     *            the nicks that are confirmed to be subscribed to the MONITOR
     *            command.
     * @param operationSet the persistent presence operation set
     */
    MonitorPresenceWatcher(final IRCApi irc, final IIRCState connectionState,
        final Set<String> nickWatchList, final Set<String> monitored,
        final OperationSetPersistentPresenceIrcImpl operationSet,
        final int maxListSize)
    {
        if (irc == null)
        {
            throw new IllegalArgumentException("irc cannot be null");
        }
        this.irc = irc;
        if (connectionState == null)
        {
            throw new IllegalArgumentException(
                "connectionState cannot be null");
        }
        this.connectionState = connectionState;
        if (nickWatchList == null)
        {
            throw new IllegalArgumentException("nickWatchList cannot be null");
        }
        this.nickWatchList = nickWatchList;
        if (monitored == null)
        {
            throw new IllegalArgumentException("monitored cannot be null");
        }
        this.monitoredList = monitored;
        this.irc.addListener(new MonitorReplyListener(this.monitoredList, operationSet));
        setUpMonitor(this.irc, this.nickWatchList, maxListSize);
        LOGGER.debug("MONITOR presence watcher initialized.");
    }

    /**
     * Set up monitor based on the nick watch list in its current state.
     *
     * Created a static method as not to interfere too much with a state that is
     * still being initialized.
     */
    private static void setUpMonitor(final IRCApi irc,
        final Collection<String> nickWatchList, final int maxListSize)
    {
        List<String> current;
        synchronized (nickWatchList)
        {
            current = new LinkedList<String>(nickWatchList);
        }
        if (current.size() > maxListSize)
        {
            // cut off list to maximum number of entries allowed by server
            current = current.subList(0, maxListSize);
        }
        final int maxLength = 510 - MONITOR_ADD_CMD_STATIC_OVERHEAD;
        final StringBuilder query = new StringBuilder();
        for (String nick : current)
        {
            if (query.length() + nick.length() + 1 > maxLength)
            {
                // full payload, send monitor query now
                irc.rawMessage("MONITOR + " + query);
                query.delete(0, query.length());
            }
            else if (query.length() > 0)
            {
                query.append(",");
            }
            query.append(nick);
        }
        if (query.length() > 0)
        {
            // send query for remaining nicks
            irc.rawMessage("MONITOR + " + query);
        }
    }

    @Override
    public void add(final String nick)
    {
        LOGGER.trace("Adding nick '" + nick + "' to MONITOR watch list.");
        this.nickWatchList.add(nick);
        this.irc.rawMessage("MONITOR + " + nick);
    }

    @Override
    public void remove(final String nick)
    {
        LOGGER.trace("Removing nick '" + nick + "' from MONITOR watch list.");
        this.nickWatchList.remove(nick);
        this.irc.rawMessage("MONITOR - " + nick);
        // 'MONITOR - nick' command does not send confirmation, so immediately
        // remove nick from monitored list.
        this.monitoredList.remove(nick);
    }

    /**
     * Listener for MONITOR replies.
     *
     * @author Danny van Heumen
     */
    private final class MonitorReplyListener
        extends AbstractIrcMessageListener
    {
        /**
         * Numeric message id for ONLINE nick response.
         */
        private static final int IRC_RPL_MONONLINE = 730;

        /**
         * Numeric message id for OFFLINE nick response.
         */
        private static final int IRC_RPL_MONOFFLINE = 731;

        // /**
        // * Numeric message id for MONLIST entry.
        // */
        // private static final int IRC_RPL_MONLIST = 732;
        //
        // /**
        // * Numeric message id for ENDOFMONLIST.
        // */
        // private static final int IRC_RPL_ENDOFMONLIST = 733;

        /**
         * Error message signaling full list. Nick list provided are all nicks
         * that failed to be added to the monitor list.
         */
        private static final int IRC_ERR_MONLISTFULL = 734;

        /**
         * Operation set persistent presence instance.
         */
        private final OperationSetPersistentPresenceIrcImpl operationSet;

        /**
         * Set of nicks that are confirmed to be monitored by the server.
         */
        private final Set<String> monitoredNickList;

        // TODO Update to act on onClientError once available.

        /**
         * Constructor.
         *
         * @param monitored SYNCHRONIZED Collection of monitored nicks. This
         *            collection will be updated with all nicks that are
         *            confirmed to be subscribed by the MONITOR command.
         * @param operationSet the persistent presence opset used to update nick
         *            presence statuses.
         */
        public MonitorReplyListener(final Set<String> monitored,
            final OperationSetPersistentPresenceIrcImpl operationSet)
        {
            super(MonitorPresenceWatcher.this.irc,
                MonitorPresenceWatcher.this.connectionState);
            if (operationSet == null)
            {
                throw new IllegalArgumentException(
                    "operationSet cannot be null");
            }
            this.operationSet = operationSet;
            if (monitored == null)
            {
                throw new IllegalArgumentException("monitored cannot be null");
            }
            this.monitoredNickList = monitored;
        }

        /**
         * Numeric messages received in response to MONITOR commands or presence
         * updates.
         */
        @Override
        public void onServerNumericMessage(final ServerNumericMessage msg)
        {
            final List<String> acknowledged;
            switch (msg.getNumericCode())
            {
            case IRC_RPL_MONONLINE:
                acknowledged = parseMonitorResponse(msg.getText());
                for (String nick : acknowledged)
                {
                    update(nick, IrcStatusEnum.ONLINE);
                }
                monitoredNickList.addAll(acknowledged);
                break;
            case IRC_RPL_MONOFFLINE:
                acknowledged = parseMonitorResponse(msg.getText());
                for (String nick : acknowledged)
                {
                    update(nick, IrcStatusEnum.OFFLINE);
                }
                monitoredNickList.addAll(acknowledged);
                break;
            case IRC_ERR_MONLISTFULL:
                LOGGER.debug("MONITOR list full. Nick was not added. "
                    + "Fall back Basic Poller will be used if it is enabled. ("
                    + msg.getText() + ")");
                break;
            }
        }

        /**
         * Update all monitored nicks upon receiving a server-side QUIT message
         * for local user.
         */
        @Override
        public void onUserQuit(QuitMessage msg)
        {
            super.onUserQuit(msg);
            if (localUser(msg.getSource().getNick())) {
                updateAll(IrcStatusEnum.OFFLINE);
            }
        }

        /**
         * Update all monitored nicks upon receiving a server-side ERROR
         * response.
         */
        @Override
        public void onError(ErrorMessage msg)
        {
            super.onError(msg);
            updateAll(IrcStatusEnum.OFFLINE);
        }

        /**
         * Parse response messages.
         *
         * @param message the message
         * @return Returns the list of targets extracted.
         */
        private List<String> parseMonitorResponse(final String message)
        {
            // Note: this should support both targets consisting of only a nick,
            // and targets consisting of nick!ident@host formats. (And probably
            // any variation on this that is typically allowed in IRC.)
            final LinkedList<String> acknowledged = new LinkedList<String>();
            final String[] targets = message.substring(1).split(",");
            for (String target : targets)
            {
                String[] parts = target.trim().split("!");
                acknowledged.add(parts[0]);
            }
            return acknowledged;
        }

        /**
         * Update all monitored nicks to specified status.
         *
         * @param status the desired status
         */
        private void updateAll(final IrcStatusEnum status)
        {
            final LinkedList<String> nicks;
            synchronized (monitoredNickList)
            {
                nicks = new LinkedList<String>(monitoredNickList);
            }
            for (String nick : nicks)
            {
                update(nick, status);
            }
        }

        /**
         * Update specified nick to specified presence status.
         *
         * @param nick the target nick
         * @param status the current status
         */
        private void update(final String nick, final IrcStatusEnum status)
        {
            this.operationSet.updateNickContactPresence(nick, status);
        }
    }
}