Files @ 083568c35be9
Branch filter:

Location: libtransport.git/backends/twitter/main.cpp

Sarang Bharadwaj
Removed my proxy settings
  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
//#include "twitcurl.h"
//#include <cstdio>
//#include <iostream>
//#include <fstream>
//
//void printUsage()
//{
//    printf( "\nUsage:\ntwitterClient -u username -p password\n" );
//}
//
//int main( int argc, char* argv[] )
//{
//    std::string userName( "" );
//    std::string passWord( "" );
//    if( argc > 4 )
//    {
//        for( int i = 1; i < argc; i += 2 )
//        {
//            if( 0 == strncmp( argv[i], "-u", strlen("-u") ) )
//            {
//                userName = argv[i+1];
//            }
//            else if( 0 == strncmp( argv[i], "-p", strlen("-p") ) )
//            {
//                passWord = argv[i+1];
//            }
//        }
//        if( ( 0 == userName.length() ) || ( 0 == passWord.length() ) )
//        {
//            printUsage();
//            return 0;
//        }
//    }
//    else
//    {
//        printUsage();
//        return 0;
//    }
//
//    twitCurl twitterObj;
//    std::string tmpStr;
//    std::string replyMsg;
//    char tmpBuf[1024];
//
//    /* Set twitter username and password */
//    twitterObj.setTwitterUsername( userName );
//    twitterObj.setTwitterPassword( passWord );
//
//    /* Set proxy server usename, password, IP and port (if present) */
//    memset( tmpBuf, 0, 1024 );
//    printf( "\nDo you have a proxy server configured (0 for no; 1 for yes): " );
//    gets( tmpBuf );
//    tmpStr = tmpBuf;
//
//    if( std::string::npos != tmpStr.find( "1" ) )
//    {
//        char proxyIp[1024];
//        char proxyPort[1024];
//        char proxyUsername[1024];
//        char proxyPassword[1024];
//
//        memset( proxyIp, 0, 1024 );
//        memset( proxyPort, 0, 1024 );
//        memset( proxyUsername, 0, 1024 );
//        memset( proxyPassword, 0, 1024 );
//
//        printf( "\nEnter proxy server IP: " );
//        gets( proxyIp );
//        printf( "\nEnter proxy server port: " );
//        gets( proxyPort );
//        printf( "\nEnter proxy server username: " );
//        gets( proxyUsername );
//        printf( "\nEnter proxy server password: " );
//        gets( proxyPassword );
//
//        tmpStr = proxyIp;
//        twitterObj.setProxyServerIp( tmpStr );
//        tmpStr = proxyPort;
//        twitterObj.setProxyServerPort( tmpStr );
//        tmpStr = proxyUsername;
//        twitterObj.setProxyUserName( tmpStr );
//        tmpStr = proxyPassword;
//        twitterObj.setProxyPassword( tmpStr );
//    }
//
//    /* OAuth flow begins */
//    /* Step 0: Set OAuth related params. These are got by registering your app at twitter.com */
//    twitterObj.getOAuth().setConsumerKey( std::string( "qxfSCX7WN7SZl7dshqGZA" ) );
//    twitterObj.getOAuth().setConsumerSecret( std::string( "ypWapSj87lswvnksZ46hMAoAZvST4ePGPxAQw6S2o" ) );
//
////    twitterObj.getOAuth().setConsumerKey( std::string( "vlC5S1NCMHHg8mD1ghPRkA" ) );
////    twitterObj.getOAuth().setConsumerSecret( std::string( "3w4cIrHyI3IYUZW5O2ppcFXmsACDaENzFdLIKmEU84" ) );
//
//    /* Step 1: Check if we alredy have OAuth access token from a previous run */
//    std::string myOAuthAccessTokenKey("");
//    std::string myOAuthAccessTokenSecret("");
//    std::ifstream oAuthTokenKeyIn;
//    std::ifstream oAuthTokenSecretIn;
//
//    oAuthTokenKeyIn.open( "twitterClient_token_key.txt" );
//    oAuthTokenSecretIn.open( "twitterClient_token_secret.txt" );
//
//    memset( tmpBuf, 0, 1024 );
//    oAuthTokenKeyIn >> tmpBuf;
//    myOAuthAccessTokenKey = tmpBuf;
//
//    memset( tmpBuf, 0, 1024 );
//    oAuthTokenSecretIn >> tmpBuf;
//    myOAuthAccessTokenSecret = tmpBuf;
//
//    oAuthTokenKeyIn.close();
//    oAuthTokenSecretIn.close();
//
//    if( myOAuthAccessTokenKey.size() && myOAuthAccessTokenSecret.size() )
//    {
//        /* If we already have these keys, then no need to go through auth again */
//        printf( "\nUsing:\nKey: %s\nSecret: %s\n\n", myOAuthAccessTokenKey.c_str(), myOAuthAccessTokenSecret.c_str() );
//
//        twitterObj.getOAuth().setOAuthTokenKey( myOAuthAccessTokenKey );
//        twitterObj.getOAuth().setOAuthTokenSecret( myOAuthAccessTokenSecret );
//    }
//    else
//    {
//        /* Step 2: Get request token key and secret */
//        std::string authUrl;
//        twitterObj.oAuthRequestToken( authUrl );
//
//        /* Step 3: Get PIN  */
//        memset( tmpBuf, 0, 1024 );
//        printf( "\nDo you want to visit twitter.com for PIN (0 for no; 1 for yes): " );
//        gets( tmpBuf );
//        tmpStr = tmpBuf;
//        if( std::string::npos != tmpStr.find( "1" ) )
//        {
//            /* Ask user to visit twitter.com auth page and get PIN */
//            memset( tmpBuf, 0, 1024 );
//            printf( "\nPlease visit this link in web browser and authorize this application:\n%s", authUrl.c_str() );
//            printf( "\nEnter the PIN provided by twitter: " );
//            gets( tmpBuf );
//            tmpStr = tmpBuf;
//            twitterObj.getOAuth().setOAuthPin( tmpStr );
//        }
//        else
//        {
//            /* Else, pass auth url to twitCurl and get it via twitCurl PIN handling */
//            twitterObj.oAuthHandlePIN( authUrl );
//        }
//
//        /* Step 4: Exchange request token with access token */
//        twitterObj.oAuthAccessToken();
//
//        /* Step 5: Now, save this access token key and secret for future use without PIN */
//        twitterObj.getOAuth().getOAuthTokenKey( myOAuthAccessTokenKey );
//        twitterObj.getOAuth().getOAuthTokenSecret( myOAuthAccessTokenSecret );
//
//        /* Step 6: Save these keys in a file or wherever */
//        std::ofstream oAuthTokenKeyOut;
//        std::ofstream oAuthTokenSecretOut;
//
//        oAuthTokenKeyOut.open( "twitterClient_token_key.txt" );
//        oAuthTokenSecretOut.open( "twitterClient_token_secret.txt" );
//
//        oAuthTokenKeyOut.clear();
//        oAuthTokenSecretOut.clear();
//
//        oAuthTokenKeyOut << myOAuthAccessTokenKey.c_str();
//        oAuthTokenSecretOut << myOAuthAccessTokenSecret.c_str();
//
//        oAuthTokenKeyOut.close();
//        oAuthTokenSecretOut.close();
//    }
//    /* OAuth flow ends */
//
//    /* Post a new status message */
//    memset( tmpBuf, 0, 1024 );
//    printf( "\nEnter a new status message: " );
//    gets( tmpBuf );
//    tmpStr = tmpBuf;
//    replyMsg = "";
//    if( twitterObj.statusUpdate( tmpStr ) )
//    {
//        twitterObj.getLastWebResponse( replyMsg );
//        printf( "\ntwitterClient:: twitCurl::statusUpdate web response:\n%s\n", replyMsg.c_str() );
//    }
//    else
//    {
//        twitterObj.getLastCurlError( replyMsg );
//        printf( "\ntwitterClient:: twitCurl::statusUpdate error:\n%s\n", replyMsg.c_str() );
//    }
//
////    /* Search a string */
////    twitterObj.setTwitterApiType( twitCurlTypes::eTwitCurlApiFormatJson );
////    printf( "\nEnter string to search: " );
////    memset( tmpBuf, 0, 1024 );
////    gets( tmpBuf );
////    tmpStr = tmpBuf;
////    replyMsg = "";
////    if( twitterObj.search( tmpStr ) )
////    {
////        twitterObj.getLastWebResponse( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::search web response:\n%s\n", replyMsg.c_str() );
////    }
////    else
////    {
////        twitterObj.getLastCurlError( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::search error:\n%s\n", replyMsg.c_str() );
////    }
////
////    /* Get user timeline */
////    replyMsg = "";
////    printf( "\nGetting user timeline\n" );
////    if( twitterObj.timelineUserGet( false, false, 0 ) )
////    {
////        twitterObj.getLastWebResponse( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::timelineUserGet web response:\n%s\n", replyMsg.c_str() );
////    }
////    else
////    {
////        twitterObj.getLastCurlError( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::timelineUserGet error:\n%s\n", replyMsg.c_str() );
////    }
//
//#ifdef _TWITCURL_TEST_
////    /* Destroy a status message */
////    memset( statusMsg, 0, 1024 );
////    printf( "\nEnter status message id to delete: " );
////    gets( statusMsg );
////    tmpStr = statusMsg;
////    replyMsg = "";
////    if( twitterObj.statusDestroyById( tmpStr ) )
////    {
////        twitterObj.getLastWebResponse( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::statusDestroyById web response:\n%s\n", replyMsg.c_str() );
////    }
////    else
////    {
////        twitterObj.getLastCurlError( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::statusDestroyById error:\n%s\n", replyMsg.c_str() );
////    }
////
////    /* Get public timeline */
////    replyMsg = "";
////    printf( "\nGetting public timeline\n" );
////    if( twitterObj.timelinePublicGet() )
////    {
////        twitterObj.getLastWebResponse( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::timelinePublicGet web response:\n%s\n", replyMsg.c_str() );
////    }
////    else
////    {
////        twitterObj.getLastCurlError( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::timelinePublicGet error:\n%s\n", replyMsg.c_str() );
////    }
////
////    /* Get friend ids */
////    replyMsg = "";
////    printf( "\nGetting friend ids\n" );
////    tmpStr = "techcrunch";
////    if( twitterObj.friendsIdsGet( tmpStr, false ) )
////    {
////        twitterObj.getLastWebResponse( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::friendsIdsGet web response:\n%s\n", replyMsg.c_str() );
////    }
////    else
////    {
////        twitterObj.getLastCurlError( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::friendsIdsGet error:\n%s\n", replyMsg.c_str() );
////    }
////
////    /* Get trends */
////    if( twitterObj.trendsDailyGet() )
////    {
////        twitterObj.getLastWebResponse( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::trendsDailyGet web response:\n%s\n", replyMsg.c_str() );
////    }
////    else
////    {
////        twitterObj.getLastCurlError( replyMsg );
////        printf( "\ntwitterClient:: twitCurl::trendsDailyGet error:\n%s\n", replyMsg.c_str() );
//    }
//#endif // _TWITCURL_TEST_
//
//    return 0;
//}

#include "transport/config.h"
#include "transport/networkplugin.h"
#include "transport/logging.h"
#include "Swiften/Swiften.h"
#include "unistd.h"
#include "signal.h"
#include "sys/wait.h"
#include "sys/signal.h"
#include <boost/algorithm/string.hpp>
#include "twitcurl.h"
#include <iostream>
#include <map>
#include <vector>
#include <cstdio>

using namespace boost::filesystem;
using namespace boost::program_options;
using namespace Transport;

DEFINE_LOGGER(logger, "Twitter Backend");
Swift::SimpleEventLoop *loop_; // Event Loop
class TwitterPlugin; // The plugin
TwitterPlugin * np = NULL;

class TwitterPlugin : public NetworkPlugin {
	public:
		Swift::BoostNetworkFactories *m_factories;
		Swift::BoostIOServiceThread m_boostIOServiceThread;
		boost::shared_ptr<Swift::Connection> m_conn;

		TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port) : NetworkPlugin() {
			this->config = config;
			m_factories = new Swift::BoostNetworkFactories(loop);
			m_conn = m_factories->getConnectionFactory()->createConnection();
			m_conn->onDataRead.connect(boost::bind(&TwitterPlugin::_handleDataRead, this, _1));
			m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));

			LOG4CXX_INFO(logger, "Starting the plugin.");
		}

		// Send data to NetworkPlugin server
		void sendData(const std::string &string) {
			m_conn->write(Swift::createSafeByteArray(string));
		}

		// Receive date from the NetworkPlugin server and invoke the appropirate payload handler (implement in the NetworkPlugin class)
		void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
			std::string d(data->begin(), data->end());
			handleDataRead(d);
		}
		
		// User trying to login into his twitter account
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
			LOG4CXX_INFO(logger, std::string("Received login request for ") + user)
			if(sessions.count(user)) {
				LOG4CXX_INFO(logger, std::string("A session corresponding to ") + user + std::string(" is already active"))
				return;
			}
			
			//twitCurl &twitterObj = sessions[user];
			//std::string myOAuthAccessTokenSecret, myOAuthAccessTokenKey;
        	//twitterObj.getOAuth().getOAuthTokenKey( myOAuthAccessTokenKey );
        	//twitterObj.getOAuth().getOAuthTokenSecret( myOAuthAccessTokenSecret );

			//if(myOAuthAccessTokenSecret.size() && myOAuthAccessTokenKey.size()) {	
			//}
			
			std::string username = user.substr(0,user.find('@'));
			std::string passwd = "dummy"; // Not needed since we are using OAuth
			LOG4CXX_INFO(logger, username + "  " + passwd)

			sessions[user] = new twitCurl();
			handleConnected(user);
			handleBuddyChanged(user, "twitter-account", "twitter", std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
	        
//			std::string ip = "10.93.0.36";
//			std::string port = "3128";
//			std::string puser = "cs09s022";
//			std::string ppasswd = "";
//			sessions[user]->setProxyServerIp(ip);
//	        sessions[user]->setProxyServerPort(port);
//	        sessions[user]->setProxyUserName(puser);
//	        sessions[user]->setProxyPassword(ppasswd);
			
			connectionState[user] = NEW;
			
			sessions[user]->setTwitterUsername(username);
			sessions[user]->setTwitterPassword(passwd); 
			sessions[user]->getOAuth().setConsumerKey( std::string( "qxfSCX7WN7SZl7dshqGZA" ) );
			sessions[user]->getOAuth().setConsumerSecret( std::string( "ypWapSj87lswvnksZ46hMAoAZvST4ePGPxAQw6S2o" ) );
			
			std::string authUrl;
			sessions[user]->oAuthRequestToken( authUrl );
			handleMessage(user, "twitter-account", std::string("Please visit the following link and authorize this application: ") + authUrl);
			handleMessage(user, "twitter-account", std::string("Please reply with the PIN provided by twitter. Prefix the pin with 'pin:'. Ex. 'pin: 1234'"));
			connectionState[user] = WAITING_FOR_PIN;	
		}
		
		// User logging out
		void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
			delete sessions[user];
			sessions[user] = NULL;
			connectionState[user] = DISCONNECTED;
		}


		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "") {
			LOG4CXX_INFO(logger, "Sending message from " << user << " to " << legacyName << ".");
			if(legacyName == "twitter-account") {
				std::string cmd = message.substr(0, message.find(':'));
				std::string data = message.substr(message.find(':') + 1);
				
				handleMessage(user, "twitter-account", cmd + " " + data);

				if(cmd == "pin") {
					sessions[user]->getOAuth().setOAuthPin( data );
					sessions[user]->oAuthAccessToken();
					connectionState[user] = CONNECTED;
					LOG4CXX_INFO(logger, "Sent PIN " << data << " and obtained access token");
				}

				if(cmd == "status") {
					LOG4CXX_INFO(logger, "Updating status for " << user << ": " << data);
					std::string replyMsg; 
					if( sessions[user]->statusUpdate( data ) ) {
						sessions[user]->getLastWebResponse( replyMsg );
						LOG4CXX_INFO(logger, "twitterClient:: twitCurl::statusUpdate web response: " << replyMsg );
					}
					else {
						sessions[user]->getLastCurlError( replyMsg );
						LOG4CXX_INFO(logger, "twitterClient:: twitCurl::statusUpdate error: " << replyMsg );
					}
				}
			}
		}

		void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
			LOG4CXX_INFO(logger, user << ": Added buddy " << buddyName << ".");
			handleBuddyChanged(user, buddyName, alias, groups, pbnetwork::STATUS_ONLINE);
		}

		void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) {

		}

	private:
		enum status {NEW, WAITING_FOR_PIN, CONNECTED, DISCONNECTED};
		Config *config;
		std::map<std::string, twitCurl*> sessions;
		std::map<std::string, status> connectionState;
};

