summaryrefslogtreecommitdiff
path: root/tubes/source/conference.cxx
blob: ce46cdcf650053138fb76dc8fe50e97c9e005f40 (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
/* -*- 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/conference.hxx>

#include <tubes/collaboration.hxx>
#include <tubes/constants.h>
#include <tubes/file-transfer-helper.h>
#include <tubes/manager.hxx>

#include <gtk/gtk.h>
#include <telepathy-glib/telepathy-glib.h>

#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

class TeleConferenceImpl
{
public:
    guint                   maObjectRegistrationId;
    GDBusConnection*        mpTube;
    bool                    mbTubeOfferedHandlerInvoked : 1;

    TeleConferenceImpl() :
        mpTube( NULL ),
        mbTubeOfferedHandlerInvoked( false )
    {}

    ~TeleConferenceImpl() {}
};

static void TeleConference_MethodCallHandler(
    GDBusConnection*       /*pConnection*/,
    const gchar*           pSender,
    const gchar*           /*pObjectPath*/,
    const gchar*           pInterfaceName,
    const gchar*           pMethodName,
    GVariant*              pParameters,
    GDBusMethodInvocation* pInvocation,
    void*                  pUserData)
{
    INFO_LOGGER_F( "TeleConference_MethodCallHandler");

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

    if (tp_strdiff (pMethodName, LIBO_TUBES_DBUS_MSG_METHOD))
    {
        g_dbus_method_invocation_return_error ( pInvocation,
                G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD,
                "Unknown method '%s' on interface %s",
                pMethodName, pInterfaceName );
        return;
    }

    if (!g_variant_is_of_type ( pParameters, G_VARIANT_TYPE ("(ay)")))
    {
        g_dbus_method_invocation_return_error ( pInvocation,
                G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                "'%s' takes an array of bytes, not %s",
                pMethodName,
                g_variant_get_type_string (pParameters));
        return;
    }

    GVariant *ay;
    g_variant_get( pParameters, "(@ay)", &ay);
    const char* pPacketData = reinterpret_cast<const char*>( g_variant_get_data( ay));
    gsize nPacketSize = g_variant_get_size( ay);

    SAL_WARN_IF( !pPacketData, "tubes", "TeleConference_MethodCallHandler: couldn't get packet data");
    if (!pPacketData)
        return;

    SAL_INFO( "tubes", "TeleConference_MethodCallHandler: received packet from sender "
            << (pSender ? pSender : "(null)") << " with size " << nPacketSize);
    OString aPacket( pPacketData, nPacketSize );
    if (pConference->getCollaboration())
        pConference->getCollaboration()->PacketReceived( aPacket );
    // Master needs to send the packet back to impose ordering,
    // so the slave can execute his command.
    if (pConference->isMaster())
        pConference->sendPacket( aPacket );

    g_dbus_method_invocation_return_value( pInvocation, 0 );

    g_variant_unref( ay);
}


static void TeleConference_ChannelCloseHandler(
        TpChannel*      /*proxy*/,
        const GError*   pError,
        gpointer        pUserData,
        GObject*        /*weak_object*/
        )
{
    INFO_LOGGER_F( "TeleConference_ChannelCloseHandler");

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

    if (pError)
    {
        SAL_WARN( "tubes", "TeleConference_ChannelCloseHandler: entered with error: " << pError->message);
        pConference->finalize();
        return;
    }

    pConference->finalize();
}


static void TeleConference_TubeOfferedHandler(
        GObject*      pSource,
        GAsyncResult* pResult,
        gpointer      pUserData)
{
    INFO_LOGGER_F( "TeleConference_TubeOfferedHandler");

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

    pConference->setTubeOfferedHandlerInvoked( true);

    TpDBusTubeChannel* pChannel = TP_DBUS_TUBE_CHANNEL( pSource);
    GError* pError = NULL;
    GDBusConnection* pTube = tp_dbus_tube_channel_offer_finish(
            pChannel, pResult, &pError);

    // "can't find contact ... presence" means contact is not a contact.
    /* FIXME: detect and handle */
    SAL_WARN_IF( !pTube, "tubes", "TeleConference_TubeOfferedHandler: entered with error: " << pError->message);
    if (pError) {
        g_error_free( pError);
        return;
    }

    pConference->setTube( pTube);
}


static void TeleConference_TubeAcceptedHandler(
        GObject*      pSource,
        GAsyncResult* pResult,
        gpointer      pUserData)
{
    INFO_LOGGER_F( "TeleConference_TubeAcceptedHandler");

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

    pConference->setTubeOfferedHandlerInvoked( true);

    TpDBusTubeChannel* pChannel = TP_DBUS_TUBE_CHANNEL( pSource);
    GError* pError = NULL;
    GDBusConnection* pTube = tp_dbus_tube_channel_accept_finish(
            pChannel, pResult, &pError);

    SAL_WARN_IF( !pTube, "tubes", "TeleConference_TubeAcceptedHandler: entered with error: " << pError->message);
    if (pError) {
        g_error_free( pError);
        return;
    }
    GHashTable* pParameters = tp_dbus_tube_channel_get_parameters( pChannel);
    const char* sUuid = tp_asv_get_string( pParameters, LIBO_TUBES_UUID);
    pConference->setUuid( OString( sUuid));

    pConference->setTube( pTube);
}


TeleConference::TeleConference( TpAccount* pAccount,
        TpDBusTubeChannel* pChannel, const OString sUuid, bool bMaster )
    :
        mpCollaboration( NULL ),
        mpAccount( NULL ),
        mpChannel( NULL ),
        msUuid( sUuid ),
        mbMaster( bMaster ),
        pImpl( new TeleConferenceImpl() )
{
    setChannel( pAccount, pChannel );
}


TeleConference::~TeleConference()
{
    // We're destructed from finalize()
    delete pImpl;
}

static void channel_closed_cb( TpChannel *channel, gpointer user_data, GObject * /* weak_object */ )
{
    Collaboration* pCollaboration = reinterpret_cast<Collaboration*> (user_data);
    if (TeleManager::existsCollaboration( pCollaboration ))
    {
        GtkWidget *dialog = gtk_message_dialog_new( NULL, static_cast<GtkDialogFlags> (0),
                GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE,
                "Contact %s lost, you'll now be working locally.",
                tp_contact_get_alias (tp_channel_get_target_contact (channel)) );
        g_signal_connect_swapped (dialog, "response",
                G_CALLBACK (gtk_widget_destroy), dialog);
        gtk_widget_show_all (dialog);

        pCollaboration->EndCollaboration();
    }
}


void TeleConference::setChannel( TpAccount *pAccount, TpDBusTubeChannel* pChannel )
{
    OSL_ENSURE( !mpChannel, "TeleConference::setChannel: already have channel");
    if (mpChannel)
        g_object_unref( mpChannel);
    if (mpAccount)
        g_object_unref( mpAccount);

    mpChannel = pChannel;
    if (mpChannel)
        g_object_ref( mpChannel);

    mpAccount = pAccount;
    if (mpAccount)
        g_object_ref( mpAccount);
}


bool TeleConference::spinUntilTubeEstablished()
{
    while (!isTubeOfferedHandlerInvoked())
    {
        g_main_context_iteration( NULL, TRUE );
    }

    bool bOpen = pImpl->mpTube != NULL;
    SAL_INFO( "tubes", "TeleConference::spinUntilTubeEstablished: tube open: " << bOpen);
    return bOpen;
}


bool TeleConference::acceptTube()
{
    INFO_LOGGER( "TeleConference::acceptTube");

    SAL_WARN_IF( !mpChannel, "tubes", "TeleConference::acceptTube: no channel setup");
    SAL_WARN_IF( pImpl->mpTube, "tubes", "TeleConference::acceptTube: already tubed");
    if (!mpChannel || pImpl->mpTube)
        return false;

    tp_dbus_tube_channel_accept_async( mpChannel,
            TeleConference_TubeAcceptedHandler,
            this);
    return spinUntilTubeEstablished();
}


bool TeleConference::offerTube()
{
    INFO_LOGGER( "TeleConference::offerTube");

    OSL_ENSURE( mpChannel, "TeleConference::offerTube: no channel");
    if (!mpChannel)
        return false;

    GHashTable* pParameters = tp_asv_new (
            LIBO_TUBES_UUID, G_TYPE_STRING, msUuid.getStr(),
            NULL);

    tp_dbus_tube_channel_offer_async(
            mpChannel,
            pParameters,
            TeleConference_TubeOfferedHandler,
            this);

    return spinUntilTubeEstablished();
}


