aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/gui/main/login/LoginManager.java
blob: 224d6d6ae2069e8663cbd2caeeab52a8b04b01e6 (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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
/*
 * SIP Communicator, 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.gui.main.login;

import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.customcontrols.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.impl.gui.main.authorization.*;
import net.java.sip.communicator.impl.gui.utils.Constants;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;

import org.osgi.framework.*;

/**
 * The <tt>LoginManager</tt> manages the login operation. Here we obtain the
 * <tt>ProtocolProviderFactory</tt>, we make the account installation and we
 * handle all events related to the registration state.
 * <p>
 * The <tt>LoginManager</tt> is the one that opens one or more
 * <tt>LoginWindow</tt>s for each <tt>ProtocolProviderFactory</tt>. The
 * <tt>LoginWindow</tt> is where user could enter an identifier and password.
 * <p>
 * Note that the behavior of this class will be changed when the Configuration
 * Service is ready.
 *
 * @author Yana Stamcheva
 */
public class LoginManager
    implements  ServiceListener,
                RegistrationStateChangeListener
{
    private final Logger logger = Logger.getLogger(LoginManager.class);

    private final MainFrame mainFrame;

    private boolean manuallyDisconnected = false;

    /**
     * Creates an instance of the <tt>LoginManager</tt>, by specifying the main
     * application window.
     *
     * @param mainFrame the main application window
     */
    public LoginManager(MainFrame mainFrame)
    {
        this.mainFrame = mainFrame;

        GuiActivator.bundleContext.addServiceListener(this);
    }

    /**
     * Registers the given protocol provider.
     *
     * @param protocolProvider the ProtocolProviderService to register.
     */
    public void login(ProtocolProviderService protocolProvider)
    {
        SecurityAuthorityImpl secAuth
            = new SecurityAuthorityImpl(protocolProvider);

        mainFrame.getAccountStatusPanel().startConnecting(protocolProvider);

        new RegisterProvider(protocolProvider, secAuth).start();
    }

    /**
     * Unregisters the given protocol provider.
     *
     * @param protocolProvider the ProtocolProviderService to unregister
     */
    public void logoff(ProtocolProviderService protocolProvider)
    {
        new UnregisterProvider(protocolProvider).start();
    }

    /**
     * Shows login window for each registered account.
     *
     * @param parent The parent MainFrame window.
     */
    public void runLogin(MainFrame parent)
    {
        for (ProtocolProviderFactory providerFactory : GuiActivator
            .getProtocolProviderFactories().values())
        {
            ServiceReference serRef;
            ProtocolProviderService protocolProvider;

            for (AccountID accountID : providerFactory.getRegisteredAccounts())
            {
                serRef = providerFactory.getProviderForAccount(accountID);

                protocolProvider =
                    (ProtocolProviderService) GuiActivator.bundleContext
                        .getService(serRef);

                protocolProvider.addRegistrationStateChangeListener(this);

                this.mainFrame.addProtocolProvider(protocolProvider);

                Object status =
                    this.mainFrame
                        .getProtocolProviderLastStatus(protocolProvider);

                if (status == null
                    || status.equals(Constants.ONLINE_STATUS)
                    || ((status instanceof PresenceStatus)
                        && (((PresenceStatus) status)
                        .getStatus() >= PresenceStatus.ONLINE_THRESHOLD)))
                {
                    this.login(protocolProvider);
                }
            }
        }
    }

    /**
     * The method is called by a ProtocolProvider implementation whenever a
     * change in the registration state of the corresponding provider had
     * occurred.
     *
     * @param evt ProviderStatusChangeEvent the event describing the status
     *            change.
     */
    public void registrationStateChanged(RegistrationStateChangeEvent evt)
    {
        RegistrationState newState = evt.getNewState();
        ProtocolProviderService protocolProvider = evt.getProvider();
        AccountID accountID = protocolProvider.getAccountID();

        if (logger.isTraceEnabled())
            logger.trace("Protocol provider: " + protocolProvider
            + " changed its state to: " + evt.getNewState().getStateName());

        if (newState.equals(RegistrationState.REGISTERED)
            || newState.equals(RegistrationState.UNREGISTERED)
            || newState.equals(RegistrationState.EXPIRED)
            || newState.equals(RegistrationState.AUTHENTICATION_FAILED)
            || newState.equals(RegistrationState.CONNECTION_FAILED)
            || newState.equals(RegistrationState.CHALLENGED_FOR_AUTHENTICATION)
            || newState.equals(RegistrationState.REGISTERED))
        {
            mainFrame.getAccountStatusPanel().stopConnecting(protocolProvider);
        }

        if (newState.equals(RegistrationState.REGISTERED))
        {
            OperationSetPresence presence
                = MainFrame.getProtocolPresenceOpSet(protocolProvider);

            OperationSetMultiUserChat multiUserChat = 
                mainFrame.getMultiUserChatOpSet(protocolProvider);

            if (presence != null)
            {
                presence.setAuthorizationHandler(new AuthorizationHandlerImpl(
                    mainFrame));
            }

            if(multiUserChat != null)
            {
                GuiActivator.getUIService().getConferenceChatManager()
                    .getChatRoomList().synchronizeOpSetWithLocalContactList(
                        protocolProvider, multiUserChat);
            }
          
        }
        else if (newState.equals(RegistrationState.AUTHENTICATION_FAILED))
        {
            if (evt.getReasonCode() == RegistrationStateChangeEvent
                    .REASON_RECONNECTION_RATE_LIMIT_EXCEEDED)
            {

                String msgText = GuiActivator.getResources().getI18NString(
                    "service.gui.RECONNECTION_LIMIT_EXCEEDED", new String[]
                    { accountID.getUserID(), accountID.getService() });

                new ErrorDialog(
                    null,
                    GuiActivator.getResources()
                        .getI18NString("service.gui.ERROR"),
                    msgText).showDialog();
            }
            else if (evt.getReasonCode() == RegistrationStateChangeEvent
                                                .REASON_NON_EXISTING_USER_ID)
            {
                String msgText = GuiActivator.getResources().getI18NString(
                    "service.gui.NON_EXISTING_USER_ID",
                    new String[]
                    { protocolProvider.getProtocolDisplayName() });

                new ErrorDialog(
                    null,
                    GuiActivator.getResources()
                        .getI18NString("service.gui.ERROR"),
                    msgText).showDialog();
            }

            if (logger.isTraceEnabled())
                logger.trace(evt.getReason());
        }
//        CONNECTION_FAILED events are now dispatched in reconnect plugin
//        else if (newState.equals(RegistrationState.CONNECTION_FAILED))
//        {
//            String msgText = GuiActivator.getResources().getI18NString(
//                "service.gui.CONNECTION_FAILED_MSG",
//                new String[]
//                {   accountID.getUserID(),
//                    accountID.getService() });
//
//            int result = new MessageDialog(
//                null,
//                GuiActivator.getResources().getI18NString("service.gui.ERROR"),
//                msgText,
//                GuiActivator.getResources().getI18NString("service.gui.RETRY"),
//                false).showDialog();
//
//            if (result == MessageDialog.OK_RETURN_CODE)
//            {
//                this.login(protocolProvider);
//            }
//
//            logger.trace(evt.getReason());
//        }
        else if (newState.equals(RegistrationState.EXPIRED))
        {
            String msgText = GuiActivator.getResources().getI18NString(
                "service.gui.CONNECTION_EXPIRED_MSG",
                new String[]
                { protocolProvider.getProtocolDisplayName() });

            new ErrorDialog(null,
                GuiActivator.getResources().getI18NString("service.gui.ERROR"),
                msgText).showDialog();

            logger.error(evt.getReason());
        }
        else if (newState.equals(RegistrationState.UNREGISTERED))
        {
            if (!manuallyDisconnected)
            {
                if (evt.getReasonCode() == RegistrationStateChangeEvent
                                            .REASON_MULTIPLE_LOGINS)
                {
                    String msgText = GuiActivator.getResources().getI18NString(
                        "service.gui.MULTIPLE_LOGINS",
                        new String[]
                        { accountID.getUserID(), accountID.getService() });

                    new ErrorDialog(null,
                        GuiActivator.getResources()
                            .getI18NString("service.gui.ERROR"),
                        msgText).showDialog();
                }
                else if (evt.getReasonCode() == RegistrationStateChangeEvent
                                            .REASON_CLIENT_LIMIT_REACHED_FOR_IP)
                {
                    String msgText = GuiActivator.getResources().getI18NString(
                        "service.gui.LIMIT_REACHED_FOR_IP", new String[]
                        { protocolProvider.getProtocolDisplayName() });

                    new ErrorDialog(null,
                        GuiActivator.getResources()
                            .getI18NString("service.gui.ERROR"),
                        msgText).showDialog();
                }
                else if (evt.getReasonCode() == RegistrationStateChangeEvent
                                            .REASON_USER_REQUEST)
                {
                    // do nothing
                }
                else
                {
                    String msgText = GuiActivator.getResources().getI18NString(
                        "service.gui.UNREGISTERED_MESSAGE", new String[]
                        { accountID.getUserID(), accountID.getService() });

                    new ErrorDialog(null,
                        GuiActivator.getResources()
                            .getI18NString("service.gui.ERROR"),
                        msgText).showDialog();
                }
                if (logger.isTraceEnabled())
                    logger.trace(evt.getReason());
            }
        }
    }

    /**
     * Implements the <tt>ServiceListener</tt> method. Verifies whether the
     * passed event concerns a <tt>ProtocolProviderService</tt> and adds the
     * corresponding UI controls.
     *
     * @param event The <tt>ServiceEvent</tt> object.
     */
    public void serviceChanged(ServiceEvent event)
    {
        ServiceReference serviceRef = event.getServiceReference();

        // if the event is caused by a bundle being stopped, we don't want to
        // know
        if (serviceRef.getBundle().getState() == Bundle.STOPPING)
        {
            return;
        }

        Object service = GuiActivator.bundleContext.getService(serviceRef);

        // we don't care if the source service is not a protocol provider
        if (!(service instanceof ProtocolProviderService))
        {
            return;
        }

        switch (event.getType())
        {
        case ServiceEvent.REGISTERED:
            this.handleProviderAdded((ProtocolProviderService) service);
            break;
        case ServiceEvent.UNREGISTERING:
            this.handleProviderRemoved((ProtocolProviderService) service);
            break;
        }
    }

    /**
     * Adds all UI components (status selector box, etc) related to the given
     * protocol provider.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt>
     */
    private void handleProviderAdded(ProtocolProviderService protocolProvider)
    {
        if (logger.isTraceEnabled())
            logger.trace("The following protocol provider was just added: "
            + protocolProvider.getAccountID().getAccountAddress());

        protocolProvider.addRegistrationStateChangeListener(this);
        this.mainFrame.addProtocolProvider(protocolProvider);

        Object status = this.mainFrame
            .getProtocolProviderLastStatus(protocolProvider);

        if (status == null
            || status.equals(Constants.ONLINE_STATUS)
            || ((status instanceof PresenceStatus) && (((PresenceStatus) status)
                .getStatus() >= PresenceStatus.ONLINE_THRESHOLD)))
        {
            this.login(protocolProvider);
        }
    }

    /**
     * Removes all UI components related to the given protocol provider.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt>
     */
    private void handleProviderRemoved(ProtocolProviderService protocolProvider)
    {
        this.mainFrame.removeProtocolProvider(protocolProvider);
    }

    public boolean isManuallyDisconnected()
    {
        return manuallyDisconnected;
    }

    public void setManuallyDisconnected(boolean manuallyDisconnected)
    {
        this.manuallyDisconnected = manuallyDisconnected;
    }

    /**
     * Registers a protocol provider in a separate thread.
     */
    private class RegisterProvider
        extends Thread
    {
        private final ProtocolProviderService protocolProvider;

        private final SecurityAuthority secAuth;

        RegisterProvider(ProtocolProviderService protocolProvider,
            SecurityAuthority secAuth)
        {
            this.protocolProvider = protocolProvider;
            this.secAuth = secAuth;
        }

        /**
         * Registers the contained protocol provider and process all possible
         * errors that may occur during the registration process.
         */
        public void run()
        {
            try
            {
                protocolProvider.register(secAuth);
            }
            catch (OperationFailedException ex)
            {
                handleOperationFailedException(ex);
            }
            catch (Throwable ex)
            {
                logger.error("Failed to register protocol provider. ", ex);

                AccountID accountID = protocolProvider.getAccountID();
                new ErrorDialog(
                    mainFrame,
                    GuiActivator.getResources()
                        .getI18NString("service.gui.ERROR"),
                    GuiActivator.getResources()
                        .getI18NString("service.gui.LOGIN_GENERAL_ERROR",
                    new String[]
                    { accountID.getUserID(), 
                      accountID.getProtocolName(),
                      accountID.getService() }))
                .showDialog();
            }
        }

        private void handleOperationFailedException(OperationFailedException ex)
        {
            String errorMessage = "";

            switch (ex.getErrorCode())
            {
            case OperationFailedException.GENERAL_ERROR:
            {
                logger.error("Provider could not be registered"
                    + " due to the following general error: ", ex);

                AccountID accountID = protocolProvider.getAccountID();
                errorMessage =
                    GuiActivator.getResources().getI18NString(
                        "service.gui.LOGIN_GENERAL_ERROR",
                        new String[]
                           { accountID.getUserID(),
                             accountID.getProtocolName(),
                             accountID.getService() });

                new ErrorDialog(mainFrame,
                    GuiActivator.getResources()
                        .getI18NString("service.gui.ERROR"), errorMessage, ex)
                .showDialog();
            }
                break;
            case OperationFailedException.INTERNAL_ERROR:
            {
                logger.error("Provider could not be registered"
                    + " due to the following internal error: ", ex);

                AccountID accountID = protocolProvider.getAccountID();
                errorMessage =
                    GuiActivator.getResources().getI18NString(
                        "service.gui.LOGIN_INTERNAL_ERROR",
                        new String[]
                           { accountID.getUserID(), accountID.getService() });

                new ErrorDialog(mainFrame,
                    GuiActivator.getResources().getI18NString(
                        "service.gui.ERROR"), errorMessage, ex).showDialog();
            }
                break;
            case OperationFailedException.NETWORK_FAILURE:
            {
                if (logger.isInfoEnabled())
                {
                    logger.info("Provider could not be registered"
                            + " due to a network failure: " + ex);
                }

                AccountID accountID = protocolProvider.getAccountID();
                errorMessage = GuiActivator.getResources().getI18NString(
                    "service.gui.LOGIN_NETWORK_ERROR",
                    new String[]
                       { accountID.getUserID(), accountID.getService() });

                int result =
                    new MessageDialog(
                        null,
                        GuiActivator.getResources()
                            .getI18NString("service.gui.ERROR"),
                        errorMessage,
                        GuiActivator.getResources()
                            .getI18NString("service.gui.RETRY"), false)
                    .showDialog();

                if (result == MessageDialog.OK_RETURN_CODE)
                {
                    login(protocolProvider);
                }
            }
                break;
            case OperationFailedException.INVALID_ACCOUNT_PROPERTIES:
            {
                logger.error("Provider could not be registered"
                    + " due to an invalid account property: ", ex);

                AccountID accountID = protocolProvider.getAccountID();
                errorMessage =
                    GuiActivator.getResources().getI18NString(
                        "service.gui.LOGIN_INVALID_PROPERTIES_ERROR",
                        new String[]
                        { accountID.getUserID(), accountID.getService() });

                new ErrorDialog(mainFrame,
                    GuiActivator.getResources().getI18NString("service.gui.ERROR"),
                    errorMessage, ex).showDialog();
            }
                break;
            default:
                logger.error("Provider could not be registered.", ex);
            }
        }
    }

    /**
     * Unregisters a protocol provider in a separate thread.
     */
    private class UnregisterProvider
        extends Thread
    {
        ProtocolProviderService protocolProvider;

        UnregisterProvider(ProtocolProviderService protocolProvider)
        {
            this.protocolProvider = protocolProvider;
        }

        /**
         * Unregisters the contained protocol provider and process all possible
         * errors that may occur during the un-registration process.
         */
        public void run()
        {
            try
            {
                protocolProvider.unregister();
            }
            catch (OperationFailedException ex)
            {
                int errorCode = ex.getErrorCode();

                if (errorCode == OperationFailedException.GENERAL_ERROR)
                {
                    logger.error("Provider could not be unregistered"
                        + " due to the following general error: " + ex);
                }
                else if (errorCode == OperationFailedException.INTERNAL_ERROR)
                {
                    logger.error("Provider could not be unregistered"
                        + " due to the following internal error: " + ex);
                }
                else if (errorCode == OperationFailedException.NETWORK_FAILURE)
                {
                    logger.error("Provider could not be unregistered"
                        + " due to a network failure: " + ex);
                }

                new ErrorDialog(mainFrame,
                    GuiActivator.getResources()
                        .getI18NString("service.gui.ERROR"),
                    GuiActivator.getResources()
                        .getI18NString("service.gui.LOGOFF_NOT_SUCCEEDED",
                        new String[]
                        { protocolProvider.getAccountID().getUserID(),
                            protocolProvider.getAccountID().getService() }))
                    .showDialog();
            }
        }
    }
}