summaryrefslogtreecommitdiff
path: root/tubes/source/manager.cxx
blob: 896fcc8c0cf3ddf8316e1fc9c24630170707f93a (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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2012 Red Hat, Inc., Eike Rathke <erack@redhat.com>
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include "tubes/manager.hxx"
#include "tubes/constants.h"
#include <rtl/strbuf.hxx>
#include <rtl/uuid.h>
#include <osl/mutex.hxx>
#include <cstring>


#if defined SAL_LOG_INFO
namespace
{
struct InfoLogger
{
    const void* mpThat;
    const char* mpMethod;
    explicit InfoLogger( const void* pThat, const char* pMethod )
        :
            mpThat( pThat),
            mpMethod( pMethod)
    {
        SAL_INFO( "tubes.method", mpThat << " entering " << mpMethod);
    }
    ~InfoLogger()
    {
        SAL_INFO( "tubes.method", mpThat << " leaving  " << mpMethod);
    }
};
}
#define INFO_LOGGER_F(s)    InfoLogger aLogger(0,(s))
#define INFO_LOGGER(s)      InfoLogger aLogger(this,(s))
#else
#define INFO_LOGGER_F(s)
#define INFO_LOGGER(s)
#endif // SAL_LOG_INFO


using namespace rtl;
using namespace osl;


TeleManagerImpl* TeleManager::pImpl     = NULL;
sal_uInt32       TeleManager::nRefCount = 0;
rtl::OString     TeleManager::aNameSuffix;

sal_uInt32       TeleManager::nAnotherRefCount = 0;
TeleManager*     TeleManager::pSingleton = NULL;


/** Refcounted singleton implementation class. */
class TeleManagerImpl
{
public:
    GMainLoop*                          mpLoop;
    TpAutomaticClientFactory*           mpFactory;
    TpBaseClient*                       mpClient;
    TpBaseClient*                       mpFileTransferClient;
    TpAccountManager*                   mpAccountManager;
    TeleManager::AccountManagerStatus   meAccountManagerStatus;
    bool                                mbAccountManagerReadyHandlerInvoked;
    ContactList*                        mpContactList;

                            TeleManagerImpl();
                            ~TeleManagerImpl();
};


void TeleManager::DBusChannelHandler(
        TpSimpleHandler*            /*handler*/,
        TpAccount*                  pAccount,
        TpConnection*               /*connection*/,
        GList*                      pChannels,
        GList*                      /*requests_satisfied*/,
        gint64                      /*user_action_time*/,
        TpHandleChannelsContext*    pContext,
        gpointer                    pUserData)
{
    bool aAccepted = false;
    INFO_LOGGER_F( "TeleManager::DBusChannelHandler");

    TeleManager* pManager = reinterpret_cast<TeleManager*>(pUserData);
    SAL_WARN_IF( !pManager, "tubes", "TeleManager::DBusChannelHandler: no manager");
    if (!pManager)
        return;

    for (GList* p = pChannels; p; p = p->next)
    {
        TpChannel* pChannel = TP_CHANNEL(p->data);
        if (!pChannel)
            continue;

        SAL_INFO( "tubes", "TeleManager::DBusChannelHandler: incoming dbus channel: "
                << tp_channel_get_identifier( pChannel));

        if (TP_IS_DBUS_TUBE_CHANNEL( pChannel))
        {
            SAL_INFO( "tubes", "accepting");
            aAccepted = true;

            TeleConference* pConference = new TeleConference( pManager, pAccount, TP_DBUS_TUBE_CHANNEL( pChannel ) );
            pConference->acceptTube();
            pManager->sigConferenceCreated( pConference );
        }
        else
        {
            SAL_INFO( "tubes", "ignored");
        }
    }

    if (aAccepted)
        tp_handle_channels_context_accept( pContext);
    else
    {
        GError *pError = g_error_new_literal( TP_ERRORS, TP_ERROR_CONFUSED,
            "None of these channels were LibreOffice D-Bus tubes; "
            "why did the Channel Dispatcher give them to us?");
        tp_handle_channels_context_fail( pContext, pError);
        g_clear_error (&pError);
    }
}

void TeleManager::TransferDone( EmpathyFTHandler *handler, TpFileTransferChannel *, gpointer pUserData)
{
    TeleManager* pManager = reinterpret_cast<TeleManager*>(pUserData);

    SAL_INFO( "tubes", "TeleConference_TransferDone: hooray!");
    GFile *gfile = empathy_ft_handler_get_gfile( handler);
    char *uri = g_file_get_uri( gfile);
    rtl::OUString aUri( uri, strlen( uri), RTL_TEXTENCODING_UTF8);
    g_free( uri);

    pManager->sigFileReceived( aUri );

    g_object_unref( handler);
}

static void TeleManager_TransferError( EmpathyFTHandler *handler, const GError *error, void*)
{
    SAL_INFO( "tubes", "TeleConference_TransferError: " << error->message);

    g_object_unref( handler);
}

static void
TeleManager_IncomingHandlerReady (
    EmpathyFTHandler*   pHandler,
    GError*             pError,
    void*               pUserData)
{
    TeleManager* pManager = reinterpret_cast<TeleManager*>(pUserData);

    if (pError)
    {
        SAL_INFO ("tubes", "failed to prepare incoming transfer: " << pError->message);
        g_object_unref( pHandler);
        return;
    }

    /* The filename suggested by the sender, which in our case is the last bit
     * of whatever URI got passed to ::sendFile()
     */
    const char* pFileName = empathy_ft_handler_get_filename( pHandler);
    char* pLocalUri = g_strdup_printf( "file:///tmp/LibreOffice-collab-%s", pFileName);
    GFile *pDestination = g_file_new_for_uri( pLocalUri);
    g_free( pLocalUri);

    empathy_ft_handler_incoming_set_destination( pHandler, pDestination);
    g_object_unref( pDestination);

    g_signal_connect( pHandler, "transfer-done", G_CALLBACK (&TeleManager::TransferDone), pManager);
    g_signal_connect( pHandler, "transfer-error", G_CALLBACK (TeleManager_TransferError), pManager);
    empathy_ft_handler_start_transfer( pHandler);
}

static void TeleManager_FileTransferHandler(
        TpSimpleHandler*            /*handler*/,
        TpAccount*                  /*Account*/,
        TpConnection*               /*connection*/,
        GList*                      pChannels,
        GList*                      /*requests_satisfied*/,
        gint64                      /*user_action_time*/,
        TpHandleChannelsContext*    pContext,
        gpointer                    pUserData)
{
    bool aAccepted = false;
    INFO_LOGGER_F( "TeleManager_FileTransferHandler");

    TeleManager* pManager = reinterpret_cast<TeleManager*>(pUserData);
    SAL_WARN_IF( !pManager, "tubes", "TeleManager_FileTransferHandler: no manager");
    if (!pManager)
        return;

    for (GList* p = pChannels; p; p = p->next)
    {
        TpChannel* pChannel = TP_CHANNEL(p->data);

        SAL_INFO( "tubes", "TeleManager_FileTransferHandler: incoming dbus channel: "
                << tp_channel_get_identifier( pChannel));

        if (TP_IS_FILE_TRANSFER_CHANNEL( pChannel))
        {
            SAL_INFO( "tubes", "accepting file transfer");
            empathy_ft_handler_new_incoming( TP_FILE_TRANSFER_CHANNEL( pChannel),
                TeleManager_IncomingHandlerReady, pManager);
            aAccepted = true;
        }
        else
        {
            SAL_INFO( "tubes", "ignored");
        }
    }

    if (aAccepted)
        tp_handle_channels_context_accept( pContext);
    else
    {
        GError *pError = g_error_new_literal( TP_ERRORS, TP_ERROR_CONFUSED,
            "None of these channels were file transfers; "
            "why did the Channel Dispatcher give them to us?");
        tp_handle_channels_context_fail( pContext, pError);
        g_clear_error (&pError);
    }
}

static void TeleManager_ChannelReadyHandler(
        GObject*        pSourceObject,
        GAsyncResult*   pResult,
        gpointer        pUserData
        )
{
    INFO_LOGGER_F( "TeleManager_ChannelReadyHandler");

    TeleConference* pConference = reinterpret_cast<TeleConference*>(pUserData);
    SAL_WARN_IF( !pConference, "tubes", "TeleManager_ChannelReadyHandler: no conference");
    if (!pConference)
        return;

    TeleManager* pManager = pConference->getManager();
    SAL_WARN_IF( !pManager, "tubes", "TeleManager_ChannelReadyHandler: no manager");
    if (!pManager)
        return;

    pManager->setChannelReadyHandlerInvoked( true);

    TpAccountChannelRequest* pChannelRequest = TP_ACCOUNT_CHANNEL_REQUEST( pSourceObject);
    GError* pError = NULL;
    TpChannel * pChannel = tp_account_channel_request_create_and_handle_channel_finish(
            pChannelRequest, pResult, NULL, &pError);
    if (!pChannel)
    {
        // "account isn't Enabled" means just that..
        /* FIXME: detect and handle, domain=132, code=3 */
        SAL_WARN( "tubes", "TeleManager_ChannelReadyHandler: no channel: " << pError->message);
        g_error_free( pError);
        return;
    }

    pConference->setChannel( tp_account_channel_request_get_account( pChannelRequest),
            TP_DBUS_TUBE_CHANNEL (pChannel));
    pConference->offerTube();
}

static gboolean caps_hack_timeout_cb (void *pUserData)
{
    TeleManager* pManager = reinterpret_cast<TeleManager*>(pUserData);

    pManager->setAccountManagerReadyHandlerInvoked( true);
    return FALSE;
}

static void TeleManager_AccountManagerReadyHandler(
        GObject*        pSourceObject,
        GAsyncResult*   pResult,
        gpointer        pUserData
        )
{
    INFO_LOGGER_F( "TeleManager_AccountManagerReadyHandler");

    TeleManager* pManager = reinterpret_cast<TeleManager*>(pUserData);
    SAL_WARN_IF( !pManager, "tubes", "TeleManager_AccountManagerReadyHandler: no manager");
    if (!pManager)
        return;

    // Hack
    // pManager->setAccountManagerReadyHandlerInvoked( true);
    g_timeout_add_seconds( 2, caps_hack_timeout_cb, pManager);

    GError* pError = NULL;
    gboolean bPrepared = tp_proxy_prepare_finish( pSourceObject, pResult, &pError);
    SAL_WARN_IF( !bPrepared, "tubes", "TeleManager_AccountManagerReadyHandler: not prepared");
    if (!bPrepared || pError)
    {
        SAL_WARN_IF( pError, "tubes", "TeleManager_AccountManagerReadyHandler: error: " << pError->message);
        g_error_free( pError);
    }

    pManager->setAccountManagerReady( bPrepared);
}


TeleManager::TeleManager( bool bCreateOwnGMainLoop )
    :
        mbChannelReadyHandlerInvoked( false)
{
    // The glib object types need to be initialized, else we aren't going
    // anywhere.
    g_type_init();

    MutexGuard aGuard( GetMutex());
    ++nRefCount;
    if (!pImpl)
        pImpl = new TeleManagerImpl;

    // We need a main loop, else no callbacks.
    /* TODO: could the loop be run in another thread? */
    if (bCreateOwnGMainLoop && !pImpl->mpLoop)
        pImpl->mpLoop = g_main_loop_new( NULL, FALSE);
}


TeleManager::~TeleManager()
{
    MutexGuard aGuard( GetMutex());
    if (!--nRefCount)
    {
        disconnect();

        delete pImpl;
        pImpl = NULL;
    }
}

TeleManager *
TeleManager::get()
{
    MutexGuard aGuard( GetAnotherMutex());
    if (!pSingleton)
        pSingleton = new TeleManager();

    nAnotherRefCount++;
    return pSingleton;
}

void
TeleManager::unref()
{
    MutexGuard aGuard( GetAnotherMutex());
    if (nAnotherRefCount && --nAnotherRefCount == 0) {
        delete pSingleton;
        pSingleton = NULL;
    }
}


bool TeleManager::createAccountManager()
{
    INFO_LOGGER( "TeleManager::createAccountManager");

    MutexGuard aGuard( GetMutex());

    SAL_INFO_IF( pImpl->mpAccountManager, "tubes", "TeleManager::createAccountManager: already connected");
    if (pImpl->mpAccountManager)
        return true;

    GError* pError = NULL;
    TpDBusDaemon *pDBus = tp_dbus_daemon_dup( &pError);
    SAL_WARN_IF( !pDBus, "tubes", "TeleManager::createAccountManager: no dbus daemon");
    if (!pDBus || pError)
    {
        SAL_WARN_IF( pError, "tubes", "TeleManager::createAccountManager: dbus daemon error: " << pError->message);
        g_error_free( pError);
        return false;
    }

    pImpl->mpFactory = tp_automatic_client_factory_new( pDBus);
    g_object_unref( pDBus);
    SAL_WARN_IF( !pImpl->mpFactory, "tubes", "TeleManager::createAccountManager: no client factory");
    if (!pImpl->mpFactory)
        return false;

    TpAccountManager* pAccountManager = tp_account_manager_new_with_factory (
        TP_SIMPLE_CLIENT_FACTORY (pImpl->mpFactory));
    tp_account_manager_set_default( pAccountManager);

    /* Takes our ref. */
    pImpl->mpAccountManager = pAccountManager;

    pImpl->mpContactList = new ContactList(pAccountManager);

    return true;
}

bool TeleManager::registerClients()
{
    INFO_LOGGER( "TeleManager::registerClients");

    MutexGuard aGuard( GetMutex());

    /* TODO: also check whether client could be registered and retry if not? */
    SAL_INFO_IF( pImpl->mpClient && pImpl->mpFileTransferClient, "tubes", "TeleManager::registerClients: already registered");
    if (pImpl->mpClient && pImpl->mpFileTransferClient)
        return true;

    pImpl->mpClient = tp_simple_handler_new_with_factory(
            TP_SIMPLE_CLIENT_FACTORY (pImpl->mpFactory), // factory
            FALSE,                          // bypass_approval
            FALSE,                          // requests
            getFullClientName().getStr(),   // name
            FALSE,                          // uniquify
            &TeleManager::DBusChannelHandler, // callback
            this,                           // user_data
            NULL                            // destroy
            );
    SAL_WARN_IF( !pImpl->mpClient, "tubes", "TeleManager::registerClients: no client");
    if (!pImpl->mpClient)
        return false;

    // Setup client handler for buddy channels with our service.
    tp_base_client_take_handler_filter( pImpl->mpClient,
            tp_asv_new(
                TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_DBUS_TUBE,
                TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
                TP_PROP_CHANNEL_TYPE_DBUS_TUBE_SERVICE_NAME, G_TYPE_STRING, getFullServiceName().getStr(),
                NULL));

    /* TODO: setup filters for LibreOfficeCalc, LibreOfficeWriter, ... */

    // Setup client handler for MUC channels with our service.
    tp_base_client_take_handler_filter( pImpl->mpClient,
            tp_asv_new(
                TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_DBUS_TUBE,
                TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_ROOM,
                TP_PROP_CHANNEL_TYPE_DBUS_TUBE_SERVICE_NAME, G_TYPE_STRING, getFullServiceName().getStr(),
                NULL));

    GError* pError = NULL;
    if (!tp_base_client_register( pImpl->mpClient, &pError))
    {
        SAL_WARN( "tubes", "TeleManager::registerClients: error registering client handler: " << pError->message);
        g_error_free( pError);
        return false;
    }

    SAL_INFO( "tubes", "TeleManager::registerClients: bus name: " << tp_base_client_get_bus_name( pImpl->mpClient));
    SAL_INFO( "tubes", "TeleManager::registerClients: object path: " << tp_base_client_get_object_path( pImpl->mpClient));

    /* Register a second "head" for incoming file transfers. This uses a more
     * specific filter than Empathy's handler by matching on the file
     * transfer's ServiceName property, and uses bypass_approval to ensure the
     * user isn't prompted before the channel gets passed to us.
     */
    pImpl->mpFileTransferClient = tp_simple_handler_new_with_factory (
            TP_SIMPLE_CLIENT_FACTORY( pImpl->mpFactory),            // factory
            TRUE,                                           // bypass_approval
            FALSE,                                          // requests
            getFullClientName().getStr(),                   // name
            TRUE,                                           // uniquify to get a different bus name to the main client, above
            TeleManager_FileTransferHandler,                // callback
            this,                                           // user_data
            NULL                                            // destroy
            );
    tp_base_client_take_handler_filter( pImpl->mpFileTransferClient,
            tp_asv_new(
                TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER,
                TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
                TP_PROP_CHANNEL_TYPE_FILE_TRANSFER_DESCRIPTION, G_TYPE_STRING, getFullServiceName().getStr(),
                NULL));

    if (!tp_base_client_register( pImpl->mpFileTransferClient, &pError))
    {
        /* This shouldn't fail if registering the main handler succeeded */
        SAL_WARN( "tubes", "TeleManager::registerClients: error registering file transfer handler: " << pError->message);
        g_error_free( pError);
        return false;
    }

    return true;
}


/* TODO: factor out common code with startBuddySession() */
TeleConference* TeleManager::startGroupSession( TpAccount *pAccount,
                                     const rtl::OUString& rUConferenceRoom,
                                     const rtl::OUString& rUConferenceServer )
{
    INFO_LOGGER( "TeleManager::startGroupSession");

    OString aSessionId( TeleManager::createUuid());

    /* FIXME: does this work at all _creating_ a MUC? */
    // Use conference and server if given, else create conference.
    OString aConferenceRoom( OUStringToOString( rUConferenceRoom, RTL_TEXTENCODING_UTF8));
    OString aConferenceServer( OUStringToOString( rUConferenceServer, RTL_TEXTENCODING_UTF8));
    OStringBuffer aBuf(64);
    if (!aConferenceRoom.isEmpty() && !aConferenceServer.isEmpty())
        aBuf.append( aConferenceRoom).append( '@').append( aConferenceServer);
    else
    {
        aBuf.append( aSessionId);
        if (!aConferenceServer.isEmpty())
            aBuf.append( '@').append( aConferenceServer);
        /* FIXME: else? bail out? we have only a session ID without server then */
    }
    OString aTarget( aBuf.makeStringAndClear());

    SAL_INFO( "tubes", "TeleManager::startGroupSession: creating channel request from "
            << tp_account_get_path_suffix( pAccount ) << " to " << aTarget.getStr() );

    // MUC request
    GHashTable* pRequest = tp_asv_new(
            TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_DBUS_TUBE,
            TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, TP_TYPE_HANDLE, TP_HANDLE_TYPE_ROOM,
            TP_PROP_CHANNEL_TARGET_ID, G_TYPE_STRING, aTarget.getStr(),
            TP_PROP_CHANNEL_TYPE_DBUS_TUBE_SERVICE_NAME, G_TYPE_STRING, getFullServiceName().getStr(),
            NULL);

    TpAccountChannelRequest * pChannelRequest = tp_account_channel_request_new(
            pAccount, pRequest, TP_USER_ACTION_TIME_NOT_USER_ACTION);
    SAL_WARN_IF( !pChannelRequest, "tubes", "TeleManager::startGroupSession: no channel");
    if (!pChannelRequest)
    {
        g_hash_table_unref( pRequest);
        return NULL;
    }

    setChannelReadyHandlerInvoked( false);

    TeleConference* pConference = new TeleConference( this, NULL, NULL );

    tp_account_channel_request_create_and_handle_channel_async(
            pChannelRequest, NULL, TeleManager_ChannelReadyHandler, pConference);

    iterateLoop( &TeleManager::isChannelReadyHandlerInvoked);

    g_object_unref( pChannelRequest);
    g_hash_table_unref( pRequest);

    if (!pConference->getChannel() || !pConference->isTubeOpen())
        return NULL;

    return pConference;
}


void TeleManager::ensureLegacyChannel( TpAccount* pAccount, TpContact* pBuddy )
{
    /* This is a workaround for a Telepathy bug.
     * <https://bugs.freedesktop.org/show_bug.cgi?id=47760>. The first time you
     * request a tube to a contact on an account, you actually get two channels
     * back: the tube you asked for, along with a legacy Channel.Type.Tubes
     * object. This breaks create_and_handle_channel_async(), which expects to
     * only get one channel back.
     *
     * To work around this, we make sure the legacy Tubes channel already
     * exists before we request the channel we actually want. We don't actually
     * have to wait for this request to succeed—we fire it off and forget about
     * it.
     */
    GHashTable* pRequest = tp_asv_new(
            TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_TUBES,
            TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, TP_TYPE_HANDLE, TP_HANDLE_TYPE_CONTACT,
            TP_PROP_CHANNEL_TARGET_ID, G_TYPE_STRING, tp_contact_get_identifier (pBuddy),
            NULL);
    TpAccountChannelRequest* pChannelRequest = tp_account_channel_request_new(
            pAccount, pRequest, TP_USER_ACTION_TIME_NOT_USER_ACTION);
    tp_account_channel_request_ensure_channel_async( pChannelRequest, NULL,
            NULL, NULL, NULL );
    g_object_unref( pChannelRequest );
    g_hash_table_unref( pRequest );
}


/* TODO: factor out common code with startGroupSession() */
TeleConference* TeleManager::startBuddySession( TpAccount *pAccount, TpContact *pBuddy )
{
    INFO_LOGGER( "TeleManager::startBuddySession");

    ensureLegacyChannel( pAccount, pBuddy );

    const char *pIdentifier = tp_contact_get_identifier( pBuddy);
    SAL_INFO( "tubes", "TeleManager::startBuddySession: creating channel request from "
            << tp_account_get_path_suffix( pAccount)
            << " to " << pIdentifier);

    GHashTable* pRequest = tp_asv_new(
            TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_DBUS_TUBE,
            TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, TP_TYPE_HANDLE, TP_HANDLE_TYPE_CONTACT,
            TP_PROP_CHANNEL_TARGET_ID, G_TYPE_STRING, pIdentifier,
            TP_PROP_CHANNEL_TYPE_DBUS_TUBE_SERVICE_NAME, G_TYPE_STRING, getFullServiceName().getStr(),
            NULL);

    TpAccountChannelRequest * pChannelRequest = tp_account_channel_request_new(
            pAccount, pRequest, TP_USER_ACTION_TIME_NOT_USER_ACTION);
    SAL_WARN_IF( !pChannelRequest, "tubes", "TeleManager::startBuddySession: no channel");
    if (!pChannelRequest)
    {
        g_hash_table_unref( pRequest);
        return NULL;
    }

    setChannelReadyHandlerInvoked( false);

    TeleConference* pConference = new TeleConference( this, NULL, NULL );

    tp_account_channel_request_create_and_handle_channel_async(
            pChannelRequest, NULL, TeleManager_ChannelReadyHandler, pConference );

    iterateLoop( &TeleManager::isChannelReadyHandlerInvoked);

    g_object_unref( pChannelRequest);
    g_hash_table_unref( pRequest);

    if (!pConference->getChannel() || !pConference->isTubeOpen())
        return NULL;

    return pConference;
}

void TeleManager::prepareAccountManager()
{
    INFO_LOGGER( "TeleManager::prepareAccountManager");

    MutexGuard aGuard( GetMutex());

    SAL_INFO_IF( pImpl->meAccountManagerStatus == AMS_PREPARED, "tubes",
            "TeleManager::prepareAccountManager: already prepared");
    if (pImpl->meAccountManagerStatus == AMS_PREPARED)
        return;

    SAL_WARN_IF( pImpl->meAccountManagerStatus == AMS_INPREPARATION, "tubes",
            "TeleManager::prepareAccountManager: already in preparation");
    if (pImpl->meAccountManagerStatus == AMS_INPREPARATION)
        return;

    SAL_WARN_IF( pImpl->meAccountManagerStatus != AMS_UNINITIALIZED, "tubes",
            "TeleManager::prepareAccountManager: yet another attempt");

    SAL_WARN_IF( !pImpl->mpAccountManager, "tubes",
            "TeleManager::prepareAccountManager: called before ::connect()");
    if (!pImpl->mpAccountManager)
        return;

    pImpl->meAccountManagerStatus = AMS_INPREPARATION;
    setAccountManagerReadyHandlerInvoked( false);

    tp_proxy_prepare_async( pImpl->mpAccountManager, NULL, TeleManager_AccountManagerReadyHandler, this);

    iterateLoop( &TeleManager::isAccountManagerReadyHandlerInvoked);
}


TeleManager::AccountManagerStatus TeleManager::getAccountManagerStatus() const
{
    return pImpl->meAccountManagerStatus;
}


void TeleManager::setAccountManagerReadyHandlerInvoked( bool b )
{
    pImpl->mbAccountManagerReadyHandlerInvoked = b;
}


bool TeleManager::isAccountManagerReadyHandlerInvoked() const
{
    return pImpl->mbAccountManagerReadyHandlerInvoked;
}

ContactList* TeleManager::getContactList() const
{
    return pImpl->mpContactList;
}

TpAccount* TeleManager::getAccount( const rtl::OString& rAccountID )
{
    INFO_LOGGER( "TeleManager::getMyAccount");

    SAL_WARN_IF( pImpl->meAccountManagerStatus != AMS_PREPARED, "tubes",
            "TeleManager::getMyAccount: Account Manager not prepared");
    if (pImpl->meAccountManagerStatus != AMS_PREPARED)
        return NULL;

    GList* pAccounts = tp_account_manager_get_valid_accounts( pImpl->mpAccountManager);
    SAL_WARN_IF( !pAccounts, "tubes", "TeleManager::getMyAccount: no valid accounts");
    if (!pAccounts)
        return NULL;

    // Find our account to use.
    TpAccount* pAccount = NULL;
    for (GList* pA = pAccounts; pA; pA = pA->next)
    {
        TpAccount* pAcc = TP_ACCOUNT( pA->data);
        const gchar* pID = tp_account_get_normalized_name( pAcc);
        if (pID && rAccountID == pID)
        {
            pAccount = pAcc;
            break;  // for
        }
    }
    g_list_free( pAccounts);

    SAL_WARN_IF( !pAccount, "tubes", "TeleManager::getMyAccount: no account");
    if (!pAccount)
        return NULL;

    return pAccount;
}

void TeleManager::disconnect()
{
    INFO_LOGGER( "TeleManager::disconnect");

    if (!pImpl->mpClient)
        return;

    tp_base_client_unregister( pImpl->mpClient);
    pImpl->mpClient = NULL;

    tp_base_client_unregister( pImpl->mpFileTransferClient);
    pImpl->mpFileTransferClient = NULL;
}


void TeleManager::setAccountManagerReady( bool bPrepared)
{
    pImpl->meAccountManagerStatus = (bPrepared ? AMS_PREPARED : AMS_UNPREPARABLE);
}


rtl::OString TeleManager::getFullClientName()
{
    OStringBuffer aBuf(64);
    aBuf.append( RTL_CONSTASCII_STRINGPARAM( LIBO_CLIENT_SUFFIX)).append( aNameSuffix);
    return aBuf.makeStringAndClear();
}


rtl::OString TeleManager::getFullServiceName()
{
    OStringBuffer aBuf(64);
    aBuf.append( RTL_CONSTASCII_STRINGPARAM( LIBO_DTUBE_SERVICE)).append( aNameSuffix);
    return aBuf.makeStringAndClear();
}


rtl::OString TeleManager::getFullObjectPath()
{
    OStringBuffer aBuf(64);
    aBuf.append( '/').append( RTL_CONSTASCII_STRINGPARAM( LIBO_DTUBE_SERVICE)).append( aNameSuffix);
    OString aStr( aBuf.makeStringAndClear().replace( '.', '/'));
    return aStr;
}


void TeleManager::iterateLoop()
{
    GMainContext* pContext = getMainContext();
    g_main_context_iteration( pContext, TRUE);
}


void TeleManager::iterateLoop( CallBackInvokedFunc pFunc )
{
    GMainContext* pContext = getMainContext();
    while (!(*pFunc)())
    {
        g_main_context_iteration( pContext, TRUE);
    }
}


void TeleManager::iterateLoop( ManagerCallBackInvokedFunc pFunc )
{
    GMainContext* pContext = getMainContext();
    while (!(this->*pFunc)())
    {
        g_main_context_iteration( pContext, TRUE);
    }
}


void TeleManager::iterateLoop( const TeleConference* pConference, ConferenceCallBackInvokedFunc pFunc )
{
    GMainContext* pContext = getMainContext();
    while (!(pConference->*pFunc)())
    {
        g_main_context_iteration( pContext, TRUE);
    }
}


GMainLoop* TeleManager::getMainLoop() const
{
    return pImpl->mpLoop;
}


GMainContext* TeleManager::getMainContext() const
{
    return (pImpl->mpLoop ? g_main_loop_get_context( pImpl->mpLoop) : NULL);
}


// static
rtl::OString TeleManager::createUuid()
{
    sal_uInt8 nId[16];
    rtl_createUuid( nId, 0, sal_True);
    char aBuf[33];
    for (size_t i=0; i<16; ++i)
    {
        snprintf( aBuf+2*i, 3, "%02x", (unsigned char)nId[i]);
    }
    aBuf[32] = 0;
    return rtl::OString( aBuf);
}


// static
Mutex& TeleManager::GetMutex()
{
    static Mutex* pMutex = NULL;
    if (!pMutex)
    {
        MutexGuard aGuard( Mutex::getGlobalMutex());
        if (!pMutex)
            pMutex = new Mutex;
    }
    return *pMutex;
}

Mutex& TeleManager::GetAnotherMutex()
{
    static Mutex* pMutex = NULL;
    if (!pMutex)
    {
        MutexGuard aGuard( Mutex::getGlobalMutex());
        if (!pMutex)
            pMutex = new Mutex;
    }
    return *pMutex;
}


// static
void TeleManager::addSuffixToNames( const char* pName )
{
    aNameSuffix = pName;
}

// ===========================================================================

TeleManagerImpl::TeleManagerImpl()
    :
        mpLoop( NULL),
        mpFactory( NULL),
        mpClient( NULL),
        mpFileTransferClient( NULL),
        mpAccountManager( NULL),
        meAccountManagerStatus( TeleManager::AMS_UNINITIALIZED),
        mbAccountManagerReadyHandlerInvoked( false)
{
}


TeleManagerImpl::~TeleManagerImpl()
{
    if (mpFactory)
        g_object_unref( mpFactory);
    if (mpClient)
        g_object_unref( mpClient);
    if (mpFileTransferClient)
        g_object_unref( mpFileTransferClient);
    if (mpAccountManager)
        g_object_unref( mpAccountManager);
    if (mpContactList)
        delete mpContactList;
    if (mpLoop)
        g_main_loop_unref( mpLoop);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */