General cleanup (#216)

This commit is contained in:
Florian Kinder 2017-06-12 00:41:35 +02:00 committed by vitalyster
parent 180397daab
commit d93cc2ce66
23 changed files with 419 additions and 410 deletions

View File

@ -9,7 +9,7 @@
#include "purple.h"
#include <algorithm>
#include <iostream>
#include <fstream>
#include <fstream>
#include "transport/NetworkPlugin.h"
#include "transport/Logging.h"
@ -188,29 +188,29 @@ static std::string OAUTH_TOKEN = "hangouts_oauth_token";
static bool getUserOAuthToken(const std::string user, std::string &token)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
return false;
}
token = "";
int type = TYPE_STRING;
storagebackend->getUserSetting((long)info.id, OAUTH_TOKEN, type, token);
return true;
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
token = "";
int type = TYPE_STRING;
storagebackend->getUserSetting((long)info.id, OAUTH_TOKEN, type, token);
return true;
}
static bool storeUserOAuthToken(const std::string user, const std::string OAuthToken)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
return false;
}
storagebackend->updateUserSetting((long)info.id, OAUTH_TOKEN, OAuthToken);
return true;
}
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
storagebackend->updateUserSetting((long)info.id, OAUTH_TOKEN, OAuthToken);
return true;
}
class SpectrumNetworkPlugin : public NetworkPlugin {
public:
@ -274,7 +274,7 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
if (strippedKey != key2) {
continue;
}
found = true;
switch (type) {
case PURPLE_PREF_BOOLEAN:
@ -313,9 +313,9 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
std::string username(purple_account_get_username_wrapped(account));
std::vector <std::string> u = split(username, '@');
purple_account_set_username_wrapped(account, (const char*) u.front().c_str());
std::vector <std::string> s = split(u.back(), ':');
std::vector <std::string> s = split(u.back(), ':');
purple_account_set_string_wrapped(account, "server", s.front().c_str());
purple_account_set_int_wrapped(account, "port", atoi(s.back().c_str()));
purple_account_set_int_wrapped(account, "port", atoi(s.back().c_str()));
}
if (!CONFIG_STRING_DEFAULTED(config, "proxy.type", "").empty()) {
@ -430,7 +430,7 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
}
// OAuth helper
if (protocol == "prpl-hangouts") {
LOG4CXX_INFO(logger, user << ": Adding Buddy " << adminLegacyName << " " << adminAlias)
LOG4CXX_INFO(logger, user << ": Adding Buddy " << adminLegacyName << " " << adminAlias);
handleBuddyChanged(user, adminLegacyName, adminAlias, std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
}
}
@ -532,7 +532,7 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
}
return;
}
if (!conv) {
conv = purple_find_conversation_with_account_wrapped(PURPLE_CONV_TYPE_IM, LegacyNameToName(account, legacyName).c_str(), account);
if (!conv) {
@ -815,7 +815,7 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
if (xfer) {
m_unhandledXfers.erase(user + fileName + buddyName);
FTData *ftData = (FTData *) xfer->ui_data;
ftData->id = ftID;
m_xfers[ftID] = xfer;
purple_xfer_request_accepted_wrapped(xfer, fileName.c_str());
@ -1035,7 +1035,7 @@ void buddyListNewNode(PurpleBlistNode *node) {
cache->nodes[node] = 1;
return;
}
std::vector<std::string> groups = getGroups(buddy);
LOG4CXX_INFO(logger, "Buddy updated " << np->m_accounts[account] << " " << purple_buddy_get_name_wrapped(buddy) << " " << getAlias(buddy) << " group (" << groups.size() << ")=" << groups[0]);
@ -1191,7 +1191,7 @@ static void conv_write(PurpleConversation *conv, const char *who, const char *al
std::string conversationName = purple_conversation_get_name_wrapped(conv);
LOG4CXX_INFO(logger, "Received message body='" << message_ << "' name='" << conversationName << "' " << who);
np->handleMessage(np->m_accounts[account], np->NameToLegacyName(account, conversationName), message_, who, xhtml_, timestamp);
}
}
}
}
@ -1278,7 +1278,7 @@ static void conv_write_im(PurpleConversation *conv, const char *who, const char
return;
}
purple_imgstore_unref_wrapped(image);
std::string src = CONFIG_STRING(config, "service.web_url") + "/" + name + "." + ext;
std::string img = "<img src=\"" + src + "\"/>";
boost::replace_all(body, "<img id=\"" + id + "\">", img);
@ -1488,7 +1488,7 @@ static void *notify_user_info(PurpleConnection *gc, const char *who, PurpleNotif
if (pos != std::string::npos)
name.erase((int) pos, name.length() - (int) pos);
GList *vcardEntries = purple_notify_user_info_get_entries_wrapped(user_info);
PurpleNotifyUserInfoEntry *vcardEntry;
std::string firstName;
@ -1581,7 +1581,7 @@ static void *notify_user_info(PurpleConnection *gc, const char *who, PurpleNotif
purple_buddy_icon_unref_wrapped(icon);
}
}
np->handleVCard(np->m_accounts[account], np->m_vcards[np->m_accounts[account] + name], name, fullName, nickname, photo);
np->m_vcards.erase(np->m_accounts[account] + name);
@ -1833,7 +1833,7 @@ static gssize XferRead(PurpleXfer *xfer, guchar **buffer, gssize size) {
// int data_size = repeater->getDataToSend(buffer, size);
// if (data_size == 0)
// return 0;
//
//
// return data_size;
return 0;
}
@ -1880,7 +1880,7 @@ static void RoomlistProgress(PurpleRoomlist *list, gboolean in_progress)
GList *rooms;
std::list<std::string> m_topics;
for (rooms = list->rooms; rooms != NULL; rooms = rooms->next) {
PurpleRoomlistRoom *room = (PurpleRoomlistRoom *)rooms->data;
PurpleRoomlistRoom *room = (PurpleRoomlistRoom *)rooms->data;
np->m_rooms[np->m_accounts[list->account]].push_back(room->name);
if (topicId == -1) {
@ -1947,7 +1947,7 @@ static void transport_core_ui_init(void)
purple_connections_set_ui_ops_wrapped(&conn_ui_ops);
purple_conversations_set_ui_ops_wrapped(&conversation_ui_ops);
purple_roomlist_set_ui_ops_wrapped(&roomlist_ui_ops);
// #ifndef WIN32
// purple_dnsquery_set_ui_ops_wrapped(getDNSUiOps());
// #endif
@ -2018,7 +2018,7 @@ debug_init(void)
REGISTER_G_LOG_HANDLER("GLib-GObject");
REGISTER_G_LOG_HANDLER("GThread");
REGISTER_G_LOG_HANDLER("GConf");
#undef REGISTER_G_LOD_HANDLER
}
@ -2045,7 +2045,7 @@ static void signed_on(PurpleConnection *gc, gpointer unused) {
#endif
#endif
purple_roomlist_get_list_wrapped(gc);
// For prpl-gg
execute_purple_plugin_action(gc, "Download buddylist from Server");
if (CONFIG_STRING(config, "service.protocol") == "prpl-hangouts") {
@ -2129,7 +2129,7 @@ static bool initPurple() {
std::string cacertsDir = CONFIG_STRING_DEFAULTED(config, "purple.cacerts_dir", "./ca-certs");
LOG4CXX_INFO(logger, "Setting libpurple cacerts directory to: " << cacertsDir);
purple_certificate_add_ca_search_path_wrapped(cacertsDir.c_str());
std::string userDir = CONFIG_STRING_DEFAULTED(config, "service.working_dir", "./");
LOG4CXX_INFO(logger, "Setting libpurple user directory to: " << userDir);
@ -2196,7 +2196,7 @@ static bool initPurple() {
purple_signal_connect_wrapped(purple_xfers_get_handle_wrapped(), "file-recv-request", &xfer_handle, PURPLE_CALLBACK(newXfer), NULL);
purple_signal_connect_wrapped(purple_xfers_get_handle_wrapped(), "file-recv-complete", &xfer_handle, PURPLE_CALLBACK(XferReceiveComplete), NULL);
purple_signal_connect_wrapped(purple_xfers_get_handle_wrapped(), "file-send-complete", &xfer_handle, PURPLE_CALLBACK(XferSendComplete), NULL);
//
//
// purple_commands_init();
}
@ -2224,7 +2224,7 @@ static void transportDataReceived(gpointer data, gint source, PurpleInputConditi
if (firstPing) {
firstPing = false;
NetworkPlugin::PluginConfig cfg;
NetworkPlugin::PluginConfig cfg;
cfg.setSupportMUC(true);
if (CONFIG_STRING(config, "service.protocol") == "prpl-telegram") {
cfg.setNeedPassword(false);
@ -2277,7 +2277,7 @@ int main(int argc, char **argv) {
}
config = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Config>(cfg);
Logging::initBackendLogging(config.get());
if (CONFIG_STRING(config, "service.protocol") == "prpl-hangouts") {
storagebackend = StorageBackend::createBackend(config.get(), error);
@ -2287,17 +2287,17 @@ int main(int argc, char **argv) {
return NetworkPlugin::StorageBackendNeeded;
}
else if (!storagebackend->connect()) {
LOG4CXX_ERROR(logger, "Can't connect to database!")
return -1;
LOG4CXX_ERROR(logger, "Can't connect to database!");
return -1;
}
}
initPurple();
main_socket = create_socket(host.c_str(), port);
purple_input_add_wrapped(main_socket, PURPLE_INPUT_READ, &transportDataReceived, NULL);
purple_timeout_add_seconds_wrapped(30, pingTimeout, NULL);
np = new SpectrumNetworkPlugin();
bool libev = CONFIG_STRING_DEFAULTED(config, "service.eventloop", "") == "libev";

View File

@ -82,7 +82,7 @@ class SMSNetworkPlugin : public NetworkPlugin {
void handleSMS(const std::string &sms) {
LOG4CXX_INFO(logger, "Handling SMS " << sms << ".")
LOG4CXX_INFO(logger, "Handling SMS " << sms << ".");
std::ifstream t(sms.c_str());
std::string str;
@ -149,7 +149,7 @@ class SMSNetworkPlugin : public NetworkPlugin {
}
void sendSMS(const std::string &to, const std::string &msg) {
// TODO: Probably
// TODO: Probably
std::string data = "To: " + to + "\n";
data += "\n";
data += msg;
@ -232,7 +232,7 @@ class SMSNetworkPlugin : public NetworkPlugin {
private:
Config *config;
};

View File

@ -69,7 +69,7 @@ class ForwardIQHandler : public Swift::IQHandler {
private:
NetworkPlugin *m_np;
std::string m_user;
};
class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
@ -78,7 +78,7 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
Swift::BoostIOServiceThread m_boostIOServiceThread;
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> m_conn;
bool m_firstPing;
Swift::FullPayloadSerializerCollection collection;
Swift::XMPPParser *m_xmppParser;
Swift::FullPayloadParserFactoryCollection m_collection2;
@ -155,11 +155,11 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
if (m_handlers[user]->m_id2resource.find(stanza->getID()) != m_handlers[user]->m_id2resource.end()) {
std::string resource = m_handlers[user]->m_id2resource[stanza->getID()];
if (resource.empty()) {
iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain()));
iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain()));
} else {
iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain(), resource));
iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain(), resource));
}
m_handlers[user]->m_id2resource.erase(stanza->getID());
}
client->getIQRouter()->sendIQ(iq);
@ -246,38 +246,38 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
Swift::Presence::ref lastPresence = oracle->getLastPresence(item.getJID());
pbnetwork::StatusType status = lastPresence ? ((pbnetwork::StatusType) lastPresence->getShow()) : pbnetwork::STATUS_NONE;
handleBuddyChanged(user, item.getJID().toBare().toString(),
item.getName(), item.getGroups(), status);
item.getName(), item.getGroups(), status);
}
}
void handleSwiftPresenceChanged(const std::string &user, Swift::Presence::ref presence) {
// SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
// if (client->getMUCRegistry()->isMUC(presence->getFrom().toBare())) {
// return;
// }
//
// if (presence->getPayload<Swift::MUCUserPayload>() != NULL || presence->getPayload<Swift::MUCPayload>() != NULL) {
// return;
// }
//
// LOG4CXX_INFO(logger, user << ": " << presence->getFrom().toBare().toString() << " presence changed");
//
// std::string message = presence->getStatus();
// std::string photo = "";
//
// SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::VCardUpdate> update = presence->getPayload<Swift::VCardUpdate>();
// if (update) {
// photo = update->getPhotoHash();
// }
//
// boost::optional<Swift::XMPPRosterItem> item = m_users[user]->getRoster()->getItem(presence->getFrom());
// if (item) {
// handleBuddyChanged(user, presence->getFrom().toBare().toString(), item->getName(), item->getGroups(), (pbnetwork::StatusType) presence->getShow(), message, photo);
// }
// else {
// std::vector<std::string> groups;
// handleBuddyChanged(user, presence->getFrom().toBare().toString(), presence->getFrom().toBare(), groups, (pbnetwork::StatusType) presence->getShow(), message, photo);
// }
// SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
// if (client->getMUCRegistry()->isMUC(presence->getFrom().toBare())) {
// return;
// }
//
// if (presence->getPayload<Swift::MUCUserPayload>() != NULL || presence->getPayload<Swift::MUCPayload>() != NULL) {
// return;
// }
//
// LOG4CXX_INFO(logger, user << ": " << presence->getFrom().toBare().toString() << " presence changed");
//
// std::string message = presence->getStatus();
// std::string photo = "";
//
// SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::VCardUpdate> update = presence->getPayload<Swift::VCardUpdate>();
// if (update) {
// photo = update->getPhotoHash();
// }
//
// boost::optional<Swift::XMPPRosterItem> item = m_users[user]->getRoster()->getItem(presence->getFrom());
// if (item) {
// handleBuddyChanged(user, presence->getFrom().toBare().toString(), item->getName(), item->getGroups(), (pbnetwork::StatusType) presence->getShow(), message, photo);
// }
// else {
// std::vector<std::string> groups;
// handleBuddyChanged(user, presence->getFrom().toBare().toString(), presence->getFrom().toBare(), groups, (pbnetwork::StatusType) presence->getShow(), message, photo);
// }
presence->setTo(user);
std::string xml = safeByteArrayToString(serializer->serializeElement(presence));
sendRawXML(xml);
@ -343,7 +343,7 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
if (client) {
client->onConnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftConnected, this, user));
// client->onDisconnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
// client->onDisconnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
client->onMessageReceived.disconnect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
client->getRoster()->onInitialRosterPopulated.disconnect(boost::bind(&SwiftenPlugin::handleSwiftRosterReceived, this, user));
client->getPresenceOracle()->onPresenceChange.disconnect(boost::bind(&SwiftenPlugin::handleSwiftPresenceChanged, this, user, _1));
@ -369,7 +369,7 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
roster->addItem(item);
Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(roster, client->getIQRouter());
// request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
// request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
request->send();
client->getSubscriptionManager()->requestSubscription(buddyName);
}
@ -380,7 +380,7 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
roster->addItem(item);
Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(roster, client->getIQRouter());
// request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
// request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
request->send();
}
@ -394,7 +394,7 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
roster->addItem(item);
Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(roster, client->getIQRouter());
// request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
// request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
request->send();
}
}