bool TeleConference::setTube( GDBusConnection* pTube)
{
    INFO_LOGGER( "TeleConference::setTube");

    OSL_ENSURE( !pImpl->mpTube, "TeleConference::setTube: already tubed");

    pImpl->mpTube = pTube;

    GDBusNodeInfo *introspection_data;
    static const GDBusInterfaceVTable interface_vtable =
    {
        TeleConference_MethodCallHandler,
        NULL,
        NULL,
        { NULL },
    };
    static const gchar introspection_xml[] =
        "<node>"
        "  <interface name='" LIBO_TUBES_DBUS_INTERFACE "'>"
        "    <method name='" LIBO_TUBES_DBUS_MSG_METHOD "'>"
        "      <arg type='ay' name='packet' direction='in'/>"
        "    </method>"
        "  </interface>"
        "</node>";

    introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
    g_assert (introspection_data != NULL);

    pImpl->maObjectRegistrationId = g_dbus_connection_register_object( pImpl->mpTube,
            LIBO_TUBES_DBUS_PATH, introspection_data->interfaces[0],
            &interface_vtable, this, NULL, NULL);
    g_assert (pImpl->maObjectRegistrationId > 0);

    g_dbus_node_info_unref (introspection_data);

    return true;
}

void TeleConference::setTubeOfferedHandlerInvoked( bool b )
{
    pImpl->mbTubeOfferedHandlerInvoked = b;
}

bool TeleConference::isTubeOfferedHandlerInvoked() const
{
    return pImpl->mbTubeOfferedHandlerInvoked;
}

bool TeleConference::isReady() const
{
    return mpChannel && pImpl->mpTube;
}

void TeleConference::close()
{
    INFO_LOGGER( "TeleConference::close");

    if (mpChannel)
        tp_cli_channel_call_close( TP_CHANNEL( mpChannel), 5000, TeleConference_ChannelCloseHandler, this, NULL, NULL);
    else
        finalize();
}


void TeleConference::finalize()
{
    INFO_LOGGER( "TeleConference::finalize");

    TeleManager::unregisterDemoConference( this );

    if (mpChannel)
    {
        g_object_unref( mpChannel);
        mpChannel = NULL;
    }

    if (mpAccount)
    {
        g_object_unref( mpAccount);
        mpAccount = NULL;
    }

    if (pImpl->mpTube)
    {
        g_dbus_connection_unregister_object( pImpl->mpTube, pImpl->maObjectRegistrationId);
        g_dbus_connection_close_sync( pImpl->mpTube, NULL, NULL );
        g_object_unref( pImpl->mpTube );
        pImpl->mpTube = NULL;
    }

    //! *this gets destructed here!
}


bool TeleConference::sendPacket( const OString& rPacket )
{
    INFO_LOGGER( "TeleConference::sendPacket");

    if (!mpChannel && !pImpl->mpTube)
    {
        TeleManager::broadcastPacket( rPacket );
        return true;
    }

    SAL_WARN_IF( !pImpl->mpTube, "tubes", "TeleConference::sendPacket: no tube");
    if (!pImpl->mpTube)
        return false;

    /* FIXME: in GLib 2.32 we can use g_variant_new_fixed_array(). It does
     * essentially this.
     */
    void* pData = g_memdup( rPacket.getStr(), rPacket.getLength() );
    GVariant *pParameters = g_variant_new_from_data( G_VARIANT_TYPE("(ay)"),
            pData, rPacket.getLength(),
            FALSE,
            g_free, pData);

    g_dbus_connection_call( pImpl->mpTube,
            NULL, /* bus name; in multi-user case we'd address this to the master. */
            LIBO_TUBES_DBUS_PATH,
            LIBO_TUBES_DBUS_INTERFACE,
            LIBO_TUBES_DBUS_MSG_METHOD,
            pParameters, /* consumes the floating reference */
            NULL,
            G_DBUS_CALL_FLAGS_NONE,
            -1, NULL, NULL, NULL);

    // If we started the session, we can execute commands immediately.
    if (mbMaster && mpCollaboration)
        mpCollaboration->PacketReceived( rPacket );

    return true;
}

