Changeset - 6cc7c334f3c4
[Not reviewed]
0 4 2
Sarang Bharadwaj - 13 years ago 2012-06-15 11:45:41
sarang.bh@gmail.com
Retweet
6 files changed with 109 insertions and 1 deletions:
0 comments (0 inline, 0 general)
backends/twitter/Requests/RetweetRequest.cpp
Show inline comments
 
new file 100644
 
#include "RetweetRequest.h"
 
DEFINE_LOGGER(logger, "RetweetRequest")
 
void RetweetRequest::run()
 
{
 
	LOG4CXX_INFO(logger, user << " Retweeting " << data)
 
	success = twitObj->retweetById( data );
 
}
 

	
 
void RetweetRequest::finalize()
 
{
 
	replyMsg = "";
 
	if(!success) {
 
		twitObj->getLastCurlError( replyMsg );
 
		LOG4CXX_ERROR(logger, user << " " << replyMsg)
 
		callBack(user, replyMsg);
 
	} else {
 
		twitObj->getLastWebResponse( replyMsg );
 
		std::string error = getErrorMessage( replyMsg );
 
		if(error.length()) LOG4CXX_ERROR(logger, user << " " << error)
 
		else LOG4CXX_INFO(logger, user << " " << replyMsg);
 
		callBack(user, error);
 
	}
 
}
backends/twitter/Requests/RetweetRequest.h
Show inline comments
 
new file 100644
 
#ifndef RETWEET_H
 
#define RETWEET_H
 

	
 
#include "../ThreadPool.h"
 
#include "../TwitterResponseParser.h"
 
#include "../libtwitcurl/twitcurl.h"
 
#include "transport/networkplugin.h"
 
#include "transport/logging.h"
 
#include <boost/function.hpp>
 
#include <string>
 
#include <iostream>
 

	
 
using namespace Transport;
 
class RetweetRequest : public Thread
 
{
 
	twitCurl *twitObj;
 
	std::string data;
 
	std::string user;
 
	std::string replyMsg;
 
	bool success;
 
	boost::function < void (std::string&, std::string &) > callBack;
 

	
 
	public:
 
	RetweetRequest(twitCurl *obj, const std::string &_user, const std::string &_data,
 
			       boost::function < void (std::string &, std::string &) > _cb) {
 
		twitObj = obj->clone();
 
		data = _data;
 
		user = _user;
 
		callBack = _cb;
 
	}
 

	
 
	~RetweetRequest() {
 
		delete twitObj;
 
	}
 

	
 
	void run();
 
	void finalize();
 
};
 

	
 
#endif
backends/twitter/TwitterPlugin.cpp
Show inline comments
 
#include "TwitterPlugin.h"
 
#include "Requests/StatusUpdateRequest.h"
 
#include "Requests/DirectMessageRequest.h"
 
#include "Requests/TimelineRequest.h"
 
#include "Requests/FetchFriends.h"
 
#include "Requests/HelpMessageRequest.h"
 
#include "Requests/PINExchangeProcess.h"
 
#include "Requests/OAuthFlow.h"
 
#include "Requests/CreateFriendRequest.h"
 
#include "Requests/DestroyFriendRequest.h"
 
#include "Requests/RetweetRequest.h"
 

	
 
DEFINE_LOGGER(logger, "Twitter Backend");
 

	
 
TwitterPlugin *np = NULL;
 
Swift::SimpleEventLoop *loop_; // Event Loop
 

	
 
#define abs(x) ((x)<0?-(x):(x))
 
static int cmp(std::string a, std::string b)
 
{
 
	int diff = abs((int)a.size() - (int)b.size());
 
	if(a.size() < b.size()) a = std::string(diff,'0') + a;
 
	else b = std::string(diff,'0') + b;
 
	
 
	if(a == b) return 0;
 
	if(a < b) return -1;
 
	return 1;
 
}
 

	
 

	
 
TwitterPlugin::TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, StorageBackend *storagebackend, const std::string &host, int port) : NetworkPlugin() 
 