View File

@ -11,7 +11,7 @@ bool HTTPRequest::init()
curl_easy_setopt(curlhandle, CURLOPT_PROXYAUTH, (long)CURLAUTH_ANY);
return true;
}
LOG4CXX_ERROR(logger, "Couldn't Initialize curl!")
LOG4CXX_ERROR(logger, "Couldn't Initialize curl!");
return false;
}
@ -25,47 +25,47 @@ void HTTPRequest::setProxy(std::string IP, std::string port, std::string usernam
curl_easy_setopt(curlhandle, CURLOPT_PROXYUSERPWD, proxyUserPass.c_str());
}
} else {
LOG4CXX_ERROR(logger, "Trying to set proxy while CURL isn't initialized")
LOG4CXX_ERROR(logger, "Trying to set proxy while CURL isn't initialized");
}
}
int HTTPRequest::curlCallBack(char* data, size_t size, size_t nmemb, HTTPRequest* obj)
{
int writtenSize = 0;
if(obj && data) {
obj->callbackdata.append(data, size*nmemb);
writtenSize = (int)(size*nmemb);
}
return writtenSize;
int writtenSize = 0;
if(obj && data) {
obj->callbackdata.append(data, size*nmemb);
writtenSize = (int)(size*nmemb);
}
return writtenSize;
}
bool HTTPRequest::GET(std::string url, std::string &data)
bool HTTPRequest::GET(std::string url, std::string &data)
{
if(curlhandle) {
curl_easy_setopt(curlhandle, CURLOPT_CUSTOMREQUEST, NULL);
curl_easy_setopt(curlhandle, CURLOPT_ENCODING, "");
data = "";
callbackdata = "";
memset(curl_errorbuffer, 0, 1024);
curl_easy_setopt(curlhandle, CURLOPT_ERRORBUFFER, curl_errorbuffer);
curl_easy_setopt(curlhandle, CURLOPT_WRITEFUNCTION, curlCallBack);
curl_easy_setopt(curlhandle, CURLOPT_WRITEDATA, this);
/* Set http request and url */
curl_easy_setopt(curlhandle, CURLOPT_HTTPGET, 1);
// curl_easy_setopt(curlhandle, CURLOPT_VERBOSE, 1);
// curl_easy_setopt(curlhandle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curlhandle, CURLOPT_URL, url.c_str());
/* Send http request and return status*/
if(CURLE_OK == curl_easy_perform(curlhandle)) {
data = callbackdata;
return true;
}
} else {
LOG4CXX_ERROR(logger, "CURL not initialized!")
LOG4CXX_ERROR(logger, "CURL not initialized!");
strcpy(curl_errorbuffer, "CURL not initialized!");
}
return false;

View File

@ -4,20 +4,20 @@ DEFINE_LOGGER(logger, "CreateFriendRequest")
void CreateFriendRequest::run()
{
LOG4CXX_INFO(logger, user << " - Sending follow request for " << frnd)
LOG4CXX_INFO(logger, user << " - Sending follow request for " << frnd);
replyMsg = "";
success = twitObj->friendshipCreate(frnd, false);
if(success) {
twitObj->getLastWebResponse(replyMsg);
LOG4CXX_INFO(logger, user << replyMsg)
LOG4CXX_INFO(logger, user << replyMsg);
friendInfo = getUser(replyMsg);
if(friendInfo.getScreenName() == "") {LOG4CXX_INFO(logger, user << " - Was unable to fetch user info for " << frnd)}
if(friendInfo.getScreenName() == "") LOG4CXX_INFO(logger, user << " - Was unable to fetch user info for " << frnd);
HTTPRequest req;
std::string img;
req.init();
req.setProxy(twitObj->getProxyServerIp(), twitObj->getProxyServerPort(), twitObj->getProxyUserName(), twitObj->getProxyPassword());
@ -36,15 +36,15 @@ void CreateFriendRequest::finalize()
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - Curl error: " << curlerror)
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - Curl error: " << curlerror);
callBack(user, friendInfo, profileImg, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) {
LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
LOG4CXX_ERROR(logger, user << " - " << error.getMessage());
}
else LOG4CXX_INFO(logger, user << ": Now following " << frnd)
else LOG4CXX_INFO(logger, user << ": Now following " << frnd);
callBack(user, friendInfo, profileImg, error);
}
}

View File

@ -7,9 +7,9 @@ void DestroyFriendRequest::run()
success = twitObj->friendshipDestroy(frnd, false);
if(success) {
twitObj->getLastWebResponse(replyMsg);
LOG4CXX_INFO(logger, user << replyMsg)
LOG4CXX_INFO(logger, user << replyMsg);
friendInfo = getUser(replyMsg);
if(friendInfo.getScreenName() == "") LOG4CXX_INFO(logger, user << " - Was unable to fetch user info for " << frnd);
@ -22,12 +22,12 @@ void DestroyFriendRequest::finalize()
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " Curl error: " << curlerror)
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " Curl error: " << curlerror);
callBack(user, friendInfo, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage());
callBack(user, friendInfo, error);
}
}

View File

@ -2,7 +2,7 @@
DEFINE_LOGGER(logger, "DirectMessageRequest")
void DirectMessageRequest::run()
void DirectMessageRequest::run()
{
replyMsg = "";
if(username != "") success = twitObj->directMessageSend(username, data, false);
@ -20,13 +20,16 @@ void DirectMessageRequest::finalize()
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " Curl error: " << curlerror);
callBack(user, username, messages, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
else LOG4CXX_INFO(logger, user << " - " << replyMsg)
callBack(user, username, messages, error);
if(error.getMessage().length()) {
LOG4CXX_ERROR(logger, user << " - " << error.getMessage());
} else {
LOG4CXX_INFO(logger, user << " - " << replyMsg);
}
callBack(user, username, messages, error);
}
}