bool TeleConference::isMaster() const
{
    return mbMaster;
}

Collaboration* TeleConference::getCollaboration() const
{
    return mpCollaboration;
}

void TeleConference::setCollaboration( Collaboration* pCollaboration )
{
    mpCollaboration = pCollaboration;
    if (mpChannel)
    {
        GError *error = NULL;
        if (!tp_cli_channel_connect_to_closed( TP_CHANNEL (mpChannel),
                    channel_closed_cb, mpCollaboration, NULL, NULL, &error ))
        {
            SAL_WARN( "tubes", "Error when connecting to signal closed: " << error->message );
            g_error_free (error);
        }
    }
}

void TeleConference::invite( TpContact *pContact )
{
    INFO_LOGGER( "TeleConference::invite" );
    TpHandle aHandle = tp_contact_get_handle( pContact );
    GArray handles = { reinterpret_cast<gchar *> (&aHandle), 1 };
    tp_cli_channel_interface_group_call_add_members( TP_CHANNEL( mpChannel ),
            -1, &handles, NULL, NULL, NULL, NULL, NULL );
}

namespace {
class SendFileRequest {
public:
    SendFileRequest( TeleConference::FileSentCallback pCallback, void* pUserData, const char* sUuid )
        : mpCallback(pCallback)
        , mpUserData(pUserData)
        , msUuid(sUuid)
    {}

    TeleConference::FileSentCallback    mpCallback;
    void*                               mpUserData;
    const char*                         msUuid;
};
}

static void TeleConference_TransferDone( EmpathyFTHandler *handler, TpFileTransferChannel *, gpointer user_data)
{
    SendFileRequest *request = reinterpret_cast<SendFileRequest *>(user_data);

    if (request->mpCallback)
        request->mpCallback(true, request->mpUserData);
    delete request;
    g_object_unref (handler);
}

static void TeleConference_TransferError( EmpathyFTHandler *handler, const GError *error, gpointer user_data)
{
    SendFileRequest *request = reinterpret_cast<SendFileRequest *>(user_data);

    SAL_INFO( "tubes", "TeleConference_TransferError: " << error->message);

    if (request->mpCallback)
        request->mpCallback(false, request->mpUserData);
    delete request;
    g_object_unref (handler);
}

static void TeleConference_FTReady( EmpathyFTHandler *handler, GError *error, gpointer user_data)
{
    SendFileRequest *request = reinterpret_cast<SendFileRequest *>(user_data);

    if ( error != 0 )
    {
        if (request->mpCallback)
            request->mpCallback(error == 0, request->mpUserData);
        delete request;
        g_object_unref (handler);
    }
    else
    {
        g_signal_connect(handler, "transfer-done",
            G_CALLBACK (TeleConference_TransferDone), request);
        g_signal_connect(handler, "transfer-error",
            G_CALLBACK (TeleConference_TransferError), request);
        empathy_ft_handler_set_service_name(handler, TeleManager::getFullServiceName().getStr());
        empathy_ft_handler_set_description(handler, request->msUuid);
        empathy_ft_handler_start_transfer(handler);
    }
}

// TODO: move sending file to TeleManager
extern void TeleManager_fileReceived( const OUString&, const OString& );
void TeleConference::sendFile( TpContact* pContact, const OUString& localUri, FileSentCallback pCallback, void* pUserData)
{
    INFO_LOGGER( "TeleConference::sendFile");

    if (!pContact)
    {
        // used in demo mode
        TeleManager_fileReceived( localUri, "demo" );
        return;
    }

    SAL_WARN_IF( ( !mpAccount || !mpChannel), "tubes",
        "can't send a file before the tube is set up");
    if ( !mpAccount || !mpChannel)
        return;

    GFile *pSource = g_file_new_for_uri(
        OUStringToOString( localUri, RTL_TEXTENCODING_UTF8).getStr() );
    SendFileRequest *pReq = new SendFileRequest( pCallback, pUserData, msUuid.getStr() );

    empathy_ft_handler_new_outgoing( mpAccount,
        pContact,
        pSource,
        0,
        TeleConference_FTReady, pReq);
}

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