~ubuntu-branches/ubuntu/trusty/tomahawk/trusty-proposed

« back to all changes in this revision

Viewing changes to src/accounts/twitter/sip/TwitterSip.cpp

  • Committer: Package Import Robot
  • Author(s): Harald Sitter
  • Date: 2013-03-07 21:50:13 UTC
  • Revision ID: package-import@ubuntu.com-20130307215013-6gdjkdds7i9uenvs
Tags: upstream-0.6.0+dfsg
ImportĀ upstreamĀ versionĀ 0.6.0+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* === This file is part of Tomahawk Player - <http://tomahawk-player.org> ===
 
2
 *
 
3
 *   Copyright 2010-2011, Christian Muehlhaeuser <muesli@tomahawk-player.org>
 
4
 *   Copyright 2011, Leo Franchi <lfranchi@kde.org>
 
5
 *   Copyright 2010-2011, Jeff Mitchell <jeff@tomahawk-player.org>
 
6
 *
 
7
 *   Tomahawk is free software: you can redistribute it and/or modify
 
8
 *   it under the terms of the GNU General Public License as published by
 
9
 *   the Free Software Foundation, either version 3 of the License, or
 
10
 *   (at your option) any later version.
 
11
 *
 
12
 *   Tomahawk is distributed in the hope that it will be useful,
 
13
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 
15
 *   GNU General Public License for more details.
 
16
 *
 
17
 *   You should have received a copy of the GNU General Public License
 
18
 *   along with Tomahawk. If not, see <http://www.gnu.org/licenses/>.
 
19
 */
 
20
 
 
21
#include "TwitterSip.h"
 
22
 
 
23
#include "utils/TomahawkUtils.h"
 
24
#include "TomahawkSettings.h"
 
25
#include "database/Database.h"
 
26
#include "database/DatabaseImpl.h"
 
27
#include "network/Servent.h"
 
28
#include "Source.h"
 
29
 
 
30
#include "utils/Logger.h"
 
31
#include "accounts/twitter/TomahawkOAuthTwitter.h"
 
32
#include "accounts/twitter/TwitterAccount.h"
 
33
 
 
34
#include <QTweetLib/qtweetaccountverifycredentials.h>
 
35
#include <QTweetLib/qtweetuser.h>
 
36
#include <QTweetLib/qtweetstatus.h>
 
37
#include <QTweetLib/qtweetusershow.h>
 
38
 
 
39
#include <QtPlugin>
 
40
#include <QDateTime>
 
41
#include <QRegExp>
 
42
#include <QNetworkAccessManager>
 
43
#include <QNetworkRequest>
 
44
#include <QNetworkReply>
 
45
#include <QStringList>
 
46
 
 
47
static QString s_gotTomahawkRegex = QString( "^(@[a-zA-Z0-9]+ )?(Got Tomahawk\\?) (\\{[a-fA-F0-9\\-]+\\}) (.*)$" );
 
48
 
 
49
TwitterSipPlugin::TwitterSipPlugin( Tomahawk::Accounts::Account* account )
 
50
    : SipPlugin( account )
 
51
    , m_checkTimer( this )
 
52
    , m_connectTimer( this )
 
53
    , m_dmPollTimer( this )
 
54
    , m_cachedFriendsSinceId( 0 )
 
55
    , m_cachedMentionsSinceId( 0 )
 
56
    , m_cachedDirectMessagesSinceId( 0 )
 
57
    , m_cachedPeers()
 
58
    , m_keyCache()
 
59
    , m_state( Tomahawk::Accounts::Account::Disconnected )
 
60
{
 
61
    qDebug() << Q_FUNC_INFO;
 
62
 
 
63
    connect( account, SIGNAL( nowAuthenticated( const QWeakPointer< TomahawkOAuthTwitter > &, const QTweetUser & ) ), SLOT( accountAuthenticated( const QWeakPointer< TomahawkOAuthTwitter > &, const QTweetUser & ) ) );
 
64
 
 
65
    m_configuration = account->configuration();
 
66
    qDebug() << "SIP configuration:" << m_configuration << m_configuration[ "cachedpeers" ];
 
67
    if ( Database::instance()->impl()->dbid() != m_account->configuration()[ "saveddbid" ].toString() )
 
68
    {
 
69
        m_configuration[ "cachedpeers" ] = QVariantHash();
 
70
        m_configuration[ "saveddbid" ] = Database::instance()->impl()->dbid();
 
71
        syncConfig();
 
72
    }
 
73
 
 
74
    m_checkTimer.setInterval( 180000 );
 
75
    m_checkTimer.setSingleShot( false );
 
76
    connect( &m_checkTimer, SIGNAL( timeout() ), SLOT( checkTimerFired() ) );
 
77
 
 
78
    m_dmPollTimer.setInterval( 60000 );
 
79
    m_dmPollTimer.setSingleShot( false );
 
80
    connect( &m_dmPollTimer, SIGNAL( timeout() ), SLOT( pollDirectMessages() ) );
 
81
 
 
82
    m_connectTimer.setInterval( 180000 );
 
83
    m_connectTimer.setSingleShot( false );
 
84
    connect( &m_connectTimer, SIGNAL( timeout() ), SLOT( connectTimerFired() ) );
 
85
}
 
86
 
 
87
 
 
88
bool
 
89
TwitterSipPlugin::isValid() const
 
90
{
 
91
    return m_account->enabled() && m_account->isAuthenticated() && !m_cachedTwitterAuth.isNull();
 
92
}
 
93
 
 
94
 
 
95
Tomahawk::Accounts::Account::ConnectionState
 
96
TwitterSipPlugin::connectionState() const
 
97
{
 
98
    return m_state;
 
99
}
 
100
 
 
101
QString
 
102
TwitterSipPlugin::inviteString() const
 
103
{
 
104
    return tr( "Enter Twitter username" );
 
105
}
 
106
 
 
107
 
 
108
void
 
109
TwitterSipPlugin::checkSettings()
 
110
{
 
111
    configurationChanged();
 
112
}
 
113
 
 
114
 
 
115
void
 
116
TwitterSipPlugin::connectPlugin()
 
117
{
 
118
    tDebug() << Q_FUNC_INFO;
 
119
    if ( !m_account->enabled() )
 
120
    {
 
121
        tDebug() << Q_FUNC_INFO << "account isn't enabled";
 
122
        return;
 
123
    }
 
124
 
 
125
    m_cachedPeers = m_configuration[ "cachedpeers" ].toHash();
 
126
    QStringList peerList = m_cachedPeers.keys();
 
127
    qStableSort( peerList.begin(), peerList.end() );
 
128
 
 
129
    if ( !m_account->isAuthenticated() )
 
130
    {
 
131
        tDebug() << Q_FUNC_INFO << "account isn't authenticated, attempting";
 
132
        m_account->authenticate();
 
133
    }
 
134
 
 
135
    m_state = Tomahawk::Accounts::Account::Connecting;
 
136
    emit stateChanged( m_state );
 
137
}
 
138
 
 
139
 
 
140
void
 
141
TwitterSipPlugin::disconnectPlugin()
 
142
{
 
143
    tDebug() << Q_FUNC_INFO;
 
144
    m_checkTimer.stop();
 
145
    m_connectTimer.stop();
 
146
    m_dmPollTimer.stop();
 
147
    if( !m_friendsTimeline.isNull() )
 
148
        delete m_friendsTimeline.data();
 
149
    if( !m_mentions.isNull() )
 
150
        delete m_mentions.data();
 
151
    if( !m_directMessages.isNull() )
 
152
        delete m_directMessages.data();
 
153
    if( !m_directMessageNew.isNull() )
 
154
        delete m_directMessageNew.data();
 
155
    if( !m_directMessageDestroy.isNull() )
 
156
        delete m_directMessageDestroy.data();
 
157
 
 
158
    m_cachedTwitterAuth.clear();
 
159
 
 
160
    m_configuration[ "cachedpeers" ] = m_cachedPeers;
 
161
    syncConfig();
 
162
    m_cachedPeers.empty();
 
163
    m_state = Tomahawk::Accounts::Account::Disconnected;
 
164
    emit stateChanged( m_state );
 
165
}
 
166
 
 
167
void
 
168
TwitterSipPlugin::accountAuthenticated( const QWeakPointer< TomahawkOAuthTwitter > &twitterAuth, const QTweetUser &user )
 
169
{
 
170
    Q_UNUSED( user );
 
171
 
 
172
    if ( !m_account->enabled() || !m_account->isAuthenticated() )
 
173
        return;
 
174
 
 
175
    m_cachedTwitterAuth = twitterAuth;
 
176
 
 
177
    m_friendsTimeline = QWeakPointer<QTweetFriendsTimeline>( new QTweetFriendsTimeline( m_cachedTwitterAuth.data(), this ) );
 
178
    m_mentions = QWeakPointer<QTweetMentions>( new QTweetMentions( m_cachedTwitterAuth.data(), this ) );
 
179
    m_directMessages = QWeakPointer<QTweetDirectMessages>( new QTweetDirectMessages( m_cachedTwitterAuth.data(), this ) );
 
180
    m_directMessageNew = QWeakPointer<QTweetDirectMessageNew>( new QTweetDirectMessageNew( m_cachedTwitterAuth.data(), this ) );
 
181
    m_directMessageDestroy = QWeakPointer<QTweetDirectMessageDestroy>( new QTweetDirectMessageDestroy( m_cachedTwitterAuth.data(), this ) );
 
182
    connect( m_friendsTimeline.data(), SIGNAL( parsedStatuses(const QList< QTweetStatus > &) ), SLOT( friendsTimelineStatuses(const QList<QTweetStatus> &) ) );
 
183
    connect( m_mentions.data(), SIGNAL( parsedStatuses(const QList< QTweetStatus > &) ), SLOT( mentionsStatuses(const QList<QTweetStatus> &) ) );
 
184
    connect( m_directMessages.data(), SIGNAL( parsedDirectMessages(const QList<QTweetDMStatus> &)), SLOT( directMessages(const QList<QTweetDMStatus> &) ) );
 
185
    connect( m_directMessageNew.data(), SIGNAL( parsedDirectMessage(const QTweetDMStatus &)), SLOT( directMessagePosted(const QTweetDMStatus &) ) );
 
186
    connect( m_directMessageNew.data(), SIGNAL( error(QTweetNetBase::ErrorCode, const QString &) ), SLOT( directMessagePostError(QTweetNetBase::ErrorCode, const QString &) ) );
 
187
    connect( m_directMessageDestroy.data(), SIGNAL( parsedDirectMessage(const QTweetDMStatus &) ), SLOT( directMessageDestroyed(const QTweetDMStatus &) ) );
 
188
    m_state = Tomahawk::Accounts::Account::Connected;
 
189
    emit stateChanged( m_state );
 
190
    QStringList peerList = m_cachedPeers.keys();
 
191
    qStableSort( peerList.begin(), peerList.end() );
 
192
    registerOffers( peerList );
 
193
    m_connectTimer.start();
 
194
    m_checkTimer.start();
 
195
    m_dmPollTimer.start();
 
196
 
 
197
    QMetaObject::invokeMethod( this, "checkTimerFired", Qt::AutoConnection );
 
198
    QTimer::singleShot( 20000, this, SLOT( connectTimerFired() ) );
 
199
}
 
200
 
 
201
 
 
202
void
 
203
TwitterSipPlugin::checkTimerFired()
 
204
{
 
205
    if ( !isValid() )
 
206
        return;
 
207
 
 
208
    if ( m_cachedFriendsSinceId == 0 )
 
209
        m_cachedFriendsSinceId = m_configuration[ "cachedfriendssinceid" ].toLongLong();
 
210
 
 
211
    qDebug() << "TwitterSipPlugin looking at friends timeline since id " << m_cachedFriendsSinceId;
 
212
 
 
213
    if ( !m_friendsTimeline.isNull() )
 
214
        m_friendsTimeline.data()->fetch( m_cachedFriendsSinceId, 0, 800 );
 
215
 
 
216
    if ( m_cachedMentionsSinceId == 0 )
 
217
        m_cachedMentionsSinceId = m_configuration[ "cachedmentionssinceid" ].toLongLong();
 
218
 
 
219
    qDebug() << "TwitterSipPlugin looking at mentions timeline since id " << m_cachedMentionsSinceId;
 
220
 
 
221
    if ( !m_mentions.isNull() )
 
222
        m_mentions.data()->fetch( m_cachedMentionsSinceId, 0, 800 );
 
223
}
 
224
 
 
225
 
 
226
void
 
227
TwitterSipPlugin::registerOffers( const QStringList &peerList )
 
228
{
 
229
    if ( !isValid() )
 
230
        return;
 
231
 
 
232
    foreach( QString screenName, peerList )
 
233
    {
 
234
        QVariantHash peerData = m_cachedPeers[screenName].toHash();
 
235
 
 
236
        if ( peerData.contains( "onod" ) && peerData["onod"] != Database::instance()->impl()->dbid() )
 
237
        {
 
238
            m_cachedPeers.remove( screenName );
 
239
            m_configuration[ "cachedpeers" ] = m_cachedPeers;
 
240
            syncConfig();
 
241
        }
 
242
 
 
243
        if ( Servent::instance()->connectedToSession( peerData["node"].toString() ) )
 
244
        {
 
245
            peerData["lastseen"] = QDateTime::currentMSecsSinceEpoch();
 
246
            m_cachedPeers[screenName] = peerData;
 
247
            m_configuration[ "cachedpeers" ] = m_cachedPeers;
 
248
            syncConfig();
 
249
            qDebug() << Q_FUNC_INFO << " already connected";
 
250
            continue;
 
251
        }
 
252
        else if ( QDateTime::currentMSecsSinceEpoch() - peerData["lastseen"].toLongLong() > 1209600000 ) // 2 weeks
 
253
        {
 
254
            qDebug() << Q_FUNC_INFO << " aging peer " << screenName << " out of cache";
 
255
            m_cachedPeers.remove( screenName );
 
256
            m_configuration[ "cachedpeers" ] = m_cachedPeers;
 
257
            syncConfig();
 
258
            m_cachedAvatars.remove( screenName );
 
259
            continue;
 
260
        }
 
261
 
 
262
        if ( !peerData.contains( "host" ) || !peerData.contains( "port" ) || !peerData.contains( "pkey" ) )
 
263
        {
 
264
            qDebug() << "TwitterSipPlugin does not have host, port and/or pkey values for " << screenName << " (this is usually *not* a bug or problem but a normal part of the process)";
 
265
            continue;
 
266
        }
 
267
 
 
268
        QMetaObject::invokeMethod( this, "registerOffer", Q_ARG( QString, screenName ), Q_ARG( QVariantHash, peerData ) );
 
269
    }
 
270
}
 
271
 
 
272
 
 
273
void
 
274
TwitterSipPlugin::connectTimerFired()
 
275
{
 
276
    tDebug() << Q_FUNC_INFO << " beginning";
 
277
    if ( !isValid() || m_cachedPeers.isEmpty() )
 
278
    {
 
279
        if ( !isValid() )
 
280
            tDebug() << Q_FUNC_INFO << " is not valid";
 
281
        if ( m_cachedPeers.isEmpty() )
 
282
            tDebug() << Q_FUNC_INFO << " has empty cached peers";
 
283
        return;
 
284
    }
 
285
 
 
286
    tDebug() << Q_FUNC_INFO << " continuing";
 
287
    QString myScreenName = m_configuration[ "screenname" ].toString();
 
288
    QStringList peerList = m_cachedPeers.keys();
 
289
    qStableSort( peerList.begin(), peerList.end() );
 
290
    registerOffers( peerList );
 
291
}
 
292
 
 
293
void
 
294
TwitterSipPlugin::parseGotTomahawk( const QRegExp &regex, const QString &screenName, const QString &text )
 
295
{
 
296
    QString myScreenName = m_configuration[ "screenname" ].toString();
 
297
    qDebug() << "TwitterSipPlugin found an exact matching Got Tomahawk? mention or direct message from user " << screenName << ", now parsing";
 
298
    regex.exactMatch( text );
 
299
    if ( text.startsWith( '@' ) && regex.captureCount() >= 2 && regex.cap( 1 ) != QString( '@' + myScreenName ) )
 
300
    {
 
301
        qDebug() << "TwitterSipPlugin skipping mention because it's directed @someone that isn't us";
 
302
        return;
 
303
    }
 
304
 
 
305
    QString node;
 
306
    for ( int i = 0; i < regex.captureCount(); ++i )
 
307
    {
 
308
        if ( regex.cap( i ) == QString( "Got Tomahawk?" ) )
 
309
        {
 
310
            QString nodeCap = regex.cap( i + 1 );
 
311
            nodeCap.chop( 1 );
 
312
            node = nodeCap.mid( 1 );
 
313
        }
 
314
    }
 
315
    if ( node.isEmpty() )
 
316
    {
 
317
        qDebug() << "TwitterSipPlugin could not parse node out of the tweet";
 
318
        return;
 
319
    }
 
320
    else
 
321
        qDebug() << "TwitterSipPlugin parsed node " << node << " out of the tweet";
 
322
 
 
323
    if ( node == Database::instance()->impl()->dbid() )
 
324
    {
 
325
        qDebug() << "My dbid found; ignoring";
 
326
        return;
 
327
    }
 
328
 
 
329
    QVariantHash peerData;
 
330
    if( m_cachedPeers.contains( screenName ) )
 
331
    {
 
332
        peerData = m_cachedPeers[screenName].toHash();
 
333
        //force a re-send of info but no need to re-register
 
334
        peerData["resend"] = QVariant::fromValue< bool >( true );
 
335
        if ( peerData["node"].toString() != node )
 
336
            peerData["rekey"] = QVariant::fromValue< bool >( true );
 
337
    }
 
338
    peerData["node"] = QVariant::fromValue< QString >( node );
 
339
    QMetaObject::invokeMethod( this, "registerOffer", Q_ARG( QString, screenName ), Q_ARG( QVariantHash, peerData ) );
 
340
}
 
341
 
 
342
void
 
343
TwitterSipPlugin::friendsTimelineStatuses( const QList< QTweetStatus > &statuses )
 
344
{
 
345
    tDebug() << Q_FUNC_INFO;
 
346
    QRegExp regex( s_gotTomahawkRegex, Qt::CaseSensitive, QRegExp::RegExp2 );
 
347
 
 
348
    QHash< QString, QTweetStatus > latestHash;
 
349
    foreach ( QTweetStatus status, statuses )
 
350
    {
 
351
        if ( !regex.exactMatch( status.text() ) )
 
352
            continue;
 
353
 
 
354
        if ( !latestHash.contains( status.user().screenName() ) )
 
355
            latestHash[status.user().screenName()] = status;
 
356
        else
 
357
        {
 
358
            if ( status.id() > latestHash[status.user().screenName()].id() )
 
359
                latestHash[status.user().screenName()] = status;
 
360
        }
 
361
    }
 
362
 
 
363
    foreach( QTweetStatus status, latestHash.values() )
 
364
    {
 
365
        if ( status.id() > m_cachedFriendsSinceId )
 
366
            m_cachedFriendsSinceId = status.id();
 
367
 
 
368
        tDebug() << "TwitterSipPlugin checking mention from " << status.user().screenName() << " with content " << status.text();
 
369
        parseGotTomahawk( regex, status.user().screenName(), status.text() );
 
370
    }
 
371
 
 
372
    m_configuration[ "cachedfriendssinceid" ] = m_cachedFriendsSinceId;
 
373
    syncConfig();
 
374
}
 
375
 
 
376
void
 
377
TwitterSipPlugin::mentionsStatuses( const QList< QTweetStatus > &statuses )
 
378
{
 
379
    tDebug() << Q_FUNC_INFO;
 
380
    QRegExp regex( s_gotTomahawkRegex, Qt::CaseSensitive, QRegExp::RegExp2 );
 
381
 
 
382
    QHash< QString, QTweetStatus > latestHash;
 
383
    foreach ( QTweetStatus status, statuses )
 
384
    {
 
385
        if ( !regex.exactMatch( status.text() ) )
 
386
            continue;
 
387
 
 
388
        if ( !latestHash.contains( status.user().screenName() ) )
 
389
            latestHash[status.user().screenName()] = status;
 
390
        else
 
391
        {
 
392
            if ( status.id() > latestHash[status.user().screenName()].id() )
 
393
                latestHash[status.user().screenName()] = status;
 
394
        }
 
395
    }
 
396
 
 
397
    foreach( QTweetStatus status, latestHash.values() )
 
398
    {
 
399
        if ( status.id() > m_cachedMentionsSinceId )
 
400
            m_cachedMentionsSinceId = status.id();
 
401
 
 
402
        tDebug() << "TwitterSipPlugin checking mention from " << status.user().screenName() << " with content " << status.text();
 
403
        parseGotTomahawk( regex, status.user().screenName(), status.text() );
 
404
    }
 
405
 
 
406
    m_configuration[ "cachedmentionssinceid" ] = m_cachedMentionsSinceId;
 
407
    syncConfig();
 
408
}
 
409
 
 
410
void
 
411
TwitterSipPlugin::pollDirectMessages()
 
412
{
 
413
    if ( !isValid() )
 
414
        return;
 
415
 
 
416
    if ( m_cachedDirectMessagesSinceId == 0 )
 
417
        m_cachedDirectMessagesSinceId = m_configuration[ "cacheddirectmessagessinceid" ].toLongLong();
 
418
 
 
419
    tDebug() << "TwitterSipPlugin looking for direct messages since id " << m_cachedDirectMessagesSinceId;
 
420
 
 
421
    if ( !m_directMessages.isNull() )
 
422
        m_directMessages.data()->fetch( m_cachedDirectMessagesSinceId, 0, 800 );
 
423
}
 
424
 
 
425
void
 
426
TwitterSipPlugin::directMessages( const QList< QTweetDMStatus > &messages )
 
427
{
 
428
    tDebug() << Q_FUNC_INFO;
 
429
 
 
430
    QRegExp regex( s_gotTomahawkRegex, Qt::CaseSensitive, QRegExp::RegExp2 );
 
431
    QString myScreenName = m_configuration[ "screenname" ].toString();
 
432
 
 
433
    QHash< QString, QTweetDMStatus > latestHash;
 
434
    foreach ( QTweetDMStatus status, messages )
 
435
    {
 
436
        if ( !regex.exactMatch( status.text() ) )
 
437
        {
 
438
            QStringList splitList = status.text().split(':');
 
439
            if ( splitList.length() != 5 )
 
440
                continue;
 
441
            if ( splitList[0] != "TOMAHAWKPEER" )
 
442
                continue;
 
443
            if ( !splitList[1].startsWith( "Host=" ) || !splitList[2].startsWith( "Port=" ) || !splitList[3].startsWith( "Node=" ) || !splitList[4].startsWith( "PKey=" ) )
 
444
                continue;
 
445
            int port = splitList[2].mid( 5 ).toInt();
 
446
            if ( port == 0 )
 
447
                continue;
 
448
        }
 
449
 
 
450
        if ( !latestHash.contains( status.senderScreenName() ) )
 
451
            latestHash[status.senderScreenName()] = status;
 
452
        else
 
453
        {
 
454
            if ( status.id() > latestHash[status.senderScreenName()].id() )
 
455
                latestHash[status.senderScreenName()] = status;
 
456
        }
 
457
    }
 
458
 
 
459
    foreach( QTweetDMStatus status, latestHash.values() )
 
460
    {
 
461
        qDebug() << "TwitterSipPlugin checking direct message from " << status.senderScreenName() << " with content " << status.text();
 
462
        if ( status.id() > m_cachedDirectMessagesSinceId )
 
463
            m_cachedDirectMessagesSinceId = status.id();
 
464
 
 
465
        if ( regex.exactMatch( status.text() ) )
 
466
            parseGotTomahawk( regex, status.sender().screenName(), status.text() );
 
467
        else
 
468
        {
 
469
            QStringList splitList = status.text().split(':');
 
470
            qDebug() << "TwitterSipPlugin found " << splitList.length() << " parts to the message; the parts are:";
 
471
            foreach( QString part, splitList )
 
472
                qDebug() << part;
 
473
            //validity is checked above
 
474
            int port = splitList[2].mid( 5 ).toInt();
 
475
            QString host = splitList[1].mid( 5 );
 
476
            QString node = splitList[3].mid( 5 );
 
477
            QString pkey = splitList[4].mid( 5 );
 
478
            QStringList splitNode = node.split('*');
 
479
            if ( splitNode.length() != 2 )
 
480
            {
 
481
                qDebug() << "Old-style node info found, ignoring";
 
482
                continue;
 
483
            }
 
484
            qDebug() << "TwitterSipPlugin found a peerstart message from " << status.senderScreenName() << " with host " << host << " and port " << port << " and pkey " << pkey << " and node " << splitNode[0] << " destined for node " << splitNode[1];
 
485
 
 
486
 
 
487
            QVariantHash peerData = ( m_cachedPeers.contains( status.senderScreenName() ) ) ?
 
488
                                                        m_cachedPeers[status.senderScreenName()].toHash() :
 
489
                                                        QVariantHash();
 
490
 
 
491
            peerData["host"] = QVariant::fromValue< QString >( host );
 
492
            peerData["port"] = QVariant::fromValue< int >( port );
 
493
            peerData["pkey"] = QVariant::fromValue< QString >( pkey );
 
494
            peerData["node"] = QVariant::fromValue< QString >( splitNode[0] );
 
495
            peerData["dirty"] = QVariant::fromValue< bool >( true );
 
496
 
 
497
            QMetaObject::invokeMethod( this, "registerOffer", Q_ARG( QString, status.senderScreenName() ), Q_ARG( QVariantHash, peerData ) );
 
498
 
 
499
            if ( Database::instance()->impl()->dbid().startsWith( splitNode[1] ) )
 
500
            {
 
501
                qDebug() << "TwitterSipPlugin found message destined for this node; destroying it";
 
502
                if ( !m_directMessageDestroy.isNull() )
 
503
                    m_directMessageDestroy.data()->destroyMessage( status.id() );
 
504
            }
 
505
        }
 
506
    }
 
507
 
 
508
    m_configuration[ "cacheddirectmessagessinceid" ] = m_cachedDirectMessagesSinceId;
 
509
    syncConfig();
 
510
}
 
511
 
 
512
void
 
513
TwitterSipPlugin::registerOffer( const QString &screenName, const QVariantHash &peerData )
 
514
{
 
515
    qDebug() << Q_FUNC_INFO;
 
516
 
 
517
    bool peersChanged = false;
 
518
    bool needToSend = false;
 
519
    bool needToAddToCache = false;
 
520
 
 
521
    QString friendlyName = QString( '@' + screenName );
 
522
 
 
523
    if ( !m_cachedAvatars.contains( screenName ) )
 
524
        QMetaObject::invokeMethod( this, "fetchAvatar", Q_ARG( QString, screenName ) );
 
525
 
 
526
    QVariantHash _peerData( peerData );
 
527
 
 
528
    if ( _peerData.contains( "dirty" ) )
 
529
    {
 
530
        peersChanged = true;
 
531
        _peerData.remove( "dirty" );
 
532
    }
 
533
 
 
534
    if ( _peerData.contains( "resend" ) )
 
535
    {
 
536
        needToSend = true;
 
537
        peersChanged = true;
 
538
        _peerData.remove( "resend" );
 
539
    }
 
540
 
 
541
    if ( !_peerData.contains( "okey" ) ||
 
542
         !_peerData.contains( "onod" ) ||
 
543
         ( _peerData.contains( "onod" ) && _peerData["onod"] != Database::instance()->impl()->dbid() ) )
 
544
    {
 
545
        QString okey = QUuid::createUuid().toString().split( '-' ).last();
 
546
        okey.chop( 1 );
 
547
        _peerData["okey"] = QVariant::fromValue< QString >( okey );
 
548
        _peerData["onod"] = QVariant::fromValue< QString >( Database::instance()->impl()->dbid() );
 
549
        peersChanged = true;
 
550
        needToAddToCache = true;
 
551
        needToSend = true;
 
552
    }
 
553
 
 
554
    if ( _peerData.contains( "rekey" ) || !m_keyCache.contains( _peerData["okey"].toString() ) )
 
555
    {
 
556
        _peerData.remove( "rekey" );
 
557
        needToAddToCache = true;
 
558
    }
 
559
 
 
560
    if ( !_peerData.contains( "ohst" ) || !_peerData.contains( "oprt" ) ||
 
561
            _peerData["ohst"].toString() != Servent::instance()->externalAddress() ||
 
562
            _peerData["oprt"].toInt() != Servent::instance()->externalPort()
 
563
        )
 
564
        needToSend = true;
 
565
 
 
566
    if( needToAddToCache && _peerData.contains( "node" ) )
 
567
    {
 
568
        qDebug() << "TwitterSipPlugin registering offer to " << friendlyName << " with node " << _peerData["node"].toString() << " and offeredkey " << _peerData["okey"].toString();
 
569
        m_keyCache << Servent::instance()->createConnectionKey( friendlyName, _peerData["node"].toString(), _peerData["okey"].toString(), false );
 
570
    }
 
571
 
 
572
    if( needToSend && _peerData.contains( "node") )
 
573
    {
 
574
        qDebug() << "TwitterSipPlugin needs to send and has node";
 
575
        _peerData["ohst"] = QVariant::fromValue< QString >( Servent::instance()->externalAddress() );
 
576
        _peerData["oprt"] = QVariant::fromValue< int >( Servent::instance()->externalPort() );
 
577
        peersChanged = true;
 
578
        if( !Servent::instance()->externalAddress().isEmpty() && !Servent::instance()->externalPort() == 0 )
 
579
            QMetaObject::invokeMethod( this, "sendOffer", Q_ARG( QString, screenName ), Q_ARG( QVariantHash, _peerData ) );
 
580
        else
 
581
            qDebug() << "TwitterSipPlugin did not send offer because external address is " << Servent::instance()->externalAddress() << " and external port is " << Servent::instance()->externalPort();
 
582
    }
 
583
 
 
584
    if ( peersChanged )
 
585
    {
 
586
        _peerData["lastseen"] = QString::number( QDateTime::currentMSecsSinceEpoch() );
 
587
        m_cachedPeers[screenName] = QVariant::fromValue< QVariantHash >( _peerData );
 
588
        m_configuration[ "cachedpeers" ] = m_cachedPeers;
 
589
        syncConfig();
 
590
    }
 
591
 
 
592
    if ( m_state == Tomahawk::Accounts::Account::Connected && _peerData.contains( "host" ) && _peerData.contains( "port" ) && _peerData.contains( "pkey" ) )
 
593
        QMetaObject::invokeMethod( this, "makeConnection", Q_ARG( QString, screenName ), Q_ARG( QVariantHash, _peerData ) );
 
594
 
 
595
}
 
596
 
 
597
void
 
598
TwitterSipPlugin::sendOffer( const QString &screenName, const QVariantHash &peerData )
 
599
{
 
600
    qDebug() << Q_FUNC_INFO;
 
601
    QString offerString = QString( "TOMAHAWKPEER:Host=%1:Port=%2:Node=%3*%4:PKey=%5" ).arg( peerData["ohst"].toString() )
 
602
                                                                                      .arg( peerData["oprt"].toString() )
 
603
                                                                                      .arg( Database::instance()->impl()->dbid() )
 
604
                                                                                      .arg( peerData["node"].toString().left( 8 ) )
 
605
                                                                                      .arg( peerData["okey"].toString() );
 
606
    qDebug() << "TwitterSipPlugin sending message to " << screenName << ": " << offerString;
 
607
    if( !m_directMessageNew.isNull() )
 
608
        m_directMessageNew.data()->post( screenName, offerString );
 
609
}
 
610
 
 
611
void
 
612
TwitterSipPlugin::makeConnection( const QString &screenName, const QVariantHash &peerData )
 