{
 
	this->config = config;
 
	this->storagebackend = storagebackend;
 

	
 
@@ -141,48 +142,50 @@ void TwitterPlugin::handleMessageSendRequest(const std::string &user, const std:
 
	 	
 
		int i;
 
		for(i=0 ; i<message.size() && message[i] != ' '; i++) cmd += message[i];
 
		while(i<message.size() && message[i] == ' ') i++;
 
		data = message.substr(i);
 
		
 
		//handleMessage(user, "twitter-account", cmd + " " + data);
 

	
 
		if(cmd == "#pin") tp->runAsThread(new PINExchangeProcess(np, sessions[user], user, data));
 
		else if(cmd == "#help") tp->runAsThread(new HelpMessageRequest(np, user));
 
		else if(cmd[0] == '@') {
 
			std::string username = cmd.substr(1); 
 
			tp->runAsThread(new DirectMessageRequest(sessions[user], user, username, data,
 
												     boost::bind(&TwitterPlugin::directMessageResponse, this, _1, _2, _3)));
 
		}
 
		else if(cmd == "#status") tp->runAsThread(new StatusUpdateRequest(np, sessions[user], user, data));
 
		else if(cmd == "#timeline") tp->runAsThread(new TimelineRequest(sessions[user], user, data, "",
 
														boost::bind(&TwitterPlugin::displayTweets, this, _1, _2, _3, _4)));
 
		else if(cmd == "#friends") tp->runAsThread(new FetchFriends(sessions[user], user,
 
													   boost::bind(&TwitterPlugin::displayFriendlist, this, _1, _2, _3)));
 
		else if(cmd == "#follow") tp->runAsThread(new CreateFriendRequest(sessions[user], user, data,
 
													   boost::bind(&TwitterPlugin::createFriendResponse, this, _1, _2, _3)));
 
		else if(cmd == "#unfollow") tp->runAsThread(new DestroyFriendRequest(sessions[user], user, data,
 
													   boost::bind(&TwitterPlugin::deleteFriendResponse, this, _1, _2, _3)));
 
		else if(cmd == "#retweet") tp->runAsThread(new RetweetRequest(sessions[user], user, data,
 
													   boost::bind(&TwitterPlugin::RetweetResponse, this, _1, _2)));
 
		else handleMessage(user, "twitter-account", "Unknown command! Type #help for a list of available commands.");
 
	} 
 

	
 
	else {
 
		tp->runAsThread(new DirectMessageRequest(sessions[user], user, legacyName, message,
 
												 boost::bind(&TwitterPlugin::directMessageResponse, this, _1, _2, _3)));
 
	}
 
}
 

	
 
void TwitterPlugin::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 TwitterPlugin::handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) 
 
{
 

	
 
}
 

	
 

	
 
void TwitterPlugin::pollForTweets()
 
{
 
	boost::mutex::scoped_lock lock(userlock);
 
@@ -344,49 +347,49 @@ void TwitterPlugin::populateRoster(std::string &user, std::vector<User> &friends
 
		}
 
	} else handleMessage(user, "twitter-account", std::string("Error populating roster - ") + errMsg);	
 
}
 

	
 
void TwitterPlugin::displayFriendlist(std::string &user, std::vector<User> &friends, std::string &errMsg)
 
{
 
	if(errMsg.length() == 0) 
 
	{
 
		std::string userlist = "\n***************USER LIST****************\n";
 
		for(int i=0 ; i < friends.size() ; i++) {
 
			userlist += " - " + friends[i].getUserName() + " (" + friends[i].getScreenName() + ")\n";
 
		}	
 
		userlist += "***************************************\n";
 
		handleMessage(user, "twitter-account", userlist);	
 
	} else handleMessage(user, "twitter-account", errMsg);	
 
 
 
}
 

	
 
void TwitterPlugin::displayTweets(std::string &user, std::string &userRequested, std::vector<Status> &tweets , std::string &errMsg)
 
{
 
	if(errMsg.length() == 0) {
 
		std::string timeline = "";
 

	
 
		for(int i=0 ; i<tweets.size() ; i++) {
 
			timeline += " - " + tweets[i].getUserData().getScreenName() + ": " + tweets[i].getTweet() + "\n";
 
			timeline += " - " + tweets[i].getUserData().getScreenName() + ": " + tweets[i].getTweet() + " (MsgId: " + tweets[i].getID() + ")\n";
 
		}
 

	
 
		if((userRequested == "" || userRequested == user) && tweets.size()) {
 
			std::string tweetID = getMostRecentTweetID(user);
 
			if(tweetID != tweets[0].getID()) updateLastTweetID(user, tweets[0].getID());
 
			else timeline = ""; //have already sent the tweet earlier
 
		}
 

	
 
		if(timeline.length()) handleMessage(user, "twitter-account", timeline);
 
	} else handleMessage(user, "twitter-account", errMsg);	
 
}
 

	
 
void TwitterPlugin::directMessageResponse(std::string &user, std::vector<DirectMessage> &messages, std::string &errMsg)
 