View File

@ -3,16 +3,16 @@
DEFINE_LOGGER(logger, "FetchFriends")
void FetchFriends::run()
{
replyMsg = "";
void FetchFriends::run()
{
replyMsg = "";
std::string next = "";
success = twitObj->friendsIdsGet(next, twitObj->getTwitterUsername(), false);
if(!success) return;
if(!success) return;
twitObj->getLastWebResponse( replyMsg );
std::vector<std::string> IDs = getIDs( replyMsg );
success = twitObj->userLookup(IDs, true);
if(!success) return;
@ -22,13 +22,13 @@ void FetchFriends::run()
HTTPRequest req;
req.init();
req.setProxy(twitObj->getProxyServerIp(), twitObj->getProxyServerPort(), twitObj->getProxyUserName(), twitObj->getProxyPassword());
for(int i=0 ; i<friends.size() ; i++) {
std::string img;
friendAvatars.push_back("");
if(req.GET(friends[i].getProfileImgURL(), img)) friendAvatars[i] = img;
else {
LOG4CXX_INFO(logger, "Warning: Couldn't fetch Profile Image for " << user << "'s friend " << friends[i].getScreenName())
LOG4CXX_INFO(logger, "Warning: Couldn't fetch Profile Image for " << user << "'s friend " << friends[i].getScreenName());
}
}
}
@ -39,12 +39,12 @@ void FetchFriends::finalize()
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - " << curlerror)
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - " << curlerror);
callBack(user, friends, friendAvatars, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
callBack(user, friends, friendAvatars, error);
}
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage());
callBack(user, friends, friendAvatars, error);
}
}

View File