613
{
 
614
    qDebug() << Q_FUNC_INFO;
 
615
    if ( !peerData.contains( "host" ) || !peerData.contains( "port" ) || !peerData.contains( "pkey" ) || !peerData.contains( "node" ) ||
 
616
         peerData["host"].toString().isEmpty() || peerData["port"].toString().isEmpty() || peerData["pkey"].toString().isEmpty() || peerData["node"].toString().isEmpty() )
 
617
    {
 
618
        qDebug() << "TwitterSipPlugin could not find host and/or port and/or pkey and/or node for peer " << screenName;
 
619
        return;
 
620
    }
 
621
 
 
622
    if ( peerData["host"].toString() == Servent::instance()->externalAddress() &&
 
623
         peerData["port"].toInt() == Servent::instance()->externalPort() )
 
624
    {
 
625
        qDebug() << "TwitterSipPlugin asked to make connection to our own host and port, ignoring " << screenName;
 
626
        return;
 
627
    }
 
628
 
 
629
    QString friendlyName = QString( '@' + screenName );
 
630
    if ( !Servent::instance()->connectedToSession( peerData["node"].toString() ) )
 
631
        Servent::instance()->connectToPeer( peerData["host"].toString(),
 
632
                                            peerData["port"].toString().toInt(),
 
633
                                            peerData["pkey"].toString(),
 
634
                                            friendlyName,
 
635
                                            peerData["node"].toString() );
 
636
}
 
637
 
 
638
void
 
639
TwitterSipPlugin::directMessagePosted( const QTweetDMStatus& message )
 
640
{
 
641
    qDebug() << Q_FUNC_INFO;
 
642
    qDebug() << "TwitterSipPlugin sent message to " << message.recipientScreenName() << " containing: " << message.text();
 
643
 
 
644
}
 
645
 
 
646
void
 
647
TwitterSipPlugin::directMessagePostError( QTweetNetBase::ErrorCode errorCode, const QString &message )
 
648
{
 
649
    Q_UNUSED( errorCode );
 
650
    Q_UNUSED( message );
 
651
    qDebug() << Q_FUNC_INFO;
 
652
    qDebug() << "TwitterSipPlugin received an error posting direct message: " << m_directMessageNew.data()->lastErrorMessage();
 
653
}
 
654
 
 
655
void
 
656
TwitterSipPlugin::directMessageDestroyed( const QTweetDMStatus& message )
 
657
{
 
658
    qDebug() << Q_FUNC_INFO;
 
659
    qDebug() << "TwitterSipPlugin destroyed message " << message.text();
 
660
}
 
661
 
 
662
void
 
663
TwitterSipPlugin::fetchAvatar( const QString& screenName )
 
664
{
 
665
    qDebug() << Q_FUNC_INFO;
 
666
    if ( !isValid() )
 
667
        return;
 
668
 
 
669
    QTweetUserShow *userShowFetch = new QTweetUserShow( m_cachedTwitterAuth.data(), this );
 
670
    connect( userShowFetch, SIGNAL( parsedUserInfo( QTweetUser ) ), SLOT( avatarUserDataSlot( QTweetUser ) ) );
 
671
    userShowFetch->fetch( screenName );
 
672
}
 
673
 
 
674
void
 
675
TwitterSipPlugin::avatarUserDataSlot( const QTweetUser &user )
 
676
{
 
677
    tDebug() << Q_FUNC_INFO;
 
678
    if ( !isValid() || user.profileImageUrl().isEmpty())
 
679
        return;
 
680
 
 
681
    QNetworkRequest request( user.profileImageUrl() );
 
682
    QNetworkReply *reply = m_cachedTwitterAuth.data()->networkAccessManager()->get( request );
 
683
    reply->setProperty( "screenname", user.screenName() );
 
684
    connect( reply, SIGNAL( finished() ), this, SLOT( profilePicReply() ) );
 
685
}
 
686
 
 
687
 
 
688
void
 
689
TwitterSipPlugin::profilePicReply()
 
690
{
 
691
    tDebug() << Q_FUNC_INFO;
 
692
    QNetworkReply *reply = qobject_cast< QNetworkReply* >( sender() );
 
693
    if ( !reply || reply->error() != QNetworkReply::NoError || !reply->property( "screenname" ).isValid() )
 
694
    {
 
695
        tDebug() << Q_FUNC_INFO << " reply not valid or came back with error";
 
696
        return;
 
697
    }
 
698
    QString screenName = reply->property( "screenname" ).toString();
 
699
    QString friendlyName = '@' + screenName;
 
700
    QByteArray rawData = reply->readAll();
 
701
    QImage image;
 
702
    image.loadFromData( rawData, "PNG" );
 
703
    QPixmap pixmap = QPixmap::fromImage( image );
 
704
    m_cachedAvatars[screenName] = pixmap;
 
705
    emit avatarReceived( friendlyName, QPixmap::fromImage( image ) );
 
706
}
 
707
 
 
708
void
 
709
TwitterSipPlugin::configurationChanged()
 
710
{
 
711
    tDebug() << Q_FUNC_INFO;
 
712
    if ( m_state != Tomahawk::Accounts::Account::Disconnected )
 
713
        m_account->deauthenticate();
 
714
    connectPlugin();
 
715
}
 
716
 
 
717
 
 
718
void
 
719
TwitterSipPlugin::syncConfig()
 
720
{
 
721
    m_account->setConfiguration( m_configuration );
 
722
    m_account->sync();
 
723
}