static void spectrum_sigchld_handler(int sig)
{
	int status;
	pid_t pid;

	do {
		pid = waitpid(-1, &status, WNOHANG);
	} while (pid != 0 && pid != (pid_t)-1);

	if ((pid == (pid_t) - 1) && (errno != ECHILD)) {
		char errmsg[BUFSIZ];
		snprintf(errmsg, BUFSIZ, "Warning: waitpid() returned %d", pid);
		perror(errmsg);
	}
}


int main (int argc, char* argv[]) {
	std::string host;
	int port;

	if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
		std::cout << "SIGCHLD handler can't be set\n";
		return -1;
	}

	boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <config_file.cfg>\nAllowed options");
	desc.add_options()
		("host,h", value<std::string>(&host), "host")
		("port,p", value<int>(&port), "port")
		;
	try
	{
		boost::program_options::variables_map vm;
		boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
		boost::program_options::notify(vm);
	}
	catch (std::runtime_error& e)
	{
		std::cout << desc << "\n";
		exit(1);
	}
	catch (...)
	{
		std::cout << desc << "\n";
		exit(1);
	}


	if (argc < 5) {
		return 1;
	}

	Config config;
	if (!config.load(argv[5])) {
		std::cerr << "Can't open " << argv[1] << " configuration file.\n";
		return 1;
	}

	Logging::initBackendLogging(&config);

	Swift::SimpleEventLoop eventLoop;
	loop_ = &eventLoop;
	np = new TwitterPlugin(&config, &eventLoop, host, port);
	loop_->run();

	return 0;
}