{
 
	if(errMsg.length()) {
 
		handleMessage(user, "twitter-account", std::string("Error while sending direct message! - ") + errMsg);	
 
		return;
 
	}
 
	
 
	if(!messages.size()) return;
 
	
 
	if(twitterMode == SINGLECONTACT) {
 

	
 
		std::string msglist = "";
 
@@ -423,24 +426,33 @@ void TwitterPlugin::directMessageResponse(std::string &user, std::vector<DirectM
 
void TwitterPlugin::createFriendResponse(std::string &user, std::string &frnd, std::string &errMsg)
 
{
 
	if(errMsg.length()) {
 
		handleMessage(user, "twitter-account", errMsg);
 
		return;
 
	}
 

	
 
	if(twitterMode == SINGLECONTACT) {
 
		handleMessage(user, "twitter-account", std::string("You are now following ") + frnd);
 
	} else if(twitterMode == MULTIPLECONTACT) {
 
		handleBuddyChanged(user, frnd, frnd, std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
 
	}
 
}
 

	
 
void TwitterPlugin::deleteFriendResponse(std::string &user, std::string &frnd, std::string &errMsg)
 
{
 
	if(errMsg.length()) {
 
		handleMessage(user, "twitter-account", errMsg);
 
		return;
 
	} if(twitterMode == SINGLECONTACT) {
 
		handleMessage(user, "twitter-account", std::string("You are not following ") + frnd + "anymore");
 
	} else if(twitterMode == MULTIPLECONTACT) {
 
	}
 
}
 

	
 

	
 
void TwitterPlugin::RetweetResponse(std::string &user, std::string &errMsg)
 
{
 
	if(errMsg.length()) {
 
		handleMessage(user, "twitter-account", errMsg);
 
		return;
 
	}
 
}
backends/twitter/TwitterPlugin.h
Show inline comments
 
@@ -81,48 +81,49 @@ class TwitterPlugin : public NetworkPlugin {
 
		
 
		bool storeUserOAuthKeyAndSecret(const std::string user, const std::string OAuthKey, const std::string OAuthSecret);
 
		
 
		void initUserSession(const std::string user, const std::string password);
 
		
 
		void OAuthFlowComplete(const std::string user, twitCurl *obj);
 
		
 
		void pinExchangeComplete(const std::string user, const std::string OAuthAccessTokenKey, const std::string OAuthAccessTokenSecret);
 
		
 
		void updateLastTweetID(const std::string user, const std::string ID);
 

	
 
		std::string getMostRecentTweetID(const std::string user);
 

	
 
		void updateLastDMID(const std::string user, const std::string ID);
 
		
 
		std::string getMostRecentDMID(const std::string user);
 

	
 
		/****************** Twitter Response handlers **************************************/
 
		void populateRoster(std::string &user, std::vector<User> &friends, std::string &errMsg);
 
		void displayFriendlist(std::string &user, std::vector<User> &friends, std::string &errMsg);
 
		void displayTweets(std::string &user, std::string &userRequested, std::vector<Status> &tweets , std::string &errMsg);
 
		void directMessageResponse(std::string &user, std::vector<DirectMessage> &messages, std::string &errMsg);
 
		void createFriendResponse(std::string &user, std::string &frnd, std::string &errMsg);
 
		void deleteFriendResponse(std::string &user, std::string &frnd, std::string &errMsg);
 
		void RetweetResponse(std::string &user, std::string &errMsg);
 
		/***********************************************************************************/
 

	
 
	private:
 
		enum status {NEW, WAITING_FOR_PIN, CONNECTED, DISCONNECTED};
 
		enum mode {SINGLECONTACT, MULTIPLECONTACT, CHATROOM};
 

	
 
		Config *config;
 

	
 
		std::string consumerKey;
 
		std::string consumerSecret;
 
		std::string OAUTH_KEY;
 
		std::string OAUTH_SECRET;
 

	
 
		boost::mutex dblock, userlock;
 

	
 
		ThreadPool *tp;
 
		std::map<std::string, twitCurl*> sessions;		
 
		std::map<std::string, status> connectionState;
 
		std::map<std::string, std::string> mostRecentTweetID;
 
		std::map<std::string, std::string> mostRecentDirectMessageID;
 
		std::set<std::string> onlineUsers;
 
		mode twitterMode;
 
};
 

	
backends/twitter/libtwitcurl/twitcurl.cpp
Show inline comments
 
@@ -414,48 +414,78 @@ bool twitCurl::statusShowById( std::string& statusId )
 
*
 
* @description: method to delete a status message by its id
 
*
 
* @input: statusId - a number in std::string format
 
*
 
* @output: true if DELETE is success, otherwise false. This does not check http
 
*          response by twitter. Use getLastWebResponse() for that.
 
*
 
*--*/
 
bool twitCurl::statusDestroyById( std::string& statusId )
 
{
 
    bool retVal = false;
 
    if( statusId.length() )
 
    {
 
        /* Prepare URL */
 
        std::string buildUrl = twitterDefaults::TWITCURL_STATUDESTROY_URL + statusId +
 
                               twitCurlDefaults::TWITCURL_EXTENSIONFORMATS[m_eApiFormatType];
 
 
        /* Perform DELETE */
 
        retVal = performDelete( buildUrl );
 
    }
 
    return retVal;
 
}
 
 
/*++
 
* @method: twitCurl::retweetById
 
*
 
* @description: method to retweet a status message by its id
 
*
 
* @input: statusId - a number in std::string format
 
*
 
* @output: true if RETWEET is success, otherwise false. This does not check http
 
*          response by twitter. Use getLastWebResponse() for that.
 
*
 
*--*/
 
bool twitCurl::retweetById( std::string& statusId )
 
{
 
    bool retVal = false;
 
    if( statusId.length() )
 
    {
 
        /* Prepare URL */
 
        std::string buildUrl = twitterDefaults::TWITCURL_RETWEET_URL + statusId +
 
                               twitCurlDefaults::TWITCURL_EXTENSIONFORMATS[m_eApiFormatType];
 
 
        /* Send some dummy data in POST */
 
        std::string dummyData = twitCurlDefaults::TWITCURL_TEXTSTRING +
 
                                urlencode( std::string( "dummy" ) );
 
 
        /* Perform Retweet */
 
        retVal = performPost( buildUrl, dummyData );
 
    }
 
    return retVal;
 
}
 
 
/*++
 
* @method: twitCurl::timelinePublicGet
 
*
 
* @description: method to get public timeline
 
*
 
* @input: none
 
*
 
* @output: true if GET is success, otherwise false. This does not check http
 
*          response by twitter. Use getLastWebResponse() for that.
 
*
 
*--*/
 
bool twitCurl::timelinePublicGet()
 
{
 
    /* Perform GET */
 
    return performGet( twitterDefaults::TWITCURL_PUBLIC_TIMELINE_URL +
 
                       twitCurlDefaults::TWITCURL_EXTENSIONFORMATS[m_eApiFormatType] );
 
}
 
 
/*++
 
* @method: twitCurl::timelineHomeGet
 
*
 
* @description: method to get home timeline
 
*
 
* @input: none
backends/twitter/libtwitcurl/twitcurl.h
Show inline comments
 
@@ -40,48 +40,49 @@ namespace twitCurlDefaults
 
                                                     };
 
    const std::string TWITCURL_TARGETSCREENNAME = "target_screen_name=";
 
    const std::string TWITCURL_TARGETUSERID = "target_id=";
 
    const std::string TWITCURL_SINCEID = "since_id=";
 
    const std::string TWITCURL_TRIMUSER = "trim_user=1";
 
    const std::string TWITCURL_INCRETWEETS = "include_rts=1";
 
    const std::string TWITCURL_COUNT = "count=";
 
 
    /* URL separators */
 
    const std::string TWITCURL_URL_SEP_AMP = "&";
 
    const std::string TWITCURL_URL_SEP_QUES = "?";
 
};
 
 
/* Default twitter URLs */
 
namespace twitterDefaults
 
{
 
 
    /* Search URLs */
 
    const std::string TWITCURL_SEARCH_URL = "http://search.twitter.com/search";
 
 
    /* Status URLs */
 
    const std::string TWITCURL_STATUSUPDATE_URL = "http://api.twitter.com/1/statuses/update";
 
    const std::string TWITCURL_STATUSSHOW_URL = "http://api.twitter.com/1/statuses/show/";
 
    const std::string TWITCURL_STATUDESTROY_URL = "http://api.twitter.com/1/statuses/destroy/";
 
	const std::string TWITCURL_RETWEET_URL = "http://api.twitter.com/1/statuses/retweet/";
 
 
    /* Timeline URLs */
 
    const std::string TWITCURL_HOME_TIMELINE_URL = "http://api.twitter.com/1/statuses/home_timeline";
 
    const std::string TWITCURL_PUBLIC_TIMELINE_URL = "http://api.twitter.com/1/statuses/public_timeline";
 
    const std::string TWITCURL_FEATURED_USERS_URL = "http://api.twitter.com/1/statuses/featured";
 
    const std::string TWITCURL_FRIENDS_TIMELINE_URL = "http://api.twitter.com/1/statuses/friends_timeline";
 
    const std::string TWITCURL_MENTIONS_URL = "http://api.twitter.com/1/statuses/mentions";
 
    const std::string TWITCURL_USERTIMELINE_URL = "http://api.twitter.com/1/statuses/user_timeline";
 
 
    /* Users URLs */
 
	const std::string TWITCURL_LOOKUPUSERS_URL = "http://api.twitter.com/1/users/lookup";
 
    const std::string TWITCURL_SHOWUSERS_URL = "http://api.twitter.com/1/users/show";
 
    const std::string TWITCURL_SHOWFRIENDS_URL = "http://api.twitter.com/1/statuses/friends";
 
    const std::string TWITCURL_SHOWFOLLOWERS_URL = "http://api.twitter.com/1/statuses/followers";
 
 
    /* Direct messages URLs */
 
    const std::string TWITCURL_DIRECTMESSAGES_URL = "http://api.twitter.com/1/direct_messages";
 
    const std::string TWITCURL_DIRECTMESSAGENEW_URL = "http://api.twitter.com/1/direct_messages/new";
 
    const std::string TWITCURL_DIRECTMESSAGESSENT_URL = "http://api.twitter.com/1/direct_messages/sent";
 
    const std::string TWITCURL_DIRECTMESSAGEDESTROY_URL = "http://api.twitter.com/1/direct_messages/destroy/";
 
 
    /* Friendships URLs */
 
    const std::string TWITCURL_FRIENDSHIPSCREATE_URL = "http://api.twitter.com/1/friendships/create";
 
    const std::string TWITCURL_FRIENDSHIPSDESTROY_URL = "http://api.twitter.com/1/friendships/destroy";
 
@@ -126,48 +127,49 @@ public:
 
    ~twitCurl();
 
 
    /* Twitter OAuth authorization methods */
 
    oAuth& getOAuth();
 
    bool oAuthRequestToken( std::string& authorizeUrl /* out */ );
 
    bool oAuthAccessToken();
 
    bool oAuthHandlePIN( const std::string& authorizeUrl /* in */ );
 
 
    /* Twitter login APIs, set once and forget */
 
    std::string& getTwitterUsername();
 
    std::string& getTwitterPassword();
 
    void setTwitterUsername( std::string& userName /* in */ );
 
    void setTwitterPassword( std::string& passWord /* in */ );
 
 
    /* Twitter API type */
 
    void setTwitterApiType( twitCurlTypes::eTwitCurlApiFormatType eType );
 
 
    /* Twitter search APIs */
 
    bool search( std::string& searchQuery /* in */ );
 
 
    /* Twitter status APIs */
 
    bool statusUpdate( std::string& newStatus /* in */ );
 
    bool statusShowById( std::string& statusId /* in */ );
 
    bool statusDestroyById( std::string& statusId /* in */ );
 
	bool retweetById( std::string& statusId /* in */);
 
 
    /* Twitter timeline APIs */
 
    bool timelineHomeGet(std::string sinceId = ""  /* in */);
 
    bool timelinePublicGet();
 
    bool timelineFriendsGet();
 
    bool timelineUserGet( bool trimUser /* in */, bool includeRetweets /* in */, unsigned int tweetCount /* in */, std::string userInfo = "" /* in */, bool isUserId = false /* in */ );
 
    bool featuredUsersGet();
 
    bool mentionsGet( std::string sinceId = "" /* in */ );
 
 
    /* Twitter user APIs */
 
	bool userLookup( std::vector<std::string> &userInfo /* in */,  bool isUserId = false /* in */);
 
    bool userGet( std::string& userInfo /* in */, bool isUserId = false /* in */ );
 
    bool friendsGet( std::string userInfo = "" /* in */, bool isUserId = false /* in */ );
 
    bool followersGet( std::string userInfo = "" /* in */, bool isUserId = false /* in */ );
 
 
    /* Twitter direct message APIs */
 
    bool directMessageGet( std::string sinceId /* in */ );
 
    bool directMessageSend( std::string& userInfo /* in */, std::string& dMsg /* in */, bool isUserId = false /* in */ );
 
    bool directMessageGetSent();
 
    bool directMessageDestroyById( std::string& dMsgId /* in */ );
 
 
    /* Twitter friendships APIs */
 
    bool friendshipCreate( std::string& userInfo /* in */, bool isUserId = false /* in */ );
 
    bool friendshipDestroy( std::string& userInfo /* in */, bool isUserId = false /* in */ );
0 comments (0 inline, 0 general)