@ -2,8 +2,8 @@
DEFINE_LOGGER(logger, "PINExchangeProcess")
void PINExchangeProcess::run()
{
LOG4CXX_INFO(logger, user << ": Sending PIN " << data)
LOG4CXX_INFO(logger, user << " " << twitObj->getProxyServerIp() << " " << twitObj->getProxyServerPort())
LOG4CXX_INFO(logger, user << ": Sending PIN " << data);
LOG4CXX_INFO(logger, user << " " << twitObj->getProxyServerIp() << " " << twitObj->getProxyServerPort());
twitObj->getOAuth().setOAuthPin( data );
success = twitObj->oAuthAccessToken();
}
@ -11,7 +11,7 @@ void PINExchangeProcess::run()
void PINExchangeProcess::finalize()
{
if(!success) {
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token!")
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token!");
np->handleMessage(user, "twitter.com", "Error while exchanging PIN for Access Token!");
np->handleLogoutRequest(user, "");
} else {
@ -22,7 +22,7 @@ void PINExchangeProcess::finalize()
Error error = getErrorMessage(replyMsg);
if(error.getMessage().length()) {
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token! " << error.getMessage())
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token! " << error.getMessage());
np->handleMessage(user, "twitter.com", error.getMessage());
np->handleLogoutRequest(user, "");
return;
@ -47,24 +47,24 @@ void PINExchangeProcess::finalize()
/*void handlePINExchange(const std::string &user, std::string &data) {
sessions[user]->getOAuth().setOAuthPin( data );
if (sessions[user]->oAuthAccessToken() == false) {
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token!")
LOG4CXX_ERROR(logger, user << ": Error while exchanging PIN for Access Token!");
handleLogoutRequest(user, "");
return;
}
std::string OAuthAccessTokenKey, OAuthAccessTokenSecret;
sessions[user]->getOAuth().getOAuthTokenKey( OAuthAccessTokenKey );
sessions[user]->getOAuth().getOAuthTokenSecret( OAuthAccessTokenSecret );
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
handleLogoutRequest(user, "");
return;
}
storagebackend->updateUserSetting((long)info.id, OAUTH_KEY, OAuthAccessTokenKey);
storagebackend->updateUserSetting((long)info.id, OAUTH_SECRET, OAuthAccessTokenSecret);
storagebackend->updateUserSetting((long)info.id, OAUTH_KEY, OAuthAccessTokenKey);
storagebackend->updateUserSetting((long)info.id, OAUTH_SECRET, OAuthAccessTokenSecret);
connectionState[user] = CONNECTED;
LOG4CXX_INFO(logger, user << ": Sent PIN " << data << " and obtained Access Token");

View File

@ -1,8 +1,8 @@
#include "ProfileImageRequest.h"
#include "../HTTPRequest.h"
DEFINE_LOGGER(logger, "ProfileImageRequest")
void ProfileImageRequest::run()
{
void ProfileImageRequest::run()
{
HTTPRequest req;
req.init();
req.setProxy(ip, port, puser, ppasswd);
@ -14,13 +14,13 @@ void ProfileImageRequest::finalize()
{
Error errResponse;
if(!success) {
LOG4CXX_ERROR(logger, user << " - " << error)
LOG4CXX_ERROR(logger, user << " - " << error);
img = "";
errResponse.setMessage(error);
callBack(user, buddy, img, reqID, errResponse);
} else {
LOG4CXX_INFO(logger, user << " - " << callbackdata);
img = callbackdata;
callBack(user, buddy, img, reqID, errResponse);
}
callBack(user, buddy, img, reqID, errResponse);
}
}

View File

@ -2,7 +2,7 @@
DEFINE_LOGGER(logger, "RetweetRequest")
void RetweetRequest::run()
{
LOG4CXX_INFO(logger, user << " Retweeting " << data)
LOG4CXX_INFO(logger, user << " Retweeting " << data);
success = twitObj->retweetById( data );
}
@ -12,14 +12,17 @@ void RetweetRequest::finalize()
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " Curl error: " << curlerror)
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " Curl error: " << curlerror);
callBack(user, error);
} else {
twitObj->getLastWebResponse(replyMsg);
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
else LOG4CXX_INFO(logger, user << " " << replyMsg);
if(error.getMessage().length()) {
LOG4CXX_ERROR(logger, user << " - " << error.getMessage());
} else {
LOG4CXX_INFO(logger, user << " " << replyMsg);
}
callBack(user, error);
}
}

View File

@ -2,7 +2,7 @@
#include "../TwitterResponseParser.h"
DEFINE_LOGGER(logger, "StatusUpdateRequest")
void StatusUpdateRequest::run()
void StatusUpdateRequest::run()
{
replyMsg = "";
success = twitObj->statusUpdate(data);
@ -18,13 +18,16 @@ void StatusUpdateRequest::finalize()
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - Curl error: " << curlerror);
callBack(user, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
else LOG4CXX_INFO(logger, "Updated status for " << user << ": " << data);
if(error.getMessage().length()) {
LOG4CXX_ERROR(logger, user << " - " << error.getMessage());
} else {
LOG4CXX_INFO(logger, "Updated status for " << user << ": " << data);
}
callBack(user, error);
}
}

View File

@ -1,15 +1,15 @@
#include "TimelineRequest.h"
DEFINE_LOGGER(logger, "TimelineRequest")
void TimelineRequest::run()
{
LOG4CXX_INFO(logger, "Sending timeline request for user " << userRequested)
{
LOG4CXX_INFO(logger, "Sending timeline request for user " << userRequested);
if(userRequested != "") success = twitObj->timelineUserGet(false, false, 20, userRequested, false);
else success = twitObj->timelineHomeGet(since_id);
if(!success) return;
replyMsg = "";
replyMsg = "";
twitObj->getLastWebResponse( replyMsg );
//LOG4CXX_INFO(logger, user << " - " << replyMsg.length() << " " << replyMsg << "\n" );
tweets = getTimeline(replyMsg);
@ -21,12 +21,12 @@ void TimelineRequest::finalize()
if(!success) {
std::string curlerror;
twitObj->getLastCurlError(curlerror);
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - Curl error: " << curlerror)
error.setMessage(curlerror);
LOG4CXX_ERROR(logger, user << " - Curl error: " << curlerror);
callBack(user, userRequested, tweets, error);
} else {
error = getErrorMessage(replyMsg);
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage())
if(error.getMessage().length()) LOG4CXX_ERROR(logger, user << " - " << error.getMessage());
callBack(user, userRequested, tweets, error);
}
}
}

View File

@ -23,20 +23,20 @@ const std::string OLD_APP_SECRET = "EveLmCXJIg2R7BTCpm6OWV8YyX49nI0pxnYXh7JMvDg"
#define abs(x) ((x)<0?-(x):(x))
#define SHA(x) (Swift::Hexify::hexify(Swift::SHA1::getHash(Swift::createByteArray((x)))))
//Compares two +ve intergers 'a' and 'b' represented as strings
//Compares two +ve intergers 'a' and 'b' represented as strings
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()
TwitterPlugin::TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, StorageBackend *storagebackend, const std::string &host, int port) : NetworkPlugin()
{
this->config = config;
this->storagebackend = storagebackend;
@ -60,9 +60,9 @@ TwitterPlugin::TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, Stora
exit(1);
}
adminLegacyName = "twitter.com";
adminChatRoom = "#twitter";
adminNickName = "twitter";
adminLegacyName = "twitter.com";
adminChatRoom = "#twitter";
adminNickName = "twitter";
adminAlias = "twitter";
OAUTH_KEY = "twitter_oauth_token";
@ -89,12 +89,12 @@ TwitterPlugin::TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, Stora
#if HAVE_SWIFTEN_3
cryptoProvider = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::CryptoProvider>(Swift::PlatformCryptoProvider::create());
#endif
LOG4CXX_INFO(logger, "Starting the plugin.");
}
TwitterPlugin::~TwitterPlugin()
TwitterPlugin::~TwitterPlugin()
{
delete storagebackend;
std::set<std::string>::iterator it;
@ -103,7 +103,7 @@ TwitterPlugin::~TwitterPlugin()
}
// Send data to NetworkPlugin server
void TwitterPlugin::sendData(const std::string &string)
void TwitterPlugin::sendData(const std::string &string)
{
m_conn->write(Swift::createSafeByteArray(string));
}
@ -125,42 +125,42 @@ void TwitterPlugin::_handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::
}
// User trying to login into his twitter account
void TwitterPlugin::handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password)
void TwitterPlugin::handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password)
{
if(userdb.count(user) && (userdb[user].connectionState == NEW ||
userdb[user].connectionState == CONNECTED ||
if(userdb.count(user) && (userdb[user].connectionState == NEW ||
userdb[user].connectionState == CONNECTED ||
userdb[user].connectionState == WAITING_FOR_PIN)) {
LOG4CXX_INFO(logger, std::string("A session corresponding to ") + user + std::string(" is already active"))
LOG4CXX_INFO(logger, std::string("A session corresponding to ") + user + std::string(" is already active"));
return;
}
LOG4CXX_INFO(logger, std::string("Received login request for ") + user)
LOG4CXX_INFO(logger, std::string("Received login request for ") + user);
initUserSession(user, legacyName, password);
handleConnected(user);
LOG4CXX_INFO(logger, "SPECTRUM 1 USER? - " << (userdb[user].spectrum1User? "true" : "false"))
LOG4CXX_INFO(logger, user << ": Adding Buddy " << adminLegacyName << " " << adminAlias)
LOG4CXX_INFO(logger, "SPECTRUM 1 USER? - " << (userdb[user].spectrum1User? "true" : "false"));
LOG4CXX_INFO(logger, user << ": Adding Buddy " << adminLegacyName << " " << adminAlias);
handleBuddyChanged(user, adminLegacyName, adminAlias, std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
userdb[user].nickName = "";
LOG4CXX_INFO(logger, "Querying database for usersettings of " << user)
LOG4CXX_INFO(logger, "Querying database for usersettings of " << user);
std::string key, secret;
getUserOAuthKeyAndSecret(user, key, secret);
if(key == "" || secret == "") {
LOG4CXX_INFO(logger, "Intiating OAuth Flow for user " << user)
if(key == "" || secret == "") {
LOG4CXX_INFO(logger, "Intiating OAuth Flow for user " << user);
setTwitterMode(user, 0);
tp->runAsThread(new OAuthFlow(np, userdb[user].sessions, user, userdb[user].sessions->getTwitterUsername()));
} else {
LOG4CXX_INFO(logger, user << " is already registerd. Using the stored oauth key and secret")
LOG4CXX_INFO(logger, key << " " << secret)
LOG4CXX_INFO(logger, user << " is already registerd. Using the stored oauth key and secret");
LOG4CXX_INFO(logger, key << " " << secret);
pinExchangeComplete(user, key, secret);
}
}
// User logging out
void TwitterPlugin::handleLogoutRequest(const std::string &user, const std::string &legacyName)
void TwitterPlugin::handleLogoutRequest(const std::string &user, const std::string &legacyName)
{
if (userdb.count(user)) {
delete userdb[user].sessions;
@ -176,8 +176,8 @@ void TwitterPlugin::handleLogoutRequest(const std::string &user, const std::stri
// User joining a Chatroom
void TwitterPlugin::handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &password)
{
if(room == adminChatRoom) {
LOG4CXX_INFO(logger, "Received Join Twitter room request for " << user << " '" << nickname << "'")
if(room == adminChatRoom) {
LOG4CXX_INFO(logger, "Received Join Twitter room request for " << user << " '" << nickname << "'");
setTwitterMode(user, 2);
handleParticipantChanged(user, nickname, room, 0, pbnetwork::STATUS_ONLINE);
@ -188,62 +188,62 @@ void TwitterPlugin::handleJoinRoomRequest(const std::string &user, const std::st
boost::bind(&TwitterPlugin::populateRoster, this, _1, _2, _3, _4)));
} else {
setTwitterMode(user, 0);
LOG4CXX_ERROR(logger, "Couldn't connect to chatroom - " << room <<"! Try twitter-chatroom as the chatroom to access Twitter account")
LOG4CXX_ERROR(logger, "Couldn't connect to chatroom - " << room <<"! Try twitter-chatroom as the chatroom to access Twitter account");
handleMessage(user, adminLegacyName, "Couldn't connect to chatroom! Try twitter-chatroom as the chatroom to access Twitter account");
}
}
}
// User leaving a Chatroom
void TwitterPlugin::handleLeaveRoomRequest(const std::string &user, const std::string &room)
{
if(room == adminChatRoom && onlineUsers.count(user)) {
LOG4CXX_INFO(logger, "Leaving chatroom! Switching back to default mode 0")
LOG4CXX_INFO(logger, "Leaving chatroom! Switching back to default mode 0");
setTwitterMode(user, 0);
handleBuddyChanged(user, adminLegacyName, adminAlias, std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
}
}
// Messages to be sent to Twitter
void TwitterPlugin::handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml, const std::string &/*id*/)
// Messages to be sent to Twitter
void TwitterPlugin::handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml, const std::string &/*id*/)
{
LOG4CXX_INFO(logger, "Received " << user << " --> " << legacyName << " - " << message)
LOG4CXX_INFO(logger, "Received " << user << " --> " << legacyName << " - " << message);
if(legacyName == adminLegacyName || legacyName == adminChatRoom) {
std::string cmd = "", data = "";
/** Parsing the message - Assuming message format to be <cmd>[ ]*<data>**/
/** Parsing the message - Assuming message format to be <cmd>[ ]*<data>**/
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);
/***********************************************************************/
if(cmd == "#pin")
if(cmd == "#pin")
tp->runAsThread(new PINExchangeProcess(np, userdb[user].sessions, user, data));
else if(cmd == "#help")
else if(cmd == "#help")
tp->runAsThread(new HelpMessageRequest(user, CONFIG_STRING(config, "service.jid"), boost::bind(&TwitterPlugin::helpMessageResponse, this, _1, _2)));
else if(cmd[0] == '@') {
std::string username = cmd.substr(1);
std::string username = cmd.substr(1);
tp->runAsThread(new DirectMessageRequest(userdb[user].sessions, user, username, data,
boost::bind(&TwitterPlugin::directMessageResponse, this, _1, _2, _3, _4)));
}
else if(cmd == "#status")
else if(cmd == "#status")
tp->runAsThread(new StatusUpdateRequest(userdb[user].sessions, user, data,
boost::bind(&TwitterPlugin::statusUpdateResponse, this, _1, _2)));
else if(cmd == "#timeline")
else if(cmd == "#timeline")
tp->runAsThread(new TimelineRequest(userdb[user].sessions, user, data, "",
boost::bind(&TwitterPlugin::displayTweets, this, _1, _2, _3, _4)));
else if(cmd == "#friends")
else if(cmd == "#friends")
tp->runAsThread(new FetchFriends(userdb[user].sessions, user,
boost::bind(&TwitterPlugin::displayFriendlist, this, _1, _2, _3, _4)));
else if(cmd == "#follow")
else if(cmd == "#follow")
tp->runAsThread(new CreateFriendRequest(userdb[user].sessions, user, data.substr(0,data.find('@')),
boost::bind(&TwitterPlugin::createFriendResponse, this, _1, _2, _3, _4)));
else if(cmd == "#unfollow")
else if(cmd == "#unfollow")
tp->runAsThread(new DestroyFriendRequest(userdb[user].sessions, user, data.substr(0,data.find('@')),
boost::bind(&TwitterPlugin::deleteFriendResponse, this, _1, _2, _3)));
else if(cmd == "#retweet")
else if(cmd == "#retweet")
tp->runAsThread(new RetweetRequest(userdb[user].sessions, user, data,
boost::bind(&TwitterPlugin::RetweetResponse, this, _1, _2)));
else if(cmd == "#mode") {
@ -259,13 +259,13 @@ void TwitterPlugin::handleMessageSendRequest(const std::string &user, const std:
setTwitterMode(user, m);
if((userdb[user].twitterMode == SINGLECONTACT || userdb[user].twitterMode == CHATROOM) && prevm == MULTIPLECONTACT) clearRoster(user);
else if(userdb[user].twitterMode == MULTIPLECONTACT)
else if(userdb[user].twitterMode == MULTIPLECONTACT)
tp->runAsThread(new FetchFriends(userdb[user].sessions, user, boost::bind(&TwitterPlugin::populateRoster, this, _1, _2, _3, _4)));
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("Changed mode to ") + data, userdb[user].twitterMode == CHATROOM ? adminNickName : "");
LOG4CXX_INFO(logger, user << ": Changed mode to " << data << " <" << (userdb[user].twitterMode == CHATROOM ? adminNickName : "") << ">" )
LOG4CXX_INFO(logger, user << ": Changed mode to " << data << " <" << (userdb[user].twitterMode == CHATROOM ? adminNickName : "") << ">" );
}
else if(userdb[user].twitterMode == CHATROOM) {
@ -281,9 +281,9 @@ void TwitterPlugin::handleMessageSendRequest(const std::string &user, const std:
}
else handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
"Unknown command! Type #help for a list of available commands.", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
}
else {
else {
std::string buddy = legacyName;
if(userdb[user].twitterMode == CHATROOM) buddy = legacyName.substr(legacyName.find("/") + 1);
if(legacyName != "twitter") {
@ -293,45 +293,45 @@ void TwitterPlugin::handleMessageSendRequest(const std::string &user, const std:
}
}
void TwitterPlugin::handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups)
void TwitterPlugin::handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups)
{
if(userdb[user].connectionState != CONNECTED) {
LOG4CXX_ERROR(logger, user << " is not connected to twitter!")
LOG4CXX_ERROR(logger, user << " is not connected to twitter!");
return;
}
LOG4CXX_INFO(logger, user << " - Adding Twitter contact " << buddyName)
tp->runAsThread(new CreateFriendRequest(userdb[user].sessions, user, buddyName,
LOG4CXX_INFO(logger, user << " - Adding Twitter contact " << buddyName);
tp->runAsThread(new CreateFriendRequest(userdb[user].sessions, user, buddyName,
boost::bind(&TwitterPlugin::createFriendResponse, this, _1, _2, _3, _4)));
}
void TwitterPlugin::handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups)
void TwitterPlugin::handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups)
{
if(userdb[user].connectionState != CONNECTED) {
LOG4CXX_ERROR(logger, user << " is not connected to twitter!")
LOG4CXX_ERROR(logger, user << " is not connected to twitter!");
return;
}
if (getTwitterMode(user) == MULTIPLECONTACT) {
LOG4CXX_ERROR(logger, user << " not removing Twitter contact " << buddyName << ", because the mode is not MULTIPLECONTACT")
LOG4CXX_ERROR(logger, user << " not removing Twitter contact " << buddyName << ", because the mode is not MULTIPLECONTACT");
return;
}
LOG4CXX_INFO(logger, user << " - Removing Twitter contact " << buddyName)
tp->runAsThread(new DestroyFriendRequest(userdb[user].sessions, user, buddyName,
LOG4CXX_INFO(logger, user << " - Removing Twitter contact " << buddyName);
tp->runAsThread(new DestroyFriendRequest(userdb[user].sessions, user, buddyName,
boost::bind(&TwitterPlugin::deleteFriendResponse, this, _1, _2, _3)));
}
void TwitterPlugin::handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id)
{
if(userdb[user].connectionState != CONNECTED) {
LOG4CXX_ERROR(logger, user << " is not connected to twitter!")
LOG4CXX_ERROR(logger, user << " is not connected to twitter!");
return;
}
LOG4CXX_INFO(logger, user << " - VCardRequest for " << legacyName << ", " << userdb[user].buddiesInfo[legacyName].getProfileImgURL())
if(getTwitterMode(user) != SINGLECONTACT && userdb[user].buddies.count(legacyName)
LOG4CXX_INFO(logger, user << " - VCardRequest for " << legacyName << ", " << userdb[user].buddiesInfo[legacyName].getProfileImgURL());
if(getTwitterMode(user) != SINGLECONTACT && userdb[user].buddies.count(legacyName)
&& userdb[user].buddiesInfo[legacyName].getProfileImgURL().length()) {
if(userdb[user].buddiesImgs.count(legacyName) == 0) {
tp->runAsThread(new ProfileImageRequest(config, user, legacyName, userdb[user].buddiesInfo[legacyName].getProfileImgURL(), id,
@ -368,13 +368,13 @@ void TwitterPlugin::pollForDirectMessages()
}
bool TwitterPlugin::getUserOAuthKeyAndSecret(const std::string user, std::string &key, std::string &secret)
bool TwitterPlugin::getUserOAuthKeyAndSecret(const std::string user, std::string &key, std::string &secret)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
@ -384,13 +384,13 @@ bool TwitterPlugin::getUserOAuthKeyAndSecret(const std::string user, std::string
return true;
}
bool TwitterPlugin::checkSpectrum1User(const std::string user)
bool TwitterPlugin::checkSpectrum1User(const std::string user)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
@ -398,19 +398,19 @@ bool TwitterPlugin::checkSpectrum1User(const std::string user)
int type = TYPE_STRING;
storagebackend->getUserSetting((long)info.id, "first_synchronization_done", type, first_synchronization_done);
LOG4CXX_INFO(logger, "first_synchronization_done: " << first_synchronization_done)
LOG4CXX_INFO(logger, "first_synchronization_done: " << first_synchronization_done);
if(first_synchronization_done.length()) return true;
return false;
}
int TwitterPlugin::getTwitterMode(const std::string user)
int TwitterPlugin::getTwitterMode(const std::string user)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return -1;
}
@ -425,18 +425,18 @@ int TwitterPlugin::getTwitterMode(const std::string user)
return m;
}
bool TwitterPlugin::setTwitterMode(const std::string user, int m)
bool TwitterPlugin::setTwitterMode(const std::string user, int m)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
if(m < 0 || m > 2) {
LOG4CXX_ERROR(logger, "Unknown mode " << m <<". Using default mode 0")
LOG4CXX_ERROR(logger, "Unknown mode " << m <<". Using default mode 0");
m = 0;
}
@ -444,23 +444,23 @@ bool TwitterPlugin::setTwitterMode(const std::string user, int m)
//int type;
std::string s_m = std::string(1,m+'0');
LOG4CXX_INFO(logger, "Storing mode " << m <<" for user " << user)
LOG4CXX_INFO(logger, "Storing mode " << m <<" for user " << user);
storagebackend->updateUserSetting((long)info.id, MODE, s_m);
return true;
}
bool TwitterPlugin::storeUserOAuthKeyAndSecret(const std::string user, const std::string OAuthKey, const std::string OAuthSecret)
bool TwitterPlugin::storeUserOAuthKeyAndSecret(const std::string user, const std::string OAuthKey, const std::string OAuthSecret)
{
boost::mutex::scoped_lock lock(dblock);
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return false;
}
storagebackend->updateUserSetting((long)info.id, OAUTH_KEY, OAuthKey);
storagebackend->updateUserSetting((long)info.id, OAUTH_KEY, OAuthKey);
storagebackend->updateUserSetting((long)info.id, OAUTH_SECRET, OAuthSecret);
return true;
}
@ -471,21 +471,21 @@ void TwitterPlugin::initUserSession(const std::string user, const std::string le
std::string username = legacyName;
std::string passwd = password;
LOG4CXX_INFO(logger, username + " " + passwd)
LOG4CXX_INFO(logger, username + " " + passwd);
userdb[user].sessions = new twitCurl();
if(CONFIG_HAS_KEY(config,"proxy.server")) {
userdb[user].sessions = new twitCurl();
if(CONFIG_HAS_KEY(config,"proxy.server")) {
std::string ip = CONFIG_STRING(config,"proxy.server");
std::ostringstream out;
std::ostringstream out;
out << CONFIG_INT(config,"proxy.port");
std::string port = out.str();
std::string puser = CONFIG_STRING(config,"proxy.user");
std::string ppasswd = CONFIG_STRING(config,"proxy.password");
LOG4CXX_INFO(logger, ip << " " << port << " " << puser << " " << ppasswd)
LOG4CXX_INFO(logger, ip << " " << port << " " << puser << " " << ppasswd);
if(ip != "localhost" && port != "0") {
userdb[user].sessions->setProxyServerIp(ip);
userdb[user].sessions->setProxyServerPort(port);
@ -498,7 +498,7 @@ void TwitterPlugin::initUserSession(const std::string user, const std::string le
userdb[user].spectrum1User = checkSpectrum1User(user);
userdb[user].connectionState = NEW;
userdb[user].legacyName = username;
userdb[user].legacyName = username;
userdb[user].sessions->setTwitterUsername(username);
userdb[user].sessions->setTwitterPassword(passwd);
@ -511,24 +511,24 @@ void TwitterPlugin::initUserSession(const std::string user, const std::string le
}
}
void TwitterPlugin::OAuthFlowComplete(const std::string user, twitCurl *obj)
void TwitterPlugin::OAuthFlowComplete(const std::string user, twitCurl *obj)
{
boost::mutex::scoped_lock lock(userlock);
boost::mutex::scoped_lock lock(userlock);
delete userdb[user].sessions;
userdb[user].sessions = obj->clone();
userdb[user].sessions = obj->clone();
userdb[user].connectionState = WAITING_FOR_PIN;
}
}
void TwitterPlugin::pinExchangeComplete(const std::string user, const std::string OAuthAccessTokenKey, const std::string OAuthAccessTokenSecret)
void TwitterPlugin::pinExchangeComplete(const std::string user, const std::string OAuthAccessTokenKey, const std::string OAuthAccessTokenSecret)
{
boost::mutex::scoped_lock lock(userlock);
boost::mutex::scoped_lock lock(userlock);
userdb[user].sessions->getOAuth().setOAuthTokenKey( OAuthAccessTokenKey );
userdb[user].sessions->getOAuth().setOAuthTokenSecret( OAuthAccessTokenSecret );
userdb[user].connectionState = CONNECTED;
userdb[user].twitterMode = (mode)getTwitterMode(user);
if(userdb[user].twitterMode == MULTIPLECONTACT) {
tp->runAsThread(new FetchFriends(userdb[user].sessions, user, boost::bind(&TwitterPlugin::populateRoster, this, _1, _2, _3, _4)));
}
@ -536,16 +536,16 @@ void TwitterPlugin::pinExchangeComplete(const std::string user, const std::strin
onlineUsers.insert(user);
userdb[user].mostRecentTweetID = "";
userdb[user].mostRecentDirectMessageID = "";
}
}
void TwitterPlugin::updateLastTweetID(const std::string user, const std::string ID)
{
boost::mutex::scoped_lock lock(userlock);
boost::mutex::scoped_lock lock(userlock);
userdb[user].mostRecentTweetID = ID;
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return;
}
@ -553,7 +553,7 @@ void TwitterPlugin::updateLastTweetID(const std::string user, const std::string
}
std::string TwitterPlugin::getMostRecentTweetIDUnsafe(const std::string user)
{
{
std::string ID = "";
if(onlineUsers.count(user)) {
ID = userdb[user].mostRecentTweetID;
@ -561,7 +561,7 @@ std::string TwitterPlugin::getMostRecentTweetIDUnsafe(const std::string user)
int type = TYPE_STRING;
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
}
else {
storagebackend->getUserSetting(info.id, "twitter_last_tweet", type, ID);
@ -572,19 +572,19 @@ std::string TwitterPlugin::getMostRecentTweetIDUnsafe(const std::string user)
}
std::string TwitterPlugin::getMostRecentTweetID(const std::string user)
{
{
boost::mutex::scoped_lock lock(userlock);
return getMostRecentTweetIDUnsafe(user);
}
void TwitterPlugin::updateLastDMID(const std::string user, const std::string ID)
{
boost::mutex::scoped_lock lock(userlock);
boost::mutex::scoped_lock lock(userlock);
userdb[user].mostRecentDirectMessageID = ID;
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
return;
}
@ -599,7 +599,7 @@ std::string TwitterPlugin::getMostRecentDMIDUnsafe(const std::string user) {
int type = TYPE_STRING;
UserInfo info;
if(storagebackend->getUser(user, info) == false) {
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!")
LOG4CXX_ERROR(logger, "Didn't find entry for " << user << " in the database!");
}
else {
storagebackend->getUserSetting(info.id, "twitter_last_dm", type, ID);
@ -611,7 +611,7 @@ std::string TwitterPlugin::getMostRecentDMIDUnsafe(const std::string user) {
std::string TwitterPlugin::getMostRecentDMID(const std::string user)
{
boost::mutex::scoped_lock lock(userlock);
boost::mutex::scoped_lock lock(userlock);
return getMostRecentDMIDUnsafe(user);
}
@ -648,19 +648,19 @@ void TwitterPlugin::clearRoster(const std::string user)
userdb[user].buddies.clear();
}
void TwitterPlugin::populateRoster(std::string &user, std::vector<User> &friends, std::vector<std::string> &friendAvatars, Error &errMsg)
void TwitterPlugin::populateRoster(std::string &user, std::vector<User> &friends, std::vector<std::string> &friendAvatars, Error &errMsg)
{
if(errMsg.getMessage().length() == 0)
if(errMsg.getMessage().length() == 0)
{
for(int i=0 ; i<friends.size() ; i++) {
userdb[user].buddies.insert(friends[i].getScreenName());
userdb[user].buddiesInfo[friends[i].getScreenName()] = friends[i];
userdb[user].buddiesImgs[friends[i].getScreenName()] = friendAvatars[i];
if(userdb[user].twitterMode == MULTIPLECONTACT) {
std::string lastTweet = friends[i].getLastStatus().getTweet();
//LOG4CXX_INFO(logger, user << " - " << SHA(friendAvatars[i]))
handleBuddyChanged(user, friends[i].getScreenName(), friends[i].getUserName(), std::vector<std::string>(),
handleBuddyChanged(user, friends[i].getScreenName(), friends[i].getUserName(), std::vector<std::string>(),
#if HAVE_SWIFTEN_3
pbnetwork::STATUS_ONLINE, lastTweet, Swift::Hexify::hexify(cryptoProvider->getSHA1Hash(Swift::createByteArray(friendAvatars[i]))));
#else
@ -669,9 +669,9 @@ void TwitterPlugin::populateRoster(std::string &user, std::vector<User> &friends
}
else if(userdb[user].twitterMode == CHATROOM)
handleParticipantChanged(user, friends[i].getScreenName(), adminChatRoom, 0, pbnetwork::STATUS_ONLINE);
/*handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
friends[i].getScreenName() + " - " + friends[i].getLastStatus().getTweet(),
friends[i].getScreenName() + " - " + friends[i].getLastStatus().getTweet(),
userdb[user].twitterMode == CHATROOM ? adminNickName : "");*/
}
} else {
@ -688,24 +688,24 @@ void TwitterPlugin::populateRoster(std::string &user, std::vector<User> &friends
void TwitterPlugin::displayFriendlist(std::string &user, std::vector<User> &friends, std::vector<std::string> &friendAvatars, Error &errMsg)
{
if(errMsg.getMessage().length() == 0)
if(errMsg.getMessage().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, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
userlist, userdb[user].twitterMode == CHATROOM ? adminNickName : "");
userlist, userdb[user].twitterMode == CHATROOM ? adminNickName : "");
} else {
if (errMsg.isCurlError()) {
handleDisconnected(user, 3, errMsg.getMessage());
return;
}
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
}
void TwitterPlugin::displayTweets(std::string &user, std::string &userRequested, std::vector<Status> &tweets , Error &errMsg)
@ -727,13 +727,13 @@ void TwitterPlugin::displayTweets(std::string &user, std::string &userRequested,
tweets[i].getTweet() + " (MsgId: " + (tweets[i].getRetweetID().empty() ? tweets[i].getID() : tweets[i].getRetweetID()) + ")", tweets[i].getUserData().getScreenName(), "", tweets[i].getCreationTime(), true);
}
}
if(userdb[user].twitterMode == MULTIPLECONTACT) {
//Set as status user's last tweet
for(it=lastTweet.begin() ; it!=lastTweet.end() ; it++) {
int t = it->second;
if (userdb[user].buddies.count(tweets[t].getUserData().getScreenName()) != 0) {
handleBuddyChanged(user, tweets[t].getUserData().getScreenName(), tweets[t].getUserData().getUserName(),
handleBuddyChanged(user, tweets[t].getUserData().getScreenName(), tweets[t].getUserData().getUserName(),
std::vector<std::string>(), pbnetwork::STATUS_ONLINE, tweets[t].getTweet());
}
}
@ -750,7 +750,7 @@ void TwitterPlugin::displayTweets(std::string &user, std::string &userRequested,
return;
}
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
}
}
@ -776,30 +776,30 @@ void TwitterPlugin::directMessageResponse(std::string &user, std::string &userna
if(username != "") {
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
"Message delivered!", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
"Message delivered!", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
return;
}
if(!messages.size()) return;
if(userdb[user].twitterMode == SINGLECONTACT) {
std::string msglist = "";
std::string msgID = getMostRecentDMID(user);
std::string maxID = msgID;
for(int i=0 ; i < messages.size() ; i++) {
if(cmp(msgID, messages[i].getID()) == -1) {
msglist += " - " + messages[i].getSenderData().getScreenName() + ": " + messages[i].getMessage() + "\n";
if(cmp(maxID, messages[i].getID()) == -1) maxID = messages[i].getID();
}
}
}
if(msglist.length()) handleMessage(user, adminLegacyName, msglist, "");
if(msglist.length()) handleMessage(user, adminLegacyName, msglist, "");
updateLastDMID(user, maxID);
} else {
std::string msgID = getMostRecentDMID(user);
std::string maxID = msgID;
@ -811,9 +811,9 @@ void TwitterPlugin::directMessageResponse(std::string &user, std::string &userna
handleMessage(user, adminChatRoom, messages[i].getMessage() + " - <Direct Message>", messages[i].getSenderData().getScreenName());
if(cmp(maxID, messages[i].getID()) == -1) maxID = messages[i].getID();
}
}
if(maxID == getMostRecentDMID(user)) LOG4CXX_INFO(logger, "No new direct messages for " << user)
}
if(maxID == getMostRecentDMID(user)) LOG4CXX_INFO(logger, "No new direct messages for " << user);
updateLastDMID(user, maxID);
}
}
@ -832,12 +832,12 @@ void TwitterPlugin::createFriendResponse(std::string &user, User &frnd, std::str
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("You are now following ") + frnd.getScreenName(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
userdb[user].buddies.insert(frnd.getScreenName());
userdb[user].buddiesInfo[frnd.getScreenName()] = frnd;
userdb[user].buddiesImgs[frnd.getScreenName()] = img;
LOG4CXX_INFO(logger, user << " - " << frnd.getScreenName() << ", " << frnd.getProfileImgURL())
LOG4CXX_INFO(logger, user << " - " << frnd.getScreenName() << ", " << frnd.getProfileImgURL());
if(userdb[user].twitterMode == MULTIPLECONTACT) {
#if HAVE_SWIFTEN_3
handleBuddyChanged(user, frnd.getScreenName(), frnd.getUserName(), std::vector<std::string>(), pbnetwork::STATUS_ONLINE, "", Swift::byteArrayToString(cryptoProvider->getSHA1Hash(Swift::createByteArray(img))));
@ -856,24 +856,24 @@ void TwitterPlugin::deleteFriendResponse(std::string &user, User &frnd, Error &e
handleDisconnected(user, 3, errMsg.getMessage());
return;
}
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
return;
}
LOG4CXX_INFO(logger, user << " - " << frnd.getScreenName() << ", " << frnd.getProfileImgURL())
}
LOG4CXX_INFO(logger, user << " - " << frnd.getScreenName() << ", " << frnd.getProfileImgURL());
userdb[user].buddies.erase(frnd.getScreenName());
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
std::string("You are not following ") + frnd.getScreenName() + " anymore", userdb[user].twitterMode == CHATROOM ? adminNickName : "");
if (userdb[user].twitterMode == CHATROOM) {
handleParticipantChanged(user, frnd.getScreenName(), adminLegacyName, 0, pbnetwork::STATUS_NONE);
}
if(userdb[user].twitterMode == MULTIPLECONTACT) {
handleBuddyRemoved(user, frnd.getScreenName());
}
}
}
@ -902,7 +902,7 @@ void TwitterPlugin::profileImageResponse(std::string &user, std::string &buddy,
handleMessage(user, userdb[user].twitterMode == CHATROOM ? adminChatRoom : adminLegacyName,
errMsg.getMessage(), userdb[user].twitterMode == CHATROOM ? adminNickName : "");
} else {
LOG4CXX_INFO(logger, user << " - Sending VCard for " << buddy)
LOG4CXX_INFO(logger, user << " - Sending VCard for " << buddy);
handleVCard(user, reqID, buddy, buddy, "", img);
}
}

View File

@ -45,7 +45,7 @@ static std::string toIsoTime(std::string in) {
output_facet->format("%Y%m%dT%H%M%S"); // boost::local_time::local_time_facet::iso_time_format_specifier ?
ss >> ldt;
ss.str("");
ss << ldt;
ss << ldt;
return ss.str();
}
@ -53,7 +53,7 @@ EmbeddedStatus getEmbeddedStatus(const rapidjson::Value &element)
{
EmbeddedStatus status;
if(!element.IsObject()) {
LOG4CXX_ERROR(logger, "Not a status element!")
LOG4CXX_ERROR(logger, "Not a status element!");
return status;
}
status.setCreationTime( toIsoTime ( std::string( element[TwitterReponseTypes::created_at.c_str()].GetString() ) ) );
@ -68,15 +68,15 @@ EmbeddedStatus getEmbeddedStatus(const rapidjson::Value &element)
"" : std::string(element[TwitterReponseTypes::in_reply_to_screen_name.c_str()].GetString()) );
status.setRetweetCount( element[TwitterReponseTypes::retweet_count.c_str()].GetInt64() );
status.setFavorited( element[TwitterReponseTypes::favorited.c_str()].GetBool() );
status.setRetweeted( element[TwitterReponseTypes::retweeted.c_str()].GetBool());
status.setRetweeted( element[TwitterReponseTypes::retweeted.c_str()].GetBool());
return status;
}
User getUser(const rapidjson::Value &element)
User getUser(const rapidjson::Value &element)
{
User user;
if(!element.IsObject()) {
LOG4CXX_ERROR(logger, "Not a user element!")
LOG4CXX_ERROR(logger, "Not a user element!");
return user;
}
@ -85,12 +85,12 @@ User getUser(const rapidjson::Value &element)
user.setUserName( std::string( element[TwitterReponseTypes::name.c_str()].GetString() ) );
user.setProfileImgURL( std::string( element[TwitterReponseTypes::profile_image_url.c_str()].GetString() ) );
user.setNumberOfTweets( element[TwitterReponseTypes::statuses_count.c_str()].GetInt64() );
if(element[TwitterReponseTypes::status.c_str()].IsObject())
if(element[TwitterReponseTypes::status.c_str()].IsObject())
user.setLastStatus(getEmbeddedStatus(element[TwitterReponseTypes::status.c_str()]));
return user;
}
Status getStatus(const rapidjson::Value &element)
Status getStatus(const rapidjson::Value &element)
{
Status status;
@ -116,14 +116,14 @@ Status getStatus(const rapidjson::Value &element)
status.setCreationTime( toIsoTime ( std::string (rt[TwitterReponseTypes::created_at.c_str()].GetString() ) ) );
status.setUserData( getUser ( rt[TwitterReponseTypes::user.c_str()]) );
}
return status;
}
DirectMessage getDirectMessage(const rapidjson::Value &element)
DirectMessage getDirectMessage(const rapidjson::Value &element)
{
DirectMessage DM;
DM.setCreationTime( toIsoTime ( std::string( element[TwitterReponseTypes::created_at.c_str()].GetString() ) ) );
DM.setID( stringOf( element[TwitterReponseTypes::id.c_str()].GetInt64() ) );
DM.setMessage( unescape ( std::string( element[TwitterReponseTypes::text.c_str()].GetString() ), getUrlEntities(element) ) );
@ -140,16 +140,16 @@ std::vector<Status> getTimeline(std::string &json)
{
std::vector<Status> statuses;
rapidjson::Document rootElement;
if(rootElement.Parse<0>(json.c_str()).HasParseError()) {
LOG4CXX_ERROR(logger, "Error while parsing JSON")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "Error while parsing JSON");
LOG4CXX_ERROR(logger, json);
return statuses;
}
if(!rootElement.IsArray()) {
LOG4CXX_ERROR(logger, "JSON doesn't correspond to timeline:")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "JSON doesn't correspond to timeline:");
LOG4CXX_ERROR(logger, json);
return statuses;
}
@ -163,17 +163,17 @@ std::vector<DirectMessage> getDirectMessages(std::string &json)
{
std::vector<DirectMessage> DMs;
rapidjson::Document rootElement;
if(rootElement.Parse<0>(json.c_str()).HasParseError()) {
LOG4CXX_ERROR(logger, "Error while parsing JSON")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "Error while parsing JSON");
LOG4CXX_ERROR(logger, json);
return DMs;
}
if(!rootElement.IsArray()) {
LOG4CXX_ERROR(logger, "JSON doesn't correspond to direct messages:")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "JSON doesn't correspond to direct messages:");
LOG4CXX_ERROR(logger, json);
return DMs;
}
@ -187,40 +187,40 @@ std::vector<User> getUsers(std::string &json)
{
std::vector<User> users;
rapidjson::Document rootElement;
if(rootElement.Parse<0>(json.c_str()).HasParseError()) {
LOG4CXX_ERROR(logger, "Error while parsing JSON")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "Error while parsing JSON");
LOG4CXX_ERROR(logger, json);
return users;
}
if(!rootElement.IsArray()) {
LOG4CXX_ERROR(logger, "JSON doesn't correspond to user list:")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "JSON doesn't correspond to user list:");
LOG4CXX_ERROR(logger, json);
return users;
}
for(rapidjson::SizeType i = 0; i < rootElement.Size(); i++) {
users.push_back(getUser(rootElement[i]));
}
return users;
return users;
}
User getUser(std::string &json)
{
User user;
rapidjson::Document rootElement;
if(rootElement.Parse<0>(json.c_str()).HasParseError()) {
LOG4CXX_ERROR(logger, "Error while parsing JSON")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "Error while parsing JSON");
LOG4CXX_ERROR(logger, json);
return user;
}
if(!rootElement.IsObject()) {
LOG4CXX_ERROR(logger, "JSON doesn't correspond to user object")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "JSON doesn't correspond to user object");
LOG4CXX_ERROR(logger, json);
return user;
}
@ -231,21 +231,21 @@ std::vector<std::string> getIDs(std::string &json)
{
std::vector<std::string> IDs;
rapidjson::Document rootElement;
if(rootElement.Parse<0>(json.c_str()).HasParseError()) {
LOG4CXX_ERROR(logger, "Error while parsing JSON")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "Error while parsing JSON");
LOG4CXX_ERROR(logger, json);
return IDs;
}
if(!rootElement.IsObject()) {
LOG4CXX_ERROR(logger, "JSON doesn't correspond to id_list");
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, json);
return IDs;
}
const rapidjson::Value & ids = rootElement[TwitterReponseTypes::ids.c_str()];
for(int i=0 ; i<ids.Size() ; i++) {
IDs.push_back(stringOf( ids[i].GetInt64()) );
}
@ -258,14 +258,14 @@ Error getErrorMessage(std::string &json)
std::string code = "0";
Error resp;
rapidjson::Document rootElement;
if(rootElement.Parse<0>(json.c_str()).HasParseError()) {
LOG4CXX_ERROR(logger, "Error while parsing JSON")
LOG4CXX_ERROR(logger, json)
LOG4CXX_ERROR(logger, "Error while parsing JSON");
LOG4CXX_ERROR(logger, json);
return resp;
}
if (rootElement.IsObject()) {
if (!rootElement["errors"].IsNull()) {
if (!rootElement["errors"].IsNull()) {
const rapidjson::Value &errorElement = rootElement["errors"][0u]; // first error
error = std::string(errorElement["message"].GetString());
code = stringOf(errorElement["code"].GetInt64());
@ -277,22 +277,22 @@ Error getErrorMessage(std::string &json)
return resp;
}
std::vector<UrlEntity> getUrlEntities(const rapidjson::Value &element)
std::vector<UrlEntity> getUrlEntities(const rapidjson::Value &element)
{
std::vector<UrlEntity> url_entities;
const rapidjson::Value &entities = element["entities"];
if (entities.IsObject()) {
const rapidjson::Value &urls = entities["urls"];
if (urls.IsArray()) {
if (urls.IsArray()) {
for (rapidjson::SizeType i = 0; i < urls.Size(); i++) {
UrlEntity entity(urls[i]["url"].GetString(), urls[i]["expanded_url"].GetString());
UrlEntity entity(urls[i]["url"].GetString(), urls[i]["expanded_url"].GetString());
url_entities.push_back(entity);
}
}
}
return url_entities;
}

View File

@ -48,7 +48,7 @@ int main (int argc, char* argv[]) {
}
else if (!storagebackend->connect()) {
LOG4CXX_ERROR(logger, "Can't connect to database!")
LOG4CXX_ERROR(logger, "Can't connect to database!");
return -1;
}

View File

@ -40,7 +40,7 @@ bool HTTPRequest::init() {
return true;
}
LOG4CXX_ERROR(logger, "Couldn't Initialize curl!")
LOG4CXX_ERROR(logger, "Couldn't Initialize curl!");
return false;
}
@ -53,7 +53,7 @@ void HTTPRequest::setProxy(std::string IP, std::string port, std::string usernam
curl_easy_setopt(curlhandle, CURLOPT_PROXYUSERPWD, proxyUserPass.c_str());
}
} else {
LOG4CXX_ERROR(logger, "Trying to set proxy while CURL isn't initialized")
LOG4CXX_ERROR(logger, "Trying to set proxy while CURL isn't initialized");
}
}
@ -71,27 +71,27 @@ bool HTTPRequest::GET(std::string url, std::string &data) {
if (curlhandle) {
curl_easy_setopt(curlhandle, CURLOPT_CUSTOMREQUEST, NULL);
curl_easy_setopt(curlhandle, CURLOPT_ENCODING, "");
data = "";
callbackdata = "";
memset(curl_errorbuffer, 0, 1024);
curl_easy_setopt(curlhandle, CURLOPT_ERRORBUFFER, curl_errorbuffer);
curl_easy_setopt(curlhandle, CURLOPT_WRITEFUNCTION, curlCallBack);
curl_easy_setopt(curlhandle, CURLOPT_WRITEDATA, this);
/* Set http request and url */
curl_easy_setopt(curlhandle, CURLOPT_HTTPGET, 1);
curl_easy_setopt(curlhandle, CURLOPT_VERBOSE, 0);
curl_easy_setopt(curlhandle, CURLOPT_URL, url.c_str());
/* Send http request and return status*/
if(CURLE_OK == curl_easy_perform(curlhandle)) {
data = callbackdata;
return true;
}
} else {
LOG4CXX_ERROR(logger, "CURL not initialized!")
LOG4CXX_ERROR(logger, "CURL not initialized!");
strcpy(curl_errorbuffer, "CURL not initialized!");
}
LOG4CXX_ERROR(logger, "Error fetching " << url);

View File

@ -35,9 +35,9 @@ ThreadPool::~ThreadPool()
}
int ThreadPool::getActiveThreadCount()
{
{
int res;
count_lock.lock();
count_lock.lock();
res = activeThreads;
count_lock.unlock();
return res;
@ -71,29 +71,29 @@ void ThreadPool::releaseThread(int i)
delete worker[i];
worker[i] = NULL;
freeThreads.push(i);
updateActiveThreadCount(1);
pool_lock.unlock();
}
void ThreadPool::cleandUp(Thread *t, int wid)
{
LOG4CXX_INFO(logger, "Cleaning up thread #" << t->getThreadID())
LOG4CXX_INFO(logger, "Cleaning up thread #" << t->getThreadID());
t->finalize();
delete t;
releaseThread(wid);
onWorkerAvailable();
onWorkerAvailable();
}
void ThreadPool::scheduleFromQueue()
{
criticalregion.lock();
criticalregion.lock();
while(!requestQueue.empty()) {
int w = getFreeThread();
if(w == -1) break;
LOG4CXX_INFO(logger, "Worker Available. Creating thread #" << w)
LOG4CXX_INFO(logger, "Worker Available. Creating thread #" << w);
Thread *t = requestQueue.front(); requestQueue.pop();
t->setThreadID(w);
worker[w] = new boost::thread(boost::bind(&ThreadPool::workerBody, this, _1, _2), t, w, loop);
@ -107,19 +107,19 @@ void ThreadPool::runAsThread(Thread *t)
{
int w;
if((w = getFreeThread()) != -1) {
LOG4CXX_INFO(logger, "Creating thread #" << w)
LOG4CXX_INFO(logger, "Creating thread #" << w);
t->setThreadID(w);
worker[w] = new boost::thread(boost::bind(&ThreadPool::workerBody, this, _1, _2), t, w, loop);
updateActiveThreadCount(-1);
}
else {
LOG4CXX_INFO(logger, "No workers available! adding to queue.")
LOG4CXX_INFO(logger, "No workers available! adding to queue.");
requestQueue.push(t);
}
}
void ThreadPool::workerBody(Thread *t, int wid) {
LOG4CXX_INFO(logger, "Starting thread " << wid)
LOG4CXX_INFO(logger, "Starting thread " << wid);
t->run();
loop->postEvent(boost::bind(&ThreadPool::cleandUp, this, t, wid), SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::EventOwner>());
}

View File

@ -63,7 +63,7 @@ User::User(const Swift::JID &jid, UserInfo &userInfo, Component *component, User
m_storageBackend = NULL;
m_reconnectTimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer(5000);
m_reconnectTimer->onTick.connect(boost::bind(&User::onConnectingTimeout, this));
m_reconnectTimer->onTick.connect(boost::bind(&User::onConnectingTimeout, this));
m_rosterManager = component->getFrontend()->createRosterManager(this, m_component);
m_conversationManager = new ConversationManager(this, m_component);
@ -180,7 +180,7 @@ void User::handlePresence(Swift::Presence::ref presence, bool forceJoin) {
m_storageBackend->getUserSetting(m_userInfo.id, "photohash", type, value);
}
if (value != vcardUpdate->getPhotoHash()) {
LOG4CXX_INFO(logger, m_jid.toString() << ": Requesting VCard")
LOG4CXX_INFO(logger, m_jid.toString() << ": Requesting VCard");
if (m_storageBackend) {
m_storageBackend->updateUserSetting(m_userInfo.id, "photohash", vcardUpdate->getPhotoHash());
}

View File

@ -34,7 +34,7 @@
#include "Swiften/Elements/StreamError.h"
#include "Swiften/Elements/MUCPayload.h"
#include "Swiften/Elements/ChatState.h"
#ifndef __FreeBSD__
#ifndef __FreeBSD__
#ifndef __MACH__
#include "malloc.h"
#endif
@ -95,7 +95,7 @@ User *UserManager::getUser(const std::string &barejid){
// if (it == m_users.end()) {
// return Swift::DiscoInfo::ref();
// }
//
//
// User *user = it->second;
// return user->getCaps(jid);
// }
@ -481,7 +481,7 @@ void UserManager::handleErrorPresence(Swift::Presence::ref presence) {
}
void UserManager::handleSubscription(Swift::Presence::ref presence) {
// answer to subscibe for transport itself
if (presence->getType() == Swift::Presence::Subscribe && presence->getTo().getNode().empty()) {
Swift::Presence::ref response = Swift::Presence::create();
@ -567,7 +567,7 @@ void UserManager::connectUser(const Swift::JID &user) {
m_component->onUserPresenceReceived.disconnect(bind(&UserManager::handlePresence, this, _1));
// #if HAVE_SWIFTEN_3
// dynamic_cast<Swift::ServerStanzaChannel *>(m_component->getFrontend())->finishSession(user, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ToplevelElement>(new Swift::StreamError()), true);
// #else
// #else
// dynamic_cast<Swift::ServerStanzaChannel *>(m_component->getFrontend())->finishSession(user, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Element>(new Swift::StreamError()), true);
// #endif
m_component->onUserPresenceReceived.connect(bind(&UserManager::handlePresence, this, _1));

View File

@ -229,7 +229,7 @@ void SlackSession::leaveRoom(const std::string &channel_) {
std::string channelId = m_idManager->getId(channel);
std::string to = m_channel2jid[channelId];
if (to.empty()) {
LOG4CXX_ERROR(logger, "Spectrum 2 is not configured to transport this Slack channel.")
LOG4CXX_ERROR(logger, "Spectrum 2 is not configured to transport this Slack channel.");
return;
}

View File

@ -36,7 +36,7 @@
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/regex.hpp>
#include <boost/regex.hpp>
#if HAVE_SWIFTEN_3
#include <Swiften/Elements/Form.h>
#endif
@ -266,7 +266,7 @@ bool XMPPUserRegistration::handleGetRequest(const Swift::JID& from, const Swift:
if (!CONFIG_BOOL(m_config,"registration.enable_public_registration")) {
std::vector<std::string> const &x = CONFIG_VECTOR(m_config,"service.allowed_servers");
if (std::find(x.begin(), x.end(), from.getDomain()) == x.end()) {
LOG4CXX_INFO(logger, from.toBare().toString() << ": This user has no permissions to register an account")
LOG4CXX_INFO(logger, from.toBare().toString() << ": This user has no permissions to register an account");
sendError(from, id, ErrorPayload::BadRequest, ErrorPayload::Modify);
return true;
}
@ -290,7 +290,7 @@ bool XMPPUserRegistration::handleSetRequest(const Swift::JID& from, const Swift:
if (!CONFIG_BOOL(m_config,"registration.enable_public_registration")) {
std::vector<std::string> const &x = CONFIG_VECTOR(m_config,"service.allowed_servers");
if (std::find(x.begin(), x.end(), from.getDomain()) == x.end()) {
LOG4CXX_INFO(logger, barejid << ": This user has no permissions to register an account")
LOG4CXX_INFO(logger, barejid << ": This user has no permissions to register an account");
sendError(from, id, ErrorPayload::BadRequest, ErrorPayload::Modify);
return true;
}
@ -342,7 +342,7 @@ bool XMPPUserRegistration::handleSetRequest(const Swift::JID& from, const Swift:
} else */ if (local_username == "" || local_password == "") {
sendResponse(from, id, InBandRegistrationPayload::ref());
return true;
}
}
// Swift::logging = true;
bool validLocal = false;
std::string localLookupServer = CONFIG_STRING(m_config, "registration.local_account_server");
@ -350,7 +350,7 @@ bool XMPPUserRegistration::handleSetRequest(const Swift::JID& from, const Swift:
SimpleEventLoop localLookupEventLoop;
BoostNetworkFactories localLookupNetworkFactories(&localLookupEventLoop);
Client localLookupClient(localLookupJID, local_password, &localLookupNetworkFactories);
// TODO: this is neccessary on my server ... but should maybe omitted
localLookupClient.setAlwaysTrustCertificates();
localLookupClient.connect();

View File

@ -69,13 +69,13 @@ static void spectrum_sigterm_handler(int sig) {
}
#ifdef WIN32
BOOL spectrum_control_handler( DWORD fdwCtrlType ) {
BOOL spectrum_control_handler( DWORD fdwCtrlType ) {
if (fdwCtrlType == CTRL_C_EVENT || fdwCtrlType == CTRL_CLOSE_EVENT) {
eventLoop_->postEvent(&stop_spectrum);
return TRUE;
}
return FALSE;
}
}
#endif
static void removeOldIcons(std::string iconDir) {
@ -131,7 +131,7 @@ static void daemonize(const char *cwd, const char *lock_file) {
if ((chdir(cwd)) < 0) {
exit(1);
}
if (freopen( "/dev/null", "r", stdin) == NULL) {
std::cout << "EE cannot open /dev/null. Exiting\n";
exit(1);
@ -146,7 +146,7 @@ static void _createDirectories(Transport::Config *config, boost::filesystem::pat
// First create branch, by calling ourself recursively
_createDirectories(config, ph.branch_path());
// Now that parent's path exists, create the directory
boost::filesystem::create_directory(ph);
@ -217,9 +217,9 @@ int mainloop() {
Swift::BoostNetworkFactories *factories = new Swift::BoostNetworkFactories(&eventLoop);
UserRegistry userRegistry(config_, factories);
Frontend *frontend = NULL;
std::string frontend_name = CONFIG_STRING_DEFAULTED(config_, "service.frontend", "xmpp");
std::string plugin_fc = "create_" + frontend_name + "_frontend_plugin";
@ -311,8 +311,8 @@ int main(int argc, char **argv)
// determine the name of the currently executing file
char szFilePath[MAX_PATH];
GetModuleFileNameA(NULL, szFilePath, sizeof(szFilePath));
std::string exe_file(szFilePath);
#endif
std::string exe_file(szFilePath);
#endif
setlocale(LC_ALL, "");
#ifndef WIN32
#ifndef __FreeBSD__
@ -334,11 +334,11 @@ int main(int argc, char **argv)
return -1;
}
#else
if( !SetConsoleCtrlHandler( (PHANDLER_ROUTINE) spectrum_control_handler, TRUE ) )
{
if( !SetConsoleCtrlHandler( (PHANDLER_ROUTINE) spectrum_control_handler, TRUE ) )
{
std::cout << "control handler can't be set\n";
return -1;
}
}
#endif
boost::program_options::options_description desc(std::string("Spectrum version: ") + SPECTRUM_VERSION + "\nUsage: spectrum [OPTIONS] <config_file.cfg>\nAllowed options");
desc.add_options()
@ -350,9 +350,9 @@ int main(int argc, char **argv)
("version,v", "Shows Spectrum version")
;
#ifdef WIN32
desc.add_options()
desc.add_options()
("install-service,i", boost::program_options::value<std::string>(&install_service_name)->default_value(""), "Install spectrum as Windows service")
("uninstall-service,u", boost::program_options::value<std::string>(&uninstall_service_name)->default_value(""), "Uninstall Windows service")
("uninstall-service,u", boost::program_options::value<std::string>(&uninstall_service_name)->default_value(""), "Uninstall Windows service")
("run-as-service,r", boost::program_options::value<std::string>(&run_service_name)->default_value(""), "stub for Windows Service Manager");
#endif
try
@ -382,12 +382,12 @@ int main(int argc, char **argv)
if(vm.count("no-daemonize")) {
no_daemon = true;
}
#ifdef WIN32
if (!install_service_name.empty()) {
#ifdef WIN32
if (!install_service_name.empty()) {
// build command line for Service Manager
std::string service_path = exe_file + std::string(" --config ") + vm["config"].as<std::string>()
+ std::string(" --run-as-service ") + install_service_name;
std::string service_path = exe_file + std::string(" --config ") + vm["config"].as<std::string>()
+ std::string(" --run-as-service ") + install_service_name;
ServiceWrapper ntservice((char *)install_service_name.c_str());
if (!ntservice.IsInstalled()) {
if (ntservice.Install((char *)service_path.c_str())) {
@ -396,7 +396,7 @@ int main(int argc, char **argv)
} else {
std::cout << "Error installing service, are you an Administrator?" << std::endl;
return 1;
}
}
} else {
std::cout << "Already installed " << install_service_name << std::endl;
return 1;
@ -411,12 +411,12 @@ int main(int argc, char **argv)
} else {
std::cout << "Error removing service, are you an Administrator?" << std::endl;
return 1;
}
}
} else {
std::cout << "Service not installed: " << uninstall_service_name << std::endl;
return 1;
}
}
}
#endif
}
catch (std::runtime_error& e)
@ -488,7 +488,7 @@ int main(int argc, char **argv)
if (!no_daemon) {
// daemonize
daemonize(CONFIG_STRING(&config, "service.working_dir").c_str(), CONFIG_STRING(&config, "service.pidfile").c_str());
// removeOldIcons(CONFIG_STRING(&config, "service.working_dir") + "/icons");
// removeOldIcons(CONFIG_STRING(&config, "service.working_dir") + "/icons");
}
else {
if ((chdir(CONFIG_STRING(&config, "service.working_dir").c_str())) < 0) {