aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/plugin/generalconfig/autoaway/AutoAwayWatcher.java
blob: 303b0134b9f88287cb3b516cdc8c890801a8cd82 (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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
 * 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.plugin.generalconfig.autoaway;

import java.beans.*;
import java.util.*;

import net.java.sip.communicator.plugin.generalconfig.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.sysactivity.*;
import net.java.sip.communicator.service.sysactivity.event.*;
import net.java.sip.communicator.util.*;

import org.jitsi.service.configuration.*;
import org.osgi.framework.*;

/**
 * Listens for idle events from SystemActivityNotifications Service.
 *
 * @author Damian Minkov
 */
public class AutoAwayWatcher
    implements ServiceListener,
               RegistrationStateChangeListener
{
    /**
     * The logger.
     */
    private static final Logger logger
        = Logger.getLogger(AutoAwayWatcher.class);

    /**
     * The states of providers before going to away.
     */
    private final Map<ProtocolProviderService, PresenceStatus> lastStates
        = new HashMap<ProtocolProviderService, PresenceStatus>();

    /**
     * Listens for idle events.
     */
    private IdleListener idleListener = null;

    /**
     * Creates AutoAway handler.
     * @param configurationService the config service.
     */
    public AutoAwayWatcher(ConfigurationService configurationService)
    {
        // if enabled start
        String enabledDefault
            = GeneralConfigPluginActivator.getResources().getSettingsString(
                    Preferences.ENABLE);

        if (configurationService.getBoolean(
                Preferences.ENABLE,
                Boolean.parseBoolean(enabledDefault)))
        {
            start();
        }

        // listens for changes in configuration enable/disable
        configurationService.addPropertyChangeListener(
                Preferences.ENABLE,
                new PropertyChangeListener()
                {
                    public void propertyChange(PropertyChangeEvent evt)
                    {
                        if(Boolean.parseBoolean((String) evt.getNewValue()))
                            start();
                        else
                            stopInner();
                    }
                }
        );

        // listens for changes in configured value.
        configurationService.addPropertyChangeListener(
            Preferences.TIMER,
            new PropertyChangeListener()
            {
                public void propertyChange(PropertyChangeEvent evt)
                {
                    stopInner();
                    start();
                }
            }
        );

        // listen for new providers
        GeneralConfigPluginActivator.bundleContext.addServiceListener(this);

        // lets check current providers
        ServiceReference[] protocolProviderRefs = null;
        try
        {
            protocolProviderRefs = GeneralConfigPluginActivator.bundleContext
                .getServiceReferences(ProtocolProviderService.class.getName(),
                                      null);
        }
        catch (InvalidSyntaxException ex)
        {
            // this shouldn't happen since we're providing no parameter string
            // but let's log just in case.
            logger.error(
                "Error while retrieving service refs", ex);
            return;
        }

        // in case we found any
        if (protocolProviderRefs != null)
        {
            for (int i = 0; i < protocolProviderRefs.length; i++)
            {
                ProtocolProviderService provider = (ProtocolProviderService)
                    GeneralConfigPluginActivator.bundleContext
                        .getService(protocolProviderRefs[i]);

                this.handleProviderAdded(provider);
            }
        }
    }

    /**
     * Starts and add needed listeners.
     */
    private void start()
    {
        if(idleListener == null)
        {
            idleListener = new IdleListener();

            SystemActivityNotificationsService
                systemActivityNotificationsService
                    =  getSystemActivityNotificationsService();

            systemActivityNotificationsService.addIdleSystemChangeListener(
                    StatusUpdateThread.getTimer() * 60 * 1000,
                    idleListener);
            systemActivityNotificationsService
                .addSystemActivityChangeListener(idleListener);
        }
    }

    /**
     * Stops and removes the listeners.
     */
    public void stop()
    {
        GeneralConfigPluginActivator.bundleContext.removeServiceListener(this);
        stopInner();
    }

    /**
     * Stops and removes the listeners, without the global service listener.
     */
    private void stopInner()
    {
        if(idleListener != null)
        {
            SystemActivityNotificationsService
                systemActivityNotificationsService
                    =  getSystemActivityNotificationsService();

            systemActivityNotificationsService.removeIdleSystemChangeListener(
                    idleListener);
            systemActivityNotificationsService
                .removeSystemActivityChangeListener(idleListener);

            idleListener = null;
        }
    }

    /**
     * Change protocol to away saving status so it can be set again when
     * out of idle state.
     */
    private void changeProtocolsToAway()
    {
        for (ProtocolProviderService protocolProviderService
                : GeneralConfigPluginActivator.getProtocolProviders())
        {
            OperationSetPresence presence
                = protocolProviderService.getOperationSet(
                        OperationSetPresence.class);

            if(presence == null)
                continue;

            PresenceStatus status = presence.getPresenceStatus();

            if (status.getStatus() < PresenceStatus.AVAILABLE_THRESHOLD)
            {
                // already (manually) set to away or lower
                continue;
            }

            addProviderToLastStates(protocolProviderService, status);

            PresenceStatus newStatus
                = StatusUpdateThread.findAwayStatus(presence);

            try
            {
                if (newStatus != null)
                {
                    presence.publishPresenceStatus(
                            newStatus,
                            newStatus.getStatusName());
                }
            }
            catch (IllegalArgumentException e)
            {
            }
            catch (IllegalStateException e)
            {
            }
            catch (OperationFailedException e)
            {
            }
        }
    }

    /**
     * Back to status which was already saved before going to idle.
     */
    private void changeProtocolsToPreviousState()
    {
        for (ProtocolProviderService protocolProviderService
                : GeneralConfigPluginActivator.getProtocolProviders())
        {
            PresenceStatus lastState
                = lastStates.get(protocolProviderService);

            if (lastState != null)
            {
                OperationSetPresence presence
                    = protocolProviderService
                        .getOperationSet(
                            OperationSetPresence.class);
                try
                {
                    presence
                        .publishPresenceStatus(lastState, "");
                }
                catch (IllegalArgumentException e)
                {
                }catch (IllegalStateException e)
                {
                }
                catch (OperationFailedException e)
                {
                }
                removeProviderFromLastStates(protocolProviderService);
            }
        }
    }

    /**
     * The SystemActivityNotifications Service.
     * @return the SystemActivityNotifications Service.
     */
    private SystemActivityNotificationsService
        getSystemActivityNotificationsService()
    {
        return
            ServiceUtils.getService(
                    GeneralConfigPluginActivator.bundleContext,
                    SystemActivityNotificationsService.class);
    }

    /**
     * When new protocol provider is registered we add our
     * registration change listener.
     * If unregistered remove reference to the provider and the
     * registration change listener.
     *
     * @param serviceEvent ServiceEvent
     */
    public void serviceChanged(ServiceEvent serviceEvent)
    {
        Object service
            = GeneralConfigPluginActivator.bundleContext.getService(
                    serviceEvent.getServiceReference());

        // we don't care if the source service is not a protocol provider
        if (service instanceof ProtocolProviderService)
        {
            int serviceEventType = serviceEvent.getType();

            if (serviceEventType == ServiceEvent.REGISTERED)
                handleProviderAdded((ProtocolProviderService) service);
            else if (serviceEventType == ServiceEvent.UNREGISTERING)
                handleProviderRemoved((ProtocolProviderService) service);
        }
    }

    /**
     * Used to set registration state change listener.
     *
     * @param provider ProtocolProviderService
     */
    private synchronized void handleProviderAdded(
            ProtocolProviderService provider)
    {
        provider.addRegistrationStateChangeListener(this);
    }

    /**
     * Removes the registration change listener.
     *
     * @param provider the ProtocolProviderService that has been unregistered.
     */
    private void handleProviderRemoved(ProtocolProviderService provider)
    {
        provider.removeRegistrationStateChangeListener(this);
    }

    /**
     * Remove provider from list with last statuses.
     * If this is the last provider stop listening for idle events.
     * @param provider
     */
    private synchronized void removeProviderFromLastStates(
        ProtocolProviderService provider)
    {
        lastStates.remove(provider);

        if(lastStates.size() == 0)
            stopInner();
    }

    /**
     * Remember provider's last status, normally before setting it to away.
     * If needed start listening for idle events.
     * @param provider the provider.
     * @param status the status to save.
     */
    private synchronized void addProviderToLastStates(
            ProtocolProviderService provider,
            PresenceStatus status)
    {
        if(lastStates.size() == 0)
            start();

        lastStates.put(provider, status);
    }

    /**
     * Listens for provider states.
     * @param evt
     */
    public void registrationStateChanged(RegistrationStateChangeEvent evt)
    {
         if(evt.getSource() instanceof ProtocolProviderService)
         {
            if(evt.getNewState().equals(RegistrationState.UNREGISTERED)
               || evt.getNewState().equals(RegistrationState.CONNECTION_FAILED))
            {
                removeProviderFromLastStates(evt.getProvider());
            }
            else if(evt.getNewState().equals(
                                RegistrationState.REGISTERED))
            {
                // we have at least one provider, so lets start listening
                if(lastStates.size() == 0)
                {
                    start();
                }
                else
                {
                    // or check are we away
                    if(getSystemActivityNotificationsService()
                        .getTimeSinceLastInput()
                            > StatusUpdateThread.getTimer()*60*1000)
                    {
                        // we are away, so update the newly registered provider
                        // do it in new thread to give the provider
                        // time dispatch his status
                        new Thread(new Runnable()
                        {
                            public void run()
                            {
                                try{
                                Thread.sleep(1000);
                                }
                                catch(Throwable t){}

                                changeProtocolsToAway();
                            }
                        }).start();
                    }
                }
            }
         }
    }

    /**
     * Listener waiting for idle state change.
     */
    private class IdleListener
        implements SystemActivityChangeListener
    {
        /**
         * Listens for activities and set corresponding statuses.
         *
         * @param event the <tt>NotificationActionTypeEvent</tt>, which is
         */
        public void activityChanged(SystemActivityEvent event)
        {
            switch(event.getEventID())
            {
                case SystemActivityEvent.EVENT_DISPLAY_SLEEP:
                case SystemActivityEvent.EVENT_SCREEN_LOCKED:
                case SystemActivityEvent.EVENT_SCREENSAVER_START:
                case SystemActivityEvent.EVENT_SYSTEM_IDLE:
                    changeProtocolsToAway();
                    break;
                case SystemActivityEvent.EVENT_DISPLAY_WAKE:
                case SystemActivityEvent.EVENT_SCREEN_UNLOCKED:
                case SystemActivityEvent.EVENT_SCREENSAVER_STOP:
                case SystemActivityEvent.EVENT_SYSTEM_IDLE_END:
                    changeProtocolsToPreviousState();
                    break;
            }
        }
    }
}