Changeset - 6b83d9f942fa
CMakeLists.txt
Show inline comments
 
@@ -76,49 +76,54 @@ if(NOT SWIFTEN_FOUND)
 
	message(STATUS "Using swiften: ${SWIFTEN_INCLUDE_DIR} ${SWIFTEN_LIBRARY}")
 
endif()
 

	
 
# FIND BOOST
 
set(Boost_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
if (WIN32)
 
	set(Boost_USE_STATIC_LIBS      ON)
 
	set(Boost_USE_MULTITHREADED      ON)
 
	set(Boost_USE_STATIC_RUNTIME    OFF)
 
	find_package(Boost COMPONENTS program_options date_time system filesystem regex thread signals REQUIRED)
 
else(WIN32)
 
	LIST_CONTAINS(contains -lboost_program_options ${SWIFTEN_LIBRARY})
 
	if(contains)
 
		message(STATUS "Using non-multithreaded boost")
 
		set(Boost_USE_MULTITHREADED 0)
 
	endif(contains)
 
	set(Boost_FIND_QUIETLY ON)
 
	find_package(Boost COMPONENTS program_options date_time system filesystem regex thread-mt signals)
 
	if (NOT Boost_FOUND)
 
		set(Boost_FIND_QUIETLY OFF)
 
		find_package(Boost COMPONENTS program_options date_time system filesystem regex thread signals REQUIRED)
 
	endif()
 
endif(WIN32)
 

	
 
message( STATUS "Found Boost: ${Boost_LIBRARIES}, ${Boost_INCLUDE_DIR}")
 
message( STATUS "Found Boost: ${Boost_VERSION}, ${Boost_LIBRARIES}, ${Boost_INCLUDE_DIR}")
 

	
 
if (${Boost_VERSION} GREATER 104999)
 
	message( STATUS "Using BOOST_FILESYSTEM_VERSION=3")
 
	add_definitions(-DBOOST_FILESYSTEM_VERSION=3)
 
endif()
 

	
 
# FIND POPT
 
if (NOT WIN32)
 
	set(popt_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
	find_package(popt REQUIRED)
 
endif()
 

	
 
###### Database ######
 

	
 
# FIND SQLITE3
 
if (ENABLE_SQLITE3)
 
	if (MSVC)
 
		ADD_SUBDIRECTORY(${CMAKE_SOURCE_DIR}/msvc-deps)
 
	else()
 
		if (WIN32)
 
			ADD_SUBDIRECTORY(${CMAKE_SOURCE_DIR}/msvc-deps/sqlite3)
 
		else()
 
			set(sqlite3_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
			find_package(sqlite3)
 
		endif()
 
	endif()
 
endif()
 

	
 
# FIND MYSQL
backends/CMakeLists.txt
Show inline comments
 
if (PROTOBUF_FOUND)
 
	if (PURPLE_FOUND)
 
		ADD_SUBDIRECTORY(libpurple)
 
	endif()
 

	
 
	if (IRC_FOUND)
 
		ADD_SUBDIRECTORY(libcommuni)
 
	endif()
 

	
 
	if (ENABLE_SWIFTEN)
 
		ADD_SUBDIRECTORY(swiften)
 
		ADD_SUBDIRECTORY(swiften_raw)
 
	endif()
 

	
 
	ADD_SUBDIRECTORY(template)
 
	if(ENABLE_TWITTER)
 
		ADD_SUBDIRECTORY(twitter)
 
	endif()
 
	if (NOT WIN32)
 
		if(ENABLE_SMSTOOLS3)
 
			ADD_SUBDIRECTORY(smstools3)
 
		endif()
 
		if(ENABLE_FROTZ)
 
			ADD_SUBDIRECTORY(frotz)
 
		endif()
 
 		if(YAHOO2_FOUND)
 
			ADD_SUBDIRECTORY(libyahoo2)
 
	 	endif()
 
		if (${LIBDBUSGLIB_FOUND})
 
			ADD_SUBDIRECTORY(skype)
 
		endif()
 
	endif()
 
endif()
backends/libpurple/main.cpp
Show inline comments
 
@@ -919,58 +919,57 @@ void buddyListNewNode(PurpleBlistNode *node) {
 
	np->handleBuddyChanged(np->m_accounts[account], purple_buddy_get_name_wrapped(buddy), getAlias(buddy), getGroups(buddy), status, message, getIconHash(buddy),
 
		blocked
 
	);
 
}
 

	
 
static void buddyListUpdate(PurpleBuddyList *list, PurpleBlistNode *node) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY_WRAPPED(node))
 
		return;
 
	buddyListNewNode(node);
 
}
 

	
 
static void buddyPrivacyChanged(PurpleBlistNode *node, void *data) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY_WRAPPED(node))
 
		return;
 
	buddyListUpdate(NULL, node);
 
}
 

	
 
static void NodeRemoved(PurpleBlistNode *node, void *data) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY_WRAPPED(node))
 
		return;
 
// 	PurpleBuddy *buddy = (PurpleBuddy *) node;
 
}
 

	
 
static void buddyListSaveNode(PurpleBlistNode *node) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY(node))
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY_WRAPPED(node))
 
		return;
 

	
 
}
 

	
 
static void buddyListSaveAccount(PurpleAccount *account) {
 
}
 

	
 
static void buddyListRemoveNode(PurpleBlistNode *node) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY(node))
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY_WRAPPED(node))
 
		return;
 
}
 

	
 
static PurpleBlistUiOps blistUiOps =
 
{
 
	NULL,
 
	buddyListNewNode,
 
	NULL,
 
	buddyListUpdate,
 
	buddyNodeRemoved,
 
	NULL,
 
	NULL,
 
	NULL, // buddyListAddBuddy,
 
	NULL,
 
	NULL,
 
	buddyListSaveNode,
 
	buddyListRemoveNode,
 
	buddyListSaveAccount,
 
	NULL
 
};
 

	
 
static void conv_write_im(PurpleConversation *conv, const char *who, const char *msg, PurpleMessageFlags flags, time_t mtime) {
 
	// Don't forwards our own messages.
 
	if (purple_conversation_get_type_wrapped(conv) == PURPLE_CONV_TYPE_IM && (flags & PURPLE_MESSAGE_SEND || flags & PURPLE_MESSAGE_SYSTEM)) {
backends/skype/skype.cpp
Show inline comments
 
/**
 
 * libtransport -- C++ library for easy XMPP Transports development
 
 *
 
 * Copyright (C) 2011, Jan Kaluza <hanzz.k@gmail.com>
 
 *
 
 * This program is free software; you can redistribute it and/or modify
 
 * it under the terms of the GNU General Public License as published by
 
 * the Free Software Foundation; either version 2 of the License, or
 
 * (at your option) any later version.
 
 *
 
 * This program is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#include "skype.h"
 
#include "skypeplugin.h"
 
#include "skypedb.h"
 

	
 
#include "transport/config.h"
 
#include "transport/logging.h"
 
#include "transport/transport.h"
 
#include "transport/usermanager.h"
 
#include "transport/memoryusage.h"
 
#include "transport/sqlite3backend.h"
 
#include "transport/userregistration.h"
 
#include "transport/user.h"
 
#include "transport/storagebackend.h"
 
#include "transport/rostermanager.h"
 
#include "transport/conversation.h"
 
#include "transport/networkplugin.h"
 
#include <boost/filesystem.hpp>
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
// #include "valgrind/memcheck.h"
 
#ifndef __FreeBSD__
 
#include "malloc.h"
 
#endif
 

	
 

	
 
DEFINE_LOGGER(logger, "Skype");
 

	
 
@@ -74,56 +75,57 @@ static pbnetwork::StatusType getStatus(const std::string &st) {
 
	else if (st == "DND") {
 
		status = pbnetwork::STATUS_DND;
 
	}
 
	else if (st == "NA") {
 
		status = pbnetwork::STATUS_XA;
 
	}
 
	else if (st == "AWAY") {
 
		status = pbnetwork::STATUS_AWAY;
 
	}
 
	return status;
 
}
 

	
 
DBusHandlerResult skype_notify_handler(DBusConnection *connection, DBusMessage *message, gpointer data) {
 
	Skype *skype = (Skype *) data;
 
	return skype->dbusMessageReceived(connection, message);
 
}
 

	
 
void Skype::login() {
 
	// Do not allow usernames with unsecure symbols
 
	if (m_username.find("..") == 0 || m_username.find("/") != std::string::npos) {
 
		m_np->handleDisconnected(m_user, pbnetwork::CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE, "Invalid username");
 
		return;
 
	}
 

	
 
	std::string db_path = createSkypeDirectory();
 
	m_db = createSkypeDirectory();
 

	
 
	bool spawned = spawnSkype(db_path);
 
	bool spawned = spawnSkype(m_db);
 
	if (!spawned) {
 
		m_np->handleDisconnected(m_user, pbnetwork::CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE, "Error spawning the Skype instance.");
 
		return;
 
	}
 

	
 
	m_db += "/" + getUsername() + "/main.db";
 

	
 
	if (m_connection == NULL) {
 
		LOG4CXX_INFO(logger, "Creating DBUS connection.");
 
		GError *error = NULL;
 
		m_connection = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
 
		if (m_connection == NULL && error != NULL)
 
		{
 
			LOG4CXX_INFO(logger,  m_username << ": Creating DBUS Connection error: " << error->message);
 
			g_error_free(error);
 
			return;
 
		}
 
	}
 

	
 
	m_timer = g_timeout_add_seconds(1, create_dbus_proxy, this);
 
}
 

	
 
bool Skype::createDBusProxy() {
 
	if (m_proxy == NULL) {
 
		LOG4CXX_INFO(logger, "Creating DBus proxy for com.Skype.Api.");
 
		m_counter++;
 

	
 
		GError *error = NULL;
 
		m_proxy = dbus_g_proxy_new_for_name_owner(m_connection, "com.Skype.API", "/com/Skype", "com.Skype.API", &error);
 
		if (m_proxy == NULL && error != NULL) {
 
@@ -208,93 +210,97 @@ bool Skype::loadSkypeBuddies() {
 
			std::vector<std::string> data;
 
			std::string name = send_command("GET GROUP " + grp + " DISPLAYNAME");
 

	
 
			if (name.find("ERROR") == 0) {
 
				continue;
 
			}
 

	
 
			boost::split(data, name, boost::is_any_of(" "));
 
			name = GET_RESPONSE_DATA(name, "DISPLAYNAME");
 

	
 
			std::string users = send_command("GET GROUP " + data[1] + " USERS");
 
			try {
 
				users = GET_RESPONSE_DATA(users, "USERS");
 
			}
 
			catch (std::out_of_range& oor) {
 
				continue;
 
			}
 
			boost::split(data, users, boost::is_any_of(","));
 
			BOOST_FOREACH(std::string u, data) {
 
				group_map[u] = grp;
 
			}
 
		}
 
	}
 

	
 
	// Try to load skype buddies from database, if it fails
 
	// fallback to old method.
 
	if (!SkypeDB::loadBuddies(m_np, m_db, m_user, group_map)) {
 
		std::string friends = send_command("GET AUTH_CONTACTS_PROFILES");
 

	
 
		char **full_friends_list = g_strsplit((strchr(friends.c_str(), ' ')+1), ";", 0);
 
		if (full_friends_list && full_friends_list[0])
 
		{
 
			//in the format of: username;full name;phone;office phone;mobile phone;
 
			//                  online status;friendly name;voicemail;mood
 
			// (comma-seperated lines, usernames can have comma's)
 

	
 
			for (int i=0; full_friends_list[i] && full_friends_list[i+1] && *full_friends_list[i] != '\0'; i+=8)
 
			{
 
				std::string buddy = full_friends_list[i];
 

	
 
				if (buddy[0] == ',') {
 
					buddy.erase(buddy.begin());
 
				}
 

	
 
				if (buddy.rfind(",") != std::string::npos) {
 
					buddy = buddy.substr(buddy.rfind(","));
 
				}
 

	
 
				if (buddy[0] == ',') {
 
					buddy.erase(buddy.begin());
 
				}
 

	
 
				LOG4CXX_INFO(logger, "Got buddy " << buddy);
 
				std::string st = full_friends_list[i + 5];
 

	
 
				pbnetwork::StatusType status = getStatus(st);
 

	
 
				std::string alias = full_friends_list[i + 6];
 

	
 
				std::string mood_text = "";
 
				if (full_friends_list[i + 8] && *full_friends_list[i + 8] != '\0' && *full_friends_list[i + 8] != ',') {
 
					mood_text = full_friends_list[i + 8];
 
				}
 

	
 
				std::vector<std::string> groups;
 
				if (group_map.find(buddy) != group_map.end()) {
 
					groups.push_back(group_map[buddy]);
 
				}
 
				m_np->handleBuddyChanged(m_user, buddy, alias, groups, status, mood_text);
 
			}
 
		}
 
		g_strfreev(full_friends_list);
 
	}
 

	
 
	send_command("SET AUTOAWAY OFF");
 
	send_command("SET USERSTATUS ONLINE");
 
	return FALSE;
 
}
 

	
 
void Skype::logout() {
 
	if (m_pid != 0) {
 
		if (m_proxy) {
 
			send_command("SET USERSTATUS INVISIBLE");
 
			send_command("SET USERSTATUS OFFLINE");
 
			sleep(2);
 
			g_object_unref(m_proxy);
 
		}
 
		LOG4CXX_INFO(logger,  m_username << ": Terminating Skype instance (SIGTERM)");
 
		kill((int) m_pid, SIGTERM);
 
		// Give skype a chance
 
		sleep(2);
 
		LOG4CXX_INFO(logger,  m_username << ": Killing Skype instance (SIGKILL)");
 
		kill((int) m_pid, SIGKILL);
 
		m_pid = 0;
 
	}
 
}
 

	
backends/skype/skype.h
Show inline comments
 
@@ -66,26 +66,27 @@ class Skype {
 
	public: // but do not use them, should be used only internally
 
		bool createDBusProxy();
 

	
 
		bool loadSkypeBuddies();
 

	
 
		void handleSkypeMessage(std::string &message);
 

	
 
		DBusHandlerResult dbusMessageReceived(DBusConnection *connection, DBusMessage *message);
 

	
 
	private:
 
		std::string createSkypeDirectory();
 
		bool spawnSkype(const std::string &db_path);
 

	
 
		std::string m_username;
 
		std::string m_password;
 
		GPid m_pid;
 
		DBusGConnection *m_connection;
 
		DBusGProxy *m_proxy;
 
		std::string m_user;
 
		int m_timer;
 
		int m_counter;
 
		int fd_output;
 
		std::map<std::string, std::string> m_groups;
 
		SkypePlugin *m_np;
 
		std::string m_db;
 
};
 

	
backends/skype/skypedb.cpp
Show inline comments
 
@@ -19,48 +19,50 @@
 
 */
 

	
 
#include "skypedb.h"
 

	
 
#include "transport/config.h"
 
#include "transport/logging.h"
 
#include "transport/transport.h"
 
#include "transport/usermanager.h"
 
#include "transport/memoryusage.h"
 
#include "transport/sqlite3backend.h"
 
#include "transport/userregistration.h"
 
#include "transport/user.h"
 
#include "transport/storagebackend.h"
 
#include "transport/rostermanager.h"
 
#include "transport/conversation.h"
 
#include "transport/networkplugin.h"
 
#include <boost/filesystem.hpp>
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
// #include "valgrind/memcheck.h"
 
#ifndef __FreeBSD__
 
#include "malloc.h"
 
#endif
 

	
 
#include "skypeplugin.h"
 

	
 
// Prepare the SQL statement
 
#define PREP_STMT(sql, str) \
 
	if(sqlite3_prepare_v2(db, std::string(str).c_str(), -1, &sql, NULL)) { \
 
		LOG4CXX_ERROR(logger, str<< (sqlite3_errmsg(db) == NULL ? "" : sqlite3_errmsg(db))); \
 
		sql = NULL; \
 
	}
 

	
 
// Finalize the prepared statement
 
#define FINALIZE_STMT(prep) \
 
	if(prep != NULL) { \
 
		sqlite3_finalize(prep); \
 
	}
 
	
 
#define BEGIN(STATEMENT) 	sqlite3_reset(STATEMENT);\
 
							int STATEMENT##_id = 1;\
 
							int STATEMENT##_id_get = 0;\
 
							(void)STATEMENT##_id_get;
 

	
 
#define BIND_INT(STATEMENT, VARIABLE) sqlite3_bind_int(STATEMENT, STATEMENT##_id++, VARIABLE)
 
#define BIND_STR(STATEMENT, VARIABLE) sqlite3_bind_text(STATEMENT, STATEMENT##_id++, VARIABLE.c_str(), -1, SQLITE_STATIC)
 
#define RESET_GET_COUNTER(STATEMENT)	STATEMENT##_id_get = 0;
 
#define GET_INT(STATEMENT)	sqlite3_column_int(STATEMENT, STATEMENT##_id_get++)
 
#define GET_STR(STATEMENT)	(const char *) sqlite3_column_text(STATEMENT, STATEMENT##_id_get++)
 
#define GET_BLOB(STATEMENT)	(const void *) sqlite3_column_blob(STATEMENT, STATEMENT##_id_get++)
 
@@ -83,33 +85,77 @@ bool getAvatar(const std::string &db_path, const std::string &name, std::string
 
		LOG4CXX_ERROR(logger, "Can't open database");
 
	}
 
	else {
 
		sqlite3_stmt *stmt;
 
		PREP_STMT(stmt, "SELECT avatar_image FROM Contacts WHERE skypename=?");
 
		if (stmt) {
 
			BEGIN(stmt);
 
			BIND_STR(stmt, name);
 
			if(sqlite3_step(stmt) == SQLITE_ROW) {
 
				int size = sqlite3_column_bytes(stmt, 0);
 
				const void *data = sqlite3_column_blob(stmt, 0);
 
				photo = std::string((const char *)data + 1, size - 1);
 
				ret = true;
 
			}
 
			else {
 
				LOG4CXX_ERROR(logger, (sqlite3_errmsg(db) == NULL ? "" : sqlite3_errmsg(db)));
 
			}
 

	
 
			int ret;
 
			while((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
 
			}
 
			FINALIZE_STMT(stmt);
 
		}
 
		else {
 
			LOG4CXX_ERROR(logger, "Can't created prepared statement");
 
			LOG4CXX_ERROR(logger, "Can't create prepared statement");
 
			LOG4CXX_ERROR(logger, (sqlite3_errmsg(db) == NULL ? "" : sqlite3_errmsg(db)));
 
		}
 
		sqlite3_close(db);
 
	}
 
	return ret;
 
}
 

	
 
bool loadBuddies(SkypePlugin *np, const std::string &db_path, std::string &user, std::map<std::string, std::string> &group_map) {
 
	bool ret = false;
 
	sqlite3 *db;
 
	LOG4CXX_INFO(logger, "Opening database " << db_path);
 
	if (sqlite3_open(db_path.c_str(), &db)) {
 
		sqlite3_close(db);
 
		LOG4CXX_ERROR(logger, "Can't open database");
 
	}
 
	else {
 
		sqlite3_stmt *stmt;
 
// 		aliases, fullname, 
 
		PREP_STMT(stmt, "select skypename, displayname, mood_text from Contacts;");
 
		if (stmt) {
 
			BEGIN(stmt);
 
			int ret2;
 
			while((ret2 = sqlite3_step(stmt)) == SQLITE_ROW) {
 
				std::string buddy = (const char *) sqlite3_column_text(stmt, 0);
 
				std::string alias = (const char *) sqlite3_column_text(stmt, 1);
 
				const char *d = (const char *) sqlite3_column_text(stmt, 2);
 
				std::string mood_text = d ? d : "";
 

	
 
				std::vector<std::string> groups;
 
				if (group_map.find(buddy) != group_map.end()) {
 
					groups.push_back(group_map[buddy]);
 
				}
 
				np->handleBuddyChanged(user, buddy, alias, groups, pbnetwork::STATUS_NONE, mood_text);
 
			}
 
			if (ret2 != SQLITE_DONE) {
 
				FINALIZE_STMT(stmt);
 
				ret = false;
 
			}
 
			else {
 
				ret = true;
 
			}
 
		}
 
		else {
 
			LOG4CXX_ERROR(logger, "Can't create prepared statement");
 
			LOG4CXX_ERROR(logger, (sqlite3_errmsg(db) == NULL ? "" : sqlite3_errmsg(db)));
 
		}
 
		sqlite3_close(db);
 
	}
 
	return ret;
 
}
 

	
 
}
backends/skype/skypedb.h
Show inline comments
 
@@ -5,29 +5,31 @@
 
 *
 
 * This program is free software; you can redistribute it and/or modify
 
 * it under the terms of the GNU General Public License as published by
 
 * the Free Software Foundation; either version 2 of the License, or
 
 * (at your option) any later version.
 
 *
 
 * This program is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include "glib.h"
 
#include <dbus-1.0/dbus/dbus-glib-lowlevel.h>
 
#include "sqlite3.h"
 
#include <iostream>
 
#include <map>
 

	
 
class SkypePlugin;
 

	
 
namespace SkypeDB {
 
	bool getAvatar(const std::string &db, const std::string &name, std::string &avatar);
 

	
 
	bool loadBuddies(SkypePlugin *np, const std::string &db, std::string &user, std::map<std::string, std::string> &group_map);
 
}
 

	
backends/swiften/main.cpp
Show inline comments
 
@@ -9,432 +9,409 @@
 
#include "Swiften/Swiften.h"
 

	
 
#ifndef WIN32
 
// for signal handler
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
#endif
 

	
 
#ifndef __FreeBSD__
 
#ifndef __MACH__
 
// malloc_trim
 
#include "malloc.h"
 
#endif
 
#endif
 

	
 
// Boost
 
#include <boost/algorithm/string.hpp>
 
using namespace boost::filesystem;
 
using namespace boost::program_options;
 
using namespace Transport;
 

	
 
DEFINE_LOGGER(logger, "Swiften");
 
DEFINE_LOGGER(logger_xml, "backend.xml");
 

	
 
// eventloop
 
Swift::SimpleEventLoop *loop_;
 

	
 
// Plugins
 
class SwiftenPlugin;
 
NetworkPlugin *np = NULL;
 
Swift::XMPPSerializer *serializer;
 

	
 
class MUCController {
 
class ForwardIQHandler : public Swift::IQHandler {
 
	public:
 
		MUCController(const std::string &user, boost::shared_ptr<Swift::Client> client, const std::string &room, const std::string &nickname, const std::string &password) {
 
			m_user = user;
 
			m_room = room;
 
			muc = client->getMUCManager()->createMUC(room);
 
			if (!password.empty()) {
 
				muc->setPassword(password);
 
			}
 

	
 
			muc->onJoinComplete.connect(boost::bind(&MUCController::handleJoinComplete, this, _1));
 
			muc->onJoinFailed.connect(boost::bind(&MUCController::handleJoinFailed, this, _1));
 
			muc->onOccupantJoined.connect(boost::bind(&MUCController::handleOccupantJoined, this, _1));
 
			muc->onOccupantPresenceChange.connect(boost::bind(&MUCController::handleOccupantPresenceChange, this, _1));
 
			muc->onOccupantLeft.connect(boost::bind(&MUCController::handleOccupantLeft, this, _1, _2, _3));
 
			muc->onOccupantRoleChanged.connect(boost::bind(&MUCController::handleOccupantRoleChanged, this, _1, _2, _3));
 
			muc->onOccupantAffiliationChanged.connect(boost::bind(&MUCController::handleOccupantAffiliationChanged, this, _1, _2, _3));
 

	
 
			muc->joinAs(nickname);
 
		}
 

	
 
		virtual ~MUCController() {
 
			muc->onJoinComplete.disconnect(boost::bind(&MUCController::handleJoinComplete, this, _1));
 
			muc->onJoinFailed.disconnect(boost::bind(&MUCController::handleJoinFailed, this, _1));
 
			muc->onOccupantJoined.disconnect(boost::bind(&MUCController::handleOccupantJoined, this, _1));
 
			muc->onOccupantPresenceChange.disconnect(boost::bind(&MUCController::handleOccupantPresenceChange, this, _1));
 
			muc->onOccupantLeft.disconnect(boost::bind(&MUCController::handleOccupantLeft, this, _1, _2, _3));
 
			muc->onOccupantRoleChanged.disconnect(boost::bind(&MUCController::handleOccupantRoleChanged, this, _1, _2, _3));
 
			muc->onOccupantAffiliationChanged.disconnect(boost::bind(&MUCController::handleOccupantAffiliationChanged, this, _1, _2, _3));
 
		}
 

	
 
		const std::string &getNickname() {
 
			//return muc->getCurrentNick();
 
			return m_nick;
 
		}
 

	
 
		void handleOccupantJoined(const Swift::MUCOccupant& occupant) {
 
			np->handleParticipantChanged(m_user, occupant.getNick(), m_room, occupant.getRole() == Swift::MUCOccupant::Moderator, pbnetwork::STATUS_ONLINE);
 
		}
 

	
 
		void handleOccupantLeft(const Swift::MUCOccupant& occupant, Swift::MUC::LeavingType type, const std::string& reason) {
 
			np->handleParticipantChanged(m_user, occupant.getNick(), m_room, occupant.getRole() == Swift::MUCOccupant::Moderator, pbnetwork::STATUS_NONE);
 
		}
 
		std::map <std::string, std::string> m_id2resource;
 

	
 
		void handleOccupantPresenceChange(boost::shared_ptr<Swift::Presence> presence) {
 
			const Swift::MUCOccupant& occupant = muc->getOccupant(presence->getFrom().getResource());
 
			np->handleParticipantChanged(m_user, presence->getFrom().getResource(), m_room, (int) occupant.getRole() == Swift::MUCOccupant::Moderator, (pbnetwork::StatusType) presence->getShow(), presence->getStatus());
 
		ForwardIQHandler(NetworkPlugin *np, const std::string &user) {
 
			m_np = np;
 
			m_user = user;
 
		}
 

	
 
		void handleOccupantRoleChanged(const std::string& nick, const Swift::MUCOccupant& occupant, const Swift::MUCOccupant::Role& oldRole) {
 

	
 
		bool handleIQ(boost::shared_ptr<Swift::IQ> iq) {
 
			if (iq->getPayload<Swift::RosterPayload>() != NULL) {
 
				return false;
 
			}
 

	
 
		void handleOccupantAffiliationChanged(const std::string& nick, const Swift::MUCOccupant::Affiliation& affiliation, const Swift::MUCOccupant::Affiliation& oldAffiliation) {
 
// 			np->handleParticipantChanged(m_user, occupant->getNick(), m_room, (int) occupant.getRole() == Swift::MUCOccupant::Moderator, pbnetwork::STATUS_ONLINE);
 
			if (iq->getType() == Swift::IQ::Get) {
 
				m_id2resource[iq->getID()] = iq->getFrom().getResource();
 
			}
 

	
 
		void handleJoinComplete(const std::string& nick) {
 
			m_nick = nick;
 
		}
 

	
 
		void handleJoinFailed(boost::shared_ptr<Swift::ErrorPayload> error) {
 
			
 
		}
 

	
 
		void part() {
 
			muc->part();
 
			iq->setTo(m_user);
 
			std::string xml = safeByteArrayToString(serializer->serializeElement(iq));
 
			m_np->sendRawXML(xml);
 
			return true;
 
		}
 

	
 
	private:
 
		Swift::MUC::ref muc;
 
		NetworkPlugin *m_np;
 
		std::string m_user;
 
		std::string m_room;
 
		std::string m_nick;
 
		
 
};
 

	
 
class SwiftenPlugin : public NetworkPlugin {
 
class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
 
	public:
 
		Swift::BoostNetworkFactories *m_factories;
 
		Swift::BoostIOServiceThread m_boostIOServiceThread;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		bool m_firstPing;
 
		
 
		Swift::FullPayloadSerializerCollection collection;
 
		Swift::XMPPParser *m_xmppParser;
 
		Swift::FullPayloadParserFactoryCollection m_collection2;
 

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

	
 
			serializer = new Swift::XMPPSerializer(&collection, Swift::ClientStreamType);
 
			m_xmppParser = new Swift::XMPPParser(this, &m_collection2, m_factories->getXMLParserFactory());
 
			m_xmppParser->parse("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='localhost' version='1.0'>");
 

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

	
 
		// NetworkPlugin uses this method to send the data to networkplugin server
 
		void sendData(const std::string &string) {
 
			m_conn->write(Swift::createSafeByteArray(string));
 
		}
 

	
 
		// This method has to call handleDataRead with all received data from network plugin server
 
		void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
 
			if (m_firstPing) {
 
				m_firstPing = false;
 
				NetworkPlugin::PluginConfig cfg;
 
				cfg.setRawXML(true);
 
				sendConfig(cfg);
 
			}
 
			std::string d(data->begin(), data->end());
 
			handleDataRead(d);
 
		}
 

	
 
		void handleStreamStart(const Swift::ProtocolHeader&) {}
 

	
 
		void handleElement(boost::shared_ptr<Swift::Element> element) {
 
			boost::shared_ptr<Swift::Stanza> stanza = boost::dynamic_pointer_cast<Swift::Stanza>(element);
 
			if (!stanza) {
 
				return;
 
			}
 

	
 
			std::string user = stanza->getFrom().toBare();
 

	
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			if (!client)
 
				return;
 

	
 
			stanza->setFrom(client->getJID());
 

	
 
			boost::shared_ptr<Swift::Message> message = boost::dynamic_pointer_cast<Swift::Message>(stanza);
 
			if (message) {
 
				client->sendMessage(message);
 
				return;
 
			}
 

	
 
			boost::shared_ptr<Swift::Presence> presence = boost::dynamic_pointer_cast<Swift::Presence>(stanza);
 
			if (presence) {
 
				client->sendPresence(presence);
 
				return;
 
			}
 

	
 
			boost::shared_ptr<Swift::IQ> iq = boost::dynamic_pointer_cast<Swift::IQ>(stanza);
 
			if (iq) {
 
				if (m_handlers[user]->m_id2resource.find(stanza->getID()) != m_handlers[user]->m_id2resource.end()) {
 
					iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain(), m_handlers[user]->m_id2resource[stanza->getID()]));
 
					m_handlers[user]->m_id2resource.erase(stanza->getID());
 
				}
 
				client->getIQRouter()->sendIQ(iq);
 
				return;
 
			}
 
		}
 

	
 
		void handleStreamEnd() {}
 

	
 
		void handleRawXML(const std::string &xml) {
 
			m_xmppParser->parse(xml);
 
		}
 

	
 
		void handleSwiftDisconnected(const std::string &user, const boost::optional<Swift::ClientError> &error) {
 
			std::string message = "";
 
			bool reconnect = false;
 
			if (error) {
 
				switch(error->getType()) {
 
					case Swift::ClientError::UnknownError: message = ("Unknown Error"); reconnect = true; break;
 
					case Swift::ClientError::DomainNameResolveError: message = ("Unable to find server"); break;
 
					case Swift::ClientError::ConnectionError: message = ("Error connecting to server"); break;
 
					case Swift::ClientError::ConnectionReadError: message = ("Error while receiving server data"); reconnect = true; break;
 
					case Swift::ClientError::ConnectionWriteError: message = ("Error while sending data to the server"); reconnect = true; break;
 
					case Swift::ClientError::XMLError: message = ("Error parsing server data"); reconnect = true; break;
 
					case Swift::ClientError::AuthenticationFailedError: message = ("Login/password invalid"); break;
 
					case Swift::ClientError::CompressionFailedError: message = ("Error while compressing stream"); break;
 
					case Swift::ClientError::ServerVerificationFailedError: message = ("Server verification failed"); break;
 
					case Swift::ClientError::NoSupportedAuthMechanismsError: message = ("Authentication mechanisms not supported"); break;
 
					case Swift::ClientError::UnexpectedElementError: message = ("Unexpected response"); break;
 
					case Swift::ClientError::ResourceBindError: message = ("Error binding resource"); break;
 
					case Swift::ClientError::SessionStartError: message = ("Error starting session"); break;
 
					case Swift::ClientError::StreamError: message = ("Stream error"); break;
 
					case Swift::ClientError::TLSError: message = ("Encryption error"); break;
 
					case Swift::ClientError::ClientCertificateLoadError: message = ("Error loading certificate (Invalid password?)"); break;
 
					case Swift::ClientError::ClientCertificateError: message = ("Certificate not authorized"); break;
 

	
 
					case Swift::ClientError::UnknownCertificateError: message = ("Unknown certificate"); break;
 
					case Swift::ClientError::CertificateExpiredError: message = ("Certificate has expired"); break;
 
					case Swift::ClientError::CertificateNotYetValidError: message = ("Certificate is not yet valid"); break;
 
					case Swift::ClientError::CertificateSelfSignedError: message = ("Certificate is self-signed"); break;
 
					case Swift::ClientError::CertificateRejectedError: message = ("Certificate has been rejected"); break;
 
					case Swift::ClientError::CertificateUntrustedError: message = ("Certificate is not trusted"); break;
 
					case Swift::ClientError::InvalidCertificatePurposeError: message = ("Certificate cannot be used for encrypting your connection"); break;
 
					case Swift::ClientError::CertificatePathLengthExceededError: message = ("Certificate path length constraint exceeded"); break;
 
					case Swift::ClientError::InvalidCertificateSignatureError: message = ("Invalid certificate signature"); break;
 
					case Swift::ClientError::InvalidCAError: message = ("Invalid Certificate Authority"); break;
 
					case Swift::ClientError::InvalidServerIdentityError: message = ("Certificate does not match the host identity"); break;
 
				}
 
			}
 
			LOG4CXX_INFO(logger, user << ": Disconnected " << message);
 
			handleDisconnected(user, reconnect ? 0 : 3, message);
 

	
 
			boost::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->onMessageReceived.disconnect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
 
				m_users.erase(user);
 
				m_mucs.erase(user);
 
				m_handlers.erase(user);
 
			}
 

	
 
#ifndef WIN32
 
#ifndef __FreeBSD__
 
#ifndef __MACH__
 
			// force returning of memory chunks allocated by libxml2 to kernel
 
			malloc_trim(0);
 
#endif
 
#endif
 
#endif
 
		}
 

	
 
		void handleSwiftConnected(const std::string &user) {
 
			LOG4CXX_INFO(logger, user << ": Connected to XMPP server.");
 
			handleConnected(user);
 
			m_users[user]->requestRoster();
 
			Swift::Presence::ref response = Swift::Presence::create();
 
			response->setFrom(m_users[user]->getJID());
 
			m_users[user]->sendPresence(response);
 
		}
 

	
 
		void handleSwiftRosterReceived(const std::string &user) {
 
			Swift::PresenceOracle *oracle = m_users[user]->getPresenceOracle();
 
			BOOST_FOREACH(const Swift::XMPPRosterItem &item, m_users[user]->getRoster()->getItems()) {
 
				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);
 
			}
 
		}
 

	
 
		void handleSwiftPresenceChanged(const std::string &user, Swift::Presence::ref presence) {
 
			boost::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 = "";
 

	
 
			boost::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);
 
			}
 
// 			boost::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 = "";
 
// 
 
// 			boost::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);
 
		}
 

	
 
		void handleSwiftMessageReceived(const std::string &user, Swift::Message::ref message) {
 
			std::string body = message->getBody();
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				if (message->getType() == Swift::Message::Groupchat) {
 
					boost::shared_ptr<Swift::Delay> delay = message->getPayload<Swift::Delay>();
 
					std::string timestamp = "";
 
					if (delay) {
 
						timestamp = boost::posix_time::to_iso_string(delay->getStamp());
 
					}
 
					handleMessage(user, message->getFrom().toBare().toString(), body, message->getFrom().getResource(), "", timestamp);
 
				}
 
				else {
 
					if (client->getMUCRegistry()->isMUC(message->getFrom().toBare())) {
 
						handleMessage(user, message->getFrom().toBare().toString(), body, message->getFrom().getResource(), "", "", false, true);
 
					}
 
					else {
 
						handleMessage(user, message->getFrom().toBare().toString(), body, "", "");
 
					}
 
			message->setTo(user);
 
			std::string xml = safeByteArrayToString(serializer->serializeElement(message));
 
			sendRawXML(xml);
 
		}
 

	
 
		void handleSwiftenDataRead(const Swift::SafeByteArray &data) {
 
			std::string d = safeByteArrayToString(data);
 
			if (!boost::starts_with(d, "<auth")) {
 
				LOG4CXX_INFO(logger_xml, "XML IN " << d);
 
			}
 
		}
 

	
 
		void handleSwiftVCardReceived(const std::string &user, unsigned int id, Swift::VCard::ref vcard, Swift::ErrorPayload::ref error) {
 
			if (error || !vcard) {
 
				LOG4CXX_INFO(logger, user << ": error fetching VCard with id=" << id);
 
				handleVCard(user, id, "", "", "", "");
 
				return;
 
			}
 
			LOG4CXX_INFO(logger, user << ": VCard fetched - id=" << id);
 
			std::string photo((const char *)&vcard->getPhoto()[0], vcard->getPhoto().size());
 
			handleVCard(user, id, vcard->getFullName(), vcard->getFullName(), vcard->getNickname(), photo);
 
		void handleSwiftenDataWritten(const Swift::SafeByteArray &data) {
 
			LOG4CXX_INFO(logger_xml, "XML OUT " << safeByteArrayToString(data));
 
		}
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			LOG4CXX_INFO(logger, user << ": connecting as " << legacyName);
 
			boost::shared_ptr<Swift::Client> client = boost::make_shared<Swift::Client>(Swift::JID(legacyName), password, m_factories);
 
			m_users[user] = client;
 
			client->setAlwaysTrustCertificates();
 
			client->onConnected.connect(boost::bind(&SwiftenPlugin::handleSwiftConnected, this, user));
 
			client->onDisconnected.connect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
 
			client->onMessageReceived.connect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
 
			client->getRoster()->onInitialRosterPopulated.connect(boost::bind(&SwiftenPlugin::handleSwiftRosterReceived, this, user));
 
			client->getPresenceOracle()->onPresenceChange.connect(boost::bind(&SwiftenPlugin::handleSwiftPresenceChanged, this, user, _1));
 
			client->onDataRead.connect(boost::bind(&SwiftenPlugin::handleSwiftenDataRead, this, _1));
 
			client->onDataWritten.connect(boost::bind(&SwiftenPlugin::handleSwiftenDataWritten, this, _1));
 
			client->getSubscriptionManager()->onPresenceSubscriptionRequest.connect(boost::bind(&SwiftenPlugin::handleSubscriptionRequest, this, user, _1, _2, _3));
 
			client->getSubscriptionManager()->onPresenceSubscriptionRevoked.connect(boost::bind(&SwiftenPlugin::handleSubscriptionRevoked, this, user, _1, _2));
 
			Swift::ClientOptions opt;
 
			opt.allowPLAINWithoutTLS = true;
 
			client->connect(opt);
 

	
 
			boost::shared_ptr<ForwardIQHandler> handler = boost::make_shared<ForwardIQHandler>(this, user);
 
			client->getIQRouter()->addHandler(handler);
 
			m_handlers[user] = handler;
 
		}
 

	
 
		void handleSubscriptionRequest(const std::string &user, const Swift::JID& jid, const std::string& message, Swift::Presence::ref presence) {
 
			handleSwiftPresenceChanged(user, presence);
 
		}
 

	
 
		void handleSubscriptionRevoked(const std::string &user, const Swift::JID& jid, const std::string& message) {
 
			Swift::Presence::ref presence = Swift::Presence::create();
 
			presence->setTo(user);
 
			presence->setFrom(jid);
 
			presence->setType(Swift::Presence::Unsubscribe);
 
			handleSwiftPresenceChanged(user, presence);
 
		}
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
			boost::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->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));
 
				client->disconnect();
 
				m_mucs.erase(user);
 
			}
 
		}
 

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &msg, const std::string &xhtml = "", const std::string &id = "") {
 
			LOG4CXX_INFO(logger, "Sending message from " << user << " to " << legacyName << ".");
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				boost::shared_ptr<Swift::Message> message(new Swift::Message());
 
				message->setTo(Swift::JID(legacyName));
 
				message->setFrom(client->getJID());
 
				message->setBody(msg);
 
				if (client->getMUCRegistry()->isMUC(legacyName)) {
 
					message->setType(Swift::Message::Groupchat);
 
					boost::shared_ptr<MUCController> muc = m_mucs[user][legacyName];
 
// 					handleMessage(user, legacyName, msg, muc->getNickname(), xhtml);
 
				}
 

	
 
				client->sendMessage(message);
 
			}
 
		}
 

	
 
		void handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id) {
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				LOG4CXX_INFO(logger, user << ": fetching VCard of " << legacyName << " id=" << id);
 
				Swift::GetVCardRequest::ref request = Swift::GetVCardRequest::create(Swift::JID(legacyName), client->getIQRouter());
 
				request->onResponse.connect(boost::bind(&SwiftenPlugin::handleSwiftVCardReceived, this, user, id, _1, _2));
 
				request->send();
 
			}
 
		}
 

	
 
		void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				LOG4CXX_INFO(logger, user << ": Added/Updated buddy " << buddyName << ".");
 
				if (!client->getRoster()->containsJID(buddyName)) {
 
				if (!client->getRoster()->containsJID(buddyName) || client->getRoster()->getSubscriptionStateForJID(buddyName) != Swift::RosterItemPayload::Both) {
 
					Swift::RosterItemPayload item;
 
					item.setName(alias);
 
					item.setJID(buddyName);
 
					item.setGroups(groups);
 
					boost::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->send();
 
					client->getSubscriptionManager()->requestSubscription(buddyName);
 
				}
 
				else {
 
					Swift::JID contact(buddyName);
 
					Swift::RosterItemPayload item(contact, alias, client->getRoster()->getSubscriptionStateForJID(contact));
 
					item.setGroups(groups);
 
					boost::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->send();
 
				}
 

	
 
			}
 
		}
 

	
 
		void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) {
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				Swift::RosterItemPayload item(buddyName, "", Swift::RosterItemPayload::Remove);
 
				boost::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->send();
 
			}
 
		}
 

	
 
		void handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &password) {
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				if (client->getMUCRegistry()->isMUC(room)) {
 
					return;
 
				}
 

	
 
				boost::shared_ptr<MUCController> muc = boost::shared_ptr<MUCController>( new MUCController(user, client, room, nickname, password));
 
				m_mucs[user][room] = muc;
 
			}
 
		}
 

	
 
		void handleLeaveRoomRequest(const std::string &user, const std::string &room) {
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				if (!client->getMUCRegistry()->isMUC(room)) {
 
					return;
 
				}
 

	
 
				boost::shared_ptr<MUCController> muc = m_mucs[user][room];
 
				if (!muc) {
 
					m_mucs[user].erase(room);
 
					return;
 
				}
 

	
 
				muc->part();
 
				m_mucs[user].erase(room);
 
			}
 
		}
 

	
 
	private:
 
		Config *config;
 
		std::map<std::string, boost::shared_ptr<Swift::Client> > m_users;
 
		std::map<std::string, std::map<std::string, boost::shared_ptr<MUCController> > > m_mucs;
 
		std::map<std::string, boost::shared_ptr<ForwardIQHandler> > m_handlers;
 
};
 

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

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

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

	
 

	
 
int main (int argc, char* argv[]) {
 
	std::string host;
 
	int port;
backends/swiften_raw/CMakeLists.txt
Show inline comments
 
deleted file
backends/swiften_raw/main.cpp
Show inline comments
 
deleted file
backends/twitter/libtwitcurl/twitcurl.cpp
Show inline comments
 
@@ -7,49 +7,49 @@ static int myDebugCallback(CURL *,
 
                    char *data,
 
                    size_t size,
 
                    void *handle)
 
{
 
	std::cerr << std::string(data, size);
 
  return 0;
 
};
 
 
/*++
 
* @method: twitCurl::twitCurl
 
*
 
* @description: constructor
 
*
 
* @input: none
 
*
 
* @output: none
 
*
 
*--*/
 
twitCurl::twitCurl():
 
m_curlHandle( NULL ),
 
m_curlProxyParamsSet( false ),
 
m_curlLoginParamsSet( false ),
 
m_curlCallbackParamsSet( false ),
 
m_eApiFormatType( twitCurlTypes::eTwitCurlApiFormatXml ),
 
m_eProtocolType( twitCurlTypes::eTwitCurlProtocolHttp )
 
m_eProtocolType( twitCurlTypes::eTwitCurlProtocolHttps )
 
{
 
    /* Clear callback buffers */
 
    clearCurlCallbackBuffers();
 
 
    /* Initialize cURL */
 
    m_curlHandle = curl_easy_init();
 
    if( NULL == m_curlHandle )
 
    {
 
        std::string dummyStr;
 
        getLastCurlError( dummyStr );
 
    }
 
    curl_easy_setopt(m_curlHandle, CURLOPT_VERBOSE, 1);
 
    curl_easy_setopt(m_curlHandle, CURLOPT_FOLLOWLOCATION, 1);
 
	curl_easy_setopt(m_curlHandle, CURLOPT_DEBUGFUNCTION, myDebugCallback);
 
}
 
 
/*++
 
* @method: twitCurl::~twitCurl
 
*
 
* @description: destructor
 
*
 
* @input: none
 
*
 
* @output: none
include/transport/buddy.h
Show inline comments
 
@@ -59,121 +59,125 @@ class Buddy {
 
		/// buddy is loaded from database.
 
		/// You should not need to set this ID manually.
 
		/// \param id ID
 
		void setID(long id);
 

	
 
		/// Returns unique ID used to identify this buddy by StorageBackend.
 

	
 
		/// \return ID which identifies the buddy in database or -1 if it's new buddy which is
 
		/// not in database yet.
 
		long getID();
 

	
 
		/// Returns full JID of this buddy.
 

	
 
		/// \param hostname hostname used as domain in returned JID
 
		/// \return full JID of this buddy
 
		const Swift::JID &getJID();
 

	
 
		/// Generates whole Presennce stanza with current status/show for this buddy.
 

	
 
		/// Presence stanza does not containt "to" attribute, it has to be added manually.
 
		/// \param features features used in returned stanza
 
		/// \param only_new if True, this function returns Presence stanza only if it's different
 
		/// than the previously generated one.
 
		/// \return Presence stanza or NULL.
 
		Swift::Presence::ref generatePresenceStanza(int features, bool only_new = false);
 
		std::vector<Swift::Presence::ref> &generatePresenceStanzas(int features, bool only_new = false);
 

	
 
		void setBlocked(bool block) {
 
			if (block)
 
				m_flags = (BuddyFlag) (m_flags | BUDDY_BLOCKED);
 
			else
 
				m_flags = (BuddyFlag) (m_flags & ~BUDDY_BLOCKED);
 
		}
 

	
 
		bool isBlocked() {
 
			return (m_flags & BUDDY_BLOCKED)  != 0;
 
		}
 

	
 
		/// Sets current subscription.
 

	
 
		/// \param subscription "to", "from", "both", "ask"
 
		void setSubscription(Subscription subscription);
 

	
 
		/// Returns current subscription
 

	
 
		/// \return subscription "to", "from", "both", "ask"
 
		Subscription getSubscription();
 

	
 
		/// Sets this buddy's flags.
 

	
 
		/// \param flags flags
 
		void setFlags(BuddyFlag flags);
 

	
 
		/// Returns this buddy's flags.
 

	
 
		/// \param flags flags
 
		BuddyFlag getFlags();
 

	
 
		/// Returns RosterManager associated with this buddy.
 

	
 
		/// \return RosterManager associated with this buddy.
 
		RosterManager *getRosterManager() { return m_rosterManager; }
 

	
 
		/// Returns legacy network username which does not contain unsafe characters,
 
		/// so it can be used in JIDs.
 
		std::string getSafeName();
 

	
 
		void sendPresence();
 

	
 
		void handleRawPresence(Swift::Presence::ref);
 

	
 
		/// Handles VCard from legacy network and forwards it to XMPP user.
 

	
 
		/// \param id ID used in IQ-result.
 
		/// \param vcard VCard which will be sent.
 
		void handleVCardReceived(const std::string &id, Swift::VCard::ref vcard);
 

	
 
		/// Returns legacy network username of this buddy. (for example UIN for ICQ, JID for Jabber, ...).
 

	
 
		/// \return legacy network username
 
		virtual std::string getName() = 0;
 

	
 
		/// Returns alias (nickname) of this buddy.
 

	
 
		/// \return alias (nickname)
 
		virtual std::string getAlias() = 0;
 

	
 
		/// Returns list of groups this buddy is in.
 

	
 
		/// \return groups
 
		virtual std::vector<std::string> getGroups() = 0;
 

	
 
		/// Returns current legacy network status and statuMessage of this buddy.
 

	
 
		/// \param status current status/show is stored here
 
		/// \param statusMessage current status message is stored here
 
		/// \return true if status was stored successfully
 
		virtual bool getStatus(Swift::StatusShow &status, std::string &statusMessage) = 0;
 

	
 
		/// Returns SHA-1 hash of buddy icon (avatar) or empty string if there is no avatar for this buddy.
 

	
 
		/// \return avatar hash or empty string.
 
		virtual std::string getIconHash() = 0;
 

	
 
		virtual bool isAvailable() = 0;
 

	
 
		/// Returns legacy name of buddy from JID.
 

	
 
		/// \param jid Jabber ID.
 
		/// \return legacy name of buddy from JID.
 
		static std::string JIDToLegacyName(const Swift::JID &jid);
 
		static BuddyFlag buddyFlagsFromJID(const Swift::JID &jid);
 

	
 
	protected:
 
		void generateJID();
 
		Swift::JID m_jid;
 
		std::vector<Swift::Presence::ref> m_presences;
 

	
 
	private:
 
		long m_id;
 
// 		Swift::Presence::ref m_lastPresence;
 
		BuddyFlag m_flags;
 
		RosterManager *m_rosterManager;
 
		Subscription m_subscription;
 
};
 

	
 
}
include/transport/conversation.h
Show inline comments
 
@@ -51,48 +51,49 @@ class Conversation {
 
		} Participant;
 

	
 
		/// Creates new conversation.
 

	
 
		/// \param conversationManager ConversationManager associated with this Conversation.
 
		/// \param legacyName Legacy network name of recipient.
 
		/// \param muc True if this conversation is Multi-user chat.
 
		Conversation(ConversationManager *conversationManager, const std::string &legacyName, bool muc = false);
 

	
 
		/// Destructor.
 
		virtual ~Conversation();
 

	
 
		/// Returns legacy network name of this conversation.
 

	
 
		/// \return legacy network name of this conversation.
 
		const std::string &getLegacyName() { return m_legacyName; }
 

	
 
		/// Handles new message from Legacy network and forwards it to XMPP.
 

	
 
		/// \param message Message received from legacy network.
 
		/// \param nickname For MUC conversation this is nickname of room participant who sent this message.
 
		void handleMessage(boost::shared_ptr<Swift::Message> &message, const std::string &nickname = "");
 

	
 
		void handleRawMessage(boost::shared_ptr<Swift::Message> &message);
 
		void handleRawPresence(Swift::Presence::ref presence);
 

	
 
		/// Handles participant change in MUC.
 

	
 
		/// \param nickname Nickname of participant which changed.
 
		/// \param flag ParticipantFlag.
 
		/// \param status Current status of this participant.
 
		/// \param statusMessage Current status message of this participant.
 
		/// \param newname If participant was renamed, this variable contains his new name.
 
		void handleParticipantChanged(const std::string &nickname, ParticipantFlag flag, int status = Swift::StatusShow::None, const std::string &statusMessage = "", const std::string &newname = "");
 

	
 
		/// Sets XMPP user nickname in MUC rooms.
 

	
 
		/// \param nickname XMPP user nickname in MUC rooms.
 
		void setNickname(const std::string &nickname);
 

	
 
		const std::string &getNickname() {
 
			return m_nickname;
 
		}
 

	
 
		void setJID(const Swift::JID &jid) {
 
			m_jid = jid;
 
		}
 

	
 
		void addJID(const Swift::JID &jid) {
 
@@ -140,32 +141,38 @@ class Conversation {
 

	
 
		/// \return room name associated with this Conversation.
 
		const std::string &getRoom() {
 
			return m_room;
 
		}
 

	
 
		void destroyRoom();
 

	
 
		void sendParticipants(const Swift::JID &to);
 

	
 
		void sendCachedMessages(const Swift::JID &to = Swift::JID());
 

	
 
	private:
 
		Swift::Presence::ref generatePresence(const std::string &nick, int flag, int status, const std::string &statusMessage, const std::string &newname = "");
 
		void cacheMessage(boost::shared_ptr<Swift::Message> &message);
 

	
 
	private:
 
		ConversationManager *m_conversationManager;
 
		std::string m_legacyName;
 
		std::string m_nickname;
 
		std::string m_room;
 
		bool m_muc;
 
		Swift::JID m_jid;
 
		std::list<Swift::JID> m_jids;
 
		std::map<std::string, Participant> m_participants;
 
		boost::shared_ptr<Swift::Message> m_subject;
 
		bool m_sentInitialPresence;
 
		bool m_nicknameChanged;
 

	
 
		// TODO: Move this to some extra class to cache the most used
 
		// rooms across different accounts. Just now if we have 10 users
 
		// connected to single room, we store all those things 10 times.
 
		// It would be also great to store last 100 messages per room
 
		// every time, so we can get history messages for IRC for example.
 
		boost::shared_ptr<Swift::Message> m_subject;
 
		std::list<boost::shared_ptr<Swift::Message> > m_cachedMessages;
 
		std::map<std::string, Swift::Presence::ref> m_participants;
 
};
 

	
 
}
include/transport/localbuddy.h
Show inline comments
 
@@ -18,52 +18,52 @@
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#ifndef SPECTRUM_BUDDY_H
 
#define SPECTRUM_BUDDY_H
 

	
 
#include <string>
 
#include <algorithm>
 
#include "transport/buddy.h"
 
#include "transport/rostermanager.h"
 

	
 
namespace Transport {
 

	
 
class LocalBuddy : public Buddy {
 
	public:
 
		LocalBuddy(RosterManager *rosterManager, long id, const std::string &name, const std::string &alias = "", const std::vector<std::string> &groups = std::vector<std::string>(), BuddyFlag flags = BUDDY_NO_FLAG);
 
		virtual ~LocalBuddy();
 

	
 
		std::string getAlias() { return m_alias; }
 
		void setAlias(const std::string &alias);
 

	
 
		std::string getName() { return m_name; }
 
		bool setName(const std::string &name);
 

	
 
		bool getStatus(Swift::StatusShow &status, std::string &statusMessage) {
 
			status = m_status;
 
			statusMessage = m_statusMessage;
 
			return true;
 
		bool getStatus(Swift::StatusShow &status, std::string &statusMessage);
 

	
 
		bool isAvailable() {
 
			return m_status.getType() != Swift::StatusShow::None;
 
		}
 

	
 
		void setStatus(const Swift::StatusShow &status, const std::string &statusMessage);
 

	
 
		std::string getIconHash() { return m_iconHash; }
 
		void setIconHash(const std::string &iconHash);
 

	
 
		std::vector<std::string> getGroups() { return m_groups; }
 
		void setGroups(const std::vector<std::string> &groups);
 

	
 
		bool isValid() {
 
			std::string safeName = getSafeName();
 
			return m_jid.isValid() && safeName.find("/") == std::string::npos;
 
		}
 

	
 
	private:
 
		std::string m_name;
 
		std::string m_alias;
 
		std::vector<std::string> m_groups;
 
		std::string m_statusMessage;
 
		std::string m_iconHash;
 
		Swift::StatusShow m_status;
 

	
 
	friend class NetworkPluginServer;
include/transport/transport.h
Show inline comments
 
@@ -134,48 +134,52 @@ namespace Transport {
 

	
 
			/// This signal is emitted when XML stanza is received from server.
 

	
 
			/// \param xml xml stanza
 
			boost::signal<void (const std::string &xml)> onXMLIn;
 

	
 
			Config *getConfig() { return m_config; }
 

	
 
			/// This signal is emitted when presence from XMPP user is received.
 

	
 
			/// It's emitted only for presences addressed to transport itself
 
			/// (for example to="j2j.domain.tld") and for presences comming to
 
			/// MUC (for example to="#chat%irc.freenode.org@irc.domain.tld")
 
			/// \param presence Presence.
 
			boost::signal<void (Swift::Presence::ref presence)> onUserPresenceReceived;
 

	
 
			/// Component class asks the XMPP clients automatically for their capabilities.
 
			/// This signal is emitted when capabilities have been received or changed.
 
			/// \param jid JID of the client for which we received capabilities
 
			/// \param info disco#info with response.
 
			boost::signal<void (const Swift::JID& jid, boost::shared_ptr<Swift::DiscoInfo> info)> onUserDiscoInfoReceived;
 

	
 
			boost::signal<void (boost::shared_ptr<Swift::IQ>)> onRawIQReceived;
 

	
 
			bool isRawXMLEnabled() {
 
				return m_rawXML;
 
			}
 

	
 
		private:
 
			void handleConnected();
 
			void handleConnectionError(const Swift::ComponentError &error);
 
			void handleServerStopped(boost::optional<Swift::BoostConnectionServer::Error> e);
 
			void handlePresence(Swift::Presence::ref presence);
 
			void handleDataRead(const Swift::SafeByteArray &data);
 
			void handleDataWritten(const Swift::SafeByteArray &data);
 

	
 
			void handleDiscoInfoResponse(boost::shared_ptr<Swift::DiscoInfo> info, Swift::ErrorPayload::ref error, const Swift::JID& jid);
 
			void handleCapsChanged(const Swift::JID& jid);
 

	
 
			void handleBackendConfigChanged();
 
			bool handleIQ(boost::shared_ptr<Swift::IQ>);
 

	
 
			Swift::NetworkFactories *m_factories;
 
			Swift::Component *m_component;
 
			Swift::Server *m_server;
 
			Swift::Timer::ref m_reconnectTimer;
 
			Swift::EntityCapsManager *m_entityCapsManager;
 
			Swift::CapsManager *m_capsManager;
 
			Swift::CapsMemoryStorage *m_capsMemoryStorage;
 
			PresenceOracle *m_presenceOracle;
 
			Swift::StanzaChannel *m_stanzaChannel;
 
			Swift::IQRouter *m_iqRouter;
src/buddy.cpp
Show inline comments
 
@@ -19,146 +19,171 @@
 
 */
 

	
 
#include "transport/buddy.h"
 
#include "transport/rostermanager.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/BlockPayload.h"
 
#include "transport/usermanager.h"
 
#include "transport/discoitemsresponder.h"
 

	
 
#include "Swiften/Elements/VCardUpdate.h"
 

	
 
namespace Transport {
 

	
 
Buddy::Buddy(RosterManager *rosterManager, long id, BuddyFlag flags) : m_id(id), m_flags(flags), m_rosterManager(rosterManager),
 
	m_subscription(Ask) {
 
// 	m_rosterManager->setBuddy(this);
 
}
 

	
 
Buddy::~Buddy() {
 
// 	m_rosterManager->unsetBuddy(this);
 
}
 

	
 
void Buddy::sendPresence() {
 
	Swift::Presence::ref presence = generatePresenceStanza(255);
 
	if (presence) {
 
	std::vector<Swift::Presence::ref> &presences = generatePresenceStanzas(255);
 
	BOOST_FOREACH(Swift::Presence::ref presence, presences) {
 
		m_rosterManager->getUser()->getComponent()->getStanzaChannel()->sendPresence(presence);
 
	}
 
}
 

	
 
void Buddy::generateJID() {
 
	m_jid = Swift::JID();
 
	m_jid = Swift::JID(getSafeName(), m_rosterManager->getUser()->getComponent()->getJID().toString(), "bot");
 
}
 

	
 
void Buddy::setID(long id) {
 
	m_id = id;
 
}
 

	
 
long Buddy::getID() {
 
	return m_id;
 
}
 

	
 
void Buddy::setFlags(BuddyFlag flags) {
 
	m_flags = flags;
 

	
 
	if (!getSafeName().empty()) {
 
		try {
 
			generateJID();
 
		} catch (...) {
 
		}
 
	}
 
}
 

	
 
BuddyFlag Buddy::getFlags() {
 
	return m_flags;
 
}
 

	
 
const Swift::JID &Buddy::getJID() {
 
	if (!m_jid.isValid() || m_jid.getNode().empty()) {
 
		generateJID();
 
	}
 
	return m_jid;
 
}
 

	
 
void Buddy::setSubscription(Subscription subscription) {
 
	m_subscription = subscription;
 
}
 

	
 
Buddy::Subscription Buddy::getSubscription() {
 
	return m_subscription;
 
}
 

	
 
Swift::Presence::ref Buddy::generatePresenceStanza(int features, bool only_new) {
 
	std::string alias = getAlias();
 
	std::string name = getSafeName();
 
void Buddy::handleRawPresence(Swift::Presence::ref presence) {
 
	for (std::vector<Swift::Presence::ref>::iterator it = m_presences.begin(); it != m_presences.end(); it++) {
 
		if ((*it)->getFrom() == presence->getFrom()) {
 
			m_presences.erase(it);
 
			break;
 
		}
 
	}
 

	
 
	Swift::StatusShow s;
 
	std::string statusMessage;
 
	if (!getStatus(s, statusMessage))
 
		return Swift::Presence::ref();
 
	m_presences.push_back(presence);
 
	m_rosterManager->getUser()->getComponent()->getStanzaChannel()->sendPresence(presence);
 
}
 

	
 
std::vector<Swift::Presence::ref> &Buddy::generatePresenceStanzas(int features, bool only_new) {
 
	if (m_jid.getNode().empty()) {
 
		generateJID();
 
	}
 

	
 
	Swift::StatusShow s;
 
	std::string statusMessage;
 
	if (!getStatus(s, statusMessage)) {
 
		for (std::vector<Swift::Presence::ref>::iterator it = m_presences.begin(); it != m_presences.end(); it++) {
 
			if ((*it)->getFrom() == m_jid) {
 
				m_presences.erase(it);
 
				break;
 
			}
 
		}
 
		return m_presences;
 
	}
 

	
 
	Swift::Presence::ref presence = Swift::Presence::create();
 
	presence->setTo(m_rosterManager->getUser()->getJID().toBare());
 
	presence->setFrom(m_jid);
 
	presence->setType(Swift::Presence::Available);
 

	
 
	if (!statusMessage.empty())
 
		presence->setStatus(statusMessage);
 

	
 
	if (s.getType() == Swift::StatusShow::None)
 
		presence->setType(Swift::Presence::Unavailable);
 

	
 
	presence->setShow(s.getType());
 

	
 
	if (presence->getType() != Swift::Presence::Unavailable) {
 
		// caps
 
		
 
		presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::CapsInfo(m_rosterManager->getUser()->getUserManager()->getDiscoResponder()->getBuddyCapsInfo())));
 

	
 
// 		if (features & 0/*TRANSPORT_FEATURE_AVATARS*/) {
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::VCardUpdate (getIconHash())));
 
// 		}
 
		if (isBlocked()) {
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Transport::BlockPayload ()));
 
		}
 
	}
 

	
 
	BOOST_FOREACH(Swift::Presence::ref &p, m_presences) {
 
		if (p->getFrom() == presence->getFrom()) {
 
			p = presence;
 
			return m_presences;
 
		}
 
	}
 

	
 
	m_presences.push_back(presence);
 

	
 
// 	if (only_new) {
 
// 		if (m_lastPresence)
 
// 			m_lastPresence->setTo(Swift::JID(""));
 
// 		if (m_lastPresence == presence) {
 
// 			return Swift::Presence::ref();
 
// 		}
 
// 		m_lastPresence = presence;
 
// 	}
 

	
 
	return presence;
 
	return m_presences;
 
}
 

	
 
std::string Buddy::getSafeName() {
 
	if (m_jid.isValid()) {
 
		return m_jid.getNode();
 
	}
 
	std::string name = getName();
 
// 	Transport::instance()->protocol()->prepareUsername(name, purple_buddy_get_account(m_buddy));
 
	if (getFlags() & BUDDY_JID_ESCAPING) {
 
		name = Swift::JID::getEscapedNode(name);
 
	}
 
	else {
 
		if (name.find_last_of("@") != std::string::npos) {
 
			name.replace(name.find_last_of("@"), 1, "%"); // OK
 
		}
 
	}
 
// 	if (name.empty()) {
 
// 		Log("SpectrumBuddy::getSafeName", "Name is EMPTY! Previous was " << getName() << ".");
 
// 	}
 
	return name;
 
}
 

	
 
void Buddy::handleVCardReceived(const std::string &id, Swift::VCard::ref vcard) {
 
	boost::shared_ptr<Swift::GenericRequest<Swift::VCard> > request(new Swift::GenericRequest<Swift::VCard>(Swift::IQ::Result, m_rosterManager->getUser()->getJID(), vcard, m_rosterManager->getUser()->getComponent()->getIQRouter()));
src/conversation.cpp
Show inline comments
 
@@ -178,65 +178,75 @@ void Conversation::handleMessage(boost::shared_ptr<Swift::Message> &message, con
 
					legacyName.replace(legacyName.find_last_of("@"), 1, "%"); // OK
 
				}
 
				message->setFrom(Swift::JID(legacyName, m_conversationManager->getComponent()->getJID().toBare(), n));
 
			}
 
		}
 
	}
 
	else {
 
		std::string legacyName = m_legacyName;
 
		if (legacyName.find_last_of("@") != std::string::npos) {
 
			legacyName.replace(legacyName.find_last_of("@"), 1, "%"); // OK
 
		}
 

	
 
		std::string n = nickname;
 
		if (n.empty()) {
 
			n = " ";
 
		}
 

	
 
		message->setFrom(Swift::JID(legacyName, m_conversationManager->getComponent()->getJID().toBare(), n));
 
	}
 

	
 
	handleRawMessage(message);
 
}
 

	
 
void Conversation::sendParticipants(const Swift::JID &to) {
 
	for (std::map<std::string, Participant>::iterator it = m_participants.begin(); it != m_participants.end(); it++) {
 
		Swift::Presence::ref presence = generatePresence(it->first, it->second.flag, it->second.status, it->second.statusMessage, "");
 
		presence->setTo(to);
 
		m_conversationManager->getComponent()->getStanzaChannel()->sendPresence(presence);
 
	for (std::map<std::string, Swift::Presence::ref>::iterator it = m_participants.begin(); it != m_participants.end(); it++) {
 
		(*it).second->setTo(to);
 
		m_conversationManager->getComponent()->getStanzaChannel()->sendPresence((*it).second);
 
	}
 
}
 

	
 
void Conversation::sendCachedMessages(const Swift::JID &to) {
 
	for (std::list<boost::shared_ptr<Swift::Message> >::const_iterator it = m_cachedMessages.begin(); it != m_cachedMessages.end(); it++) {
 
		if (to.isValid()) {
 
			(*it)->setTo(to);
 
		}
 
		else {
 
			(*it)->setTo(m_jid.toBare());
 
		}
 
		m_conversationManager->getComponent()->getStanzaChannel()->sendMessage(*it);
 
	}
 

	
 
	if (m_subject) {
 
		if (to.isValid()) {
 
			m_subject->setTo(to);
 
		}
 
		else {
 
			m_subject->setTo(m_jid.toBare());
 
		}
 
		m_conversationManager->getComponent()->getStanzaChannel()->sendMessage(m_subject);
 
	}
 

	
 
	m_cachedMessages.clear();
 
}
 

	
 
Swift::Presence::ref Conversation::generatePresence(const std::string &nick, int flag, int status, const std::string &statusMessage, const std::string &newname) {
 
	std::string nickname = nick;
 
	Swift::Presence::ref presence = Swift::Presence::create();
 
	std::string legacyName = m_legacyName;
 
	if (m_muc) {
 
		if (legacyName.find_last_of("@") != std::string::npos) {
 
			legacyName.replace(legacyName.find_last_of("@"), 1, "%"); // OK
 
		}
 
	}
 
	presence->setFrom(Swift::JID(legacyName, m_conversationManager->getComponent()->getJID().toBare(), nickname));
 
	presence->setType(Swift::Presence::Available);
 

	
 
	if (!statusMessage.empty())
 
		presence->setStatus(statusMessage);
 

	
 
	Swift::StatusShow s((Swift::StatusShow::Type) status);
 

	
 
	if (s.getType() == Swift::StatusShow::None) {
 
		presence->setType(Swift::Presence::Unavailable);
 
	}
 

	
 
@@ -281,61 +291,64 @@ Swift::Presence::ref Conversation::generatePresence(const std::string &nick, int
 

	
 
	Swift::MUCItem item;
 
	
 
	item.affiliation = Swift::MUCOccupant::Member;
 
	item.role = Swift::MUCOccupant::Participant;
 

	
 
	if (flag & PARTICIPANT_FLAG_MODERATOR) {
 
		item.affiliation = Swift::MUCOccupant::Admin;
 
		item.role = Swift::MUCOccupant::Moderator;
 
	}
 

	
 
	if (!newname.empty()) {
 
		item.nick = newname;
 
		Swift::MUCUserPayload::StatusCode c;
 
		c.code = 303;
 
		p->addStatusCode(c);
 
		presence->setType(Swift::Presence::Unavailable);
 
	}
 
	
 
	p->addItem(item);
 
	presence->addPayload(boost::shared_ptr<Swift::Payload>(p));
 
	return presence;
 
}
 

	
 

	
 
void Conversation::setNickname(const std::string &nickname) {
 
	if (!nickname.empty() && m_nickname != nickname) {
 
		m_nicknameChanged = true;
 
	}
 
	m_nickname = nickname;
 
}
 

	
 
void Conversation::handleRawPresence(Swift::Presence::ref presence) {
 
	// TODO: Detect nickname change.
 
	m_conversationManager->getComponent()->getStanzaChannel()->sendPresence(presence);
 
	m_participants[presence->getFrom().getResource()] = presence;
 
}
 

	
 
void Conversation::handleParticipantChanged(const std::string &nick, Conversation::ParticipantFlag flag, int status, const std::string &statusMessage, const std::string &newname) {
 
	Swift::Presence::ref presence = generatePresence(nick, flag, status, statusMessage, newname);
 

	
 
	if (presence->getType() == Swift::Presence::Unavailable) {
 
		m_participants.erase(nick);
 
	}
 
	else {
 
		Participant p;
 
		p.flag = flag;
 
		p.status = status;
 
		p.statusMessage = statusMessage;
 
		m_participants[nick] = p;
 
		m_participants[nick] = presence;
 
	}
 

	
 

	
 
	BOOST_FOREACH(const Swift::JID &jid, m_jids) {
 
		presence->setTo(jid);
 
		m_conversationManager->getComponent()->getStanzaChannel()->sendPresence(presence);
 
	}
 
	if (!newname.empty()) {
 
		handleParticipantChanged(newname, flag, status, statusMessage);
 
	}
 

	
 
	if (m_sentInitialPresence && m_subject) {
 
		m_conversationManager->getComponent()->getStanzaChannel()->sendMessage(m_subject);
 
		m_subject.reset();
 
	}
 
}
 

	
 
}
src/localbuddy.cpp
Show inline comments
 
@@ -81,25 +81,34 @@ void LocalBuddy::setAlias(const std::string &alias) {
 
		getRosterManager()->storeBuddy(this);
 
	}
 
}
 

	
 
void LocalBuddy::setGroups(const std::vector<std::string> &groups) {
 
	bool changed = m_groups.size() != groups.size();
 
	if (!changed) {
 
		for (int i = 0; i != m_groups.size(); i++) {
 
			if (m_groups[i] != groups[i]) {
 
				changed = true;
 
				break;
 
			}
 
		}
 
	}
 

	
 
	m_groups = groups;
 
	if (changed) {
 
		if (getRosterManager()->getUser()->getComponent()->inServerMode() || getRosterManager()->isRemoteRosterSupported()) {
 
			getRosterManager()->sendBuddyRosterPush(this);
 
		}
 
		getRosterManager()->storeBuddy(this);
 
	}
 
}
 

	
 
bool LocalBuddy::getStatus(Swift::StatusShow &status, std::string &statusMessage) {
 
	if (getRosterManager()->getUser()->getComponent()->isRawXMLEnabled()) {
 
		return false;
 
	}
 
	status = m_status;
 
	statusMessage = m_statusMessage;
 
	return true;
 
}
 

	
 
}
src/networkpluginserver.cpp
Show inline comments
 
@@ -1032,52 +1032,59 @@ void NetworkPluginServer::handleElement(boost::shared_ptr<Swift::Element> elemen
 
				}
 
			}
 
		}
 
		if (stanza->getFrom().getResource().empty()) {
 
			stanza->setFrom(Swift::JID(name, m_component->getJID().toString()));
 
		}
 
		else {
 
			stanza->setFrom(Swift::JID(name, m_component->getJID().toString(), stanza->getFrom().getResource()));
 
		}
 
	}
 

	
 
	boost::shared_ptr<Swift::Message> message = boost::dynamic_pointer_cast<Swift::Message>(stanza);
 
	if (message) {
 
		if (conv) {
 
			conv->handleRawMessage(message);
 
			return;
 
		}
 

	
 
		m_component->getStanzaChannel()->sendMessage(message);
 
		return;
 
	}
 

	
 
	boost::shared_ptr<Swift::Presence> presence = boost::dynamic_pointer_cast<Swift::Presence>(stanza);
 
	if (presence) {
 
		m_component->getStanzaChannel()->sendPresence(presence);
 
		if (buddy) {
 
			buddy->m_statusMessage = presence->getStatus();
 
			buddy->m_status = Swift::StatusShow(presence->getShow());
 
			if (!buddy->isAvailable() && presence->getType() != Swift::Presence::Unavailable) {
 
				buddy->m_status.setType(Swift::StatusShow::Online);
 
			}
 
			buddy->handleRawPresence(presence);
 
		}
 
		else if (conv) {
 
			conv->handleRawPresence(presence);
 
		}
 
		else {
 
			m_component->getStanzaChannel()->sendPresence(presence);
 
		}
 

	
 
		return;
 
	}
 

	
 
	boost::shared_ptr<Swift::IQ> iq = boost::dynamic_pointer_cast<Swift::IQ>(stanza);
 
	if (iq) {
 
		if (m_id2resource.find(stanza->getTo().toBare().toString() + stanza->getID()) != m_id2resource.end()) {
 
			iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain(), m_id2resource[stanza->getTo().toBare().toString() + stanza->getID()]));
 
			m_id2resource.erase(stanza->getTo().toBare().toString() + stanza->getID());
 
		}
 
		else {
 
			Swift::Presence::ref highest = m_component->getPresenceOracle()->getHighestPriorityPresence(user->getJID());
 
			iq->setTo(highest->getFrom());
 
		}
 
		m_component->getIQRouter()->sendIQ(iq);
 
		return;
 
	}
 
}
 

	
 
void NetworkPluginServer::handleRawXML(const std::string &xml) {
 
	m_xmppParser->parse(xml);
 
}
 

	
src/rostermanager.cpp
Show inline comments
 
@@ -234,53 +234,55 @@ void RosterManager::setBuddyCallback(Buddy *buddy) {
 
			m_RIETimer->start();
 
		}
 
	}
 

	
 
	if (m_rosterStorage)
 
		m_rosterStorage->storeBuddy(buddy);
 
}
 

	
 
void RosterManager::unsetBuddy(Buddy *buddy) {
 
	m_buddies.erase(buddy->getName());
 
	if (m_rosterStorage)
 
		m_rosterStorage->removeBuddyFromQueue(buddy);
 
	onBuddyUnset(buddy);
 
}
 

	
 
void RosterManager::storeBuddy(Buddy *buddy) {
 
	if (m_rosterStorage) {
 
		m_rosterStorage->storeBuddy(buddy);
 
	}
 
}
 

	
 
void RosterManager::handleBuddyRosterPushResponse(Swift::ErrorPayload::ref error, Swift::SetRosterRequest::ref request, const std::string &key) {
 
	LOG4CXX_INFO(logger, "handleBuddyRosterPushResponse called for buddy " << key);
 
	if (m_buddies[key] != NULL) {
 
		Swift::Presence::ref presence = m_buddies[key]->generatePresenceStanza(255);
 
		if (presence && presence->getType() == Swift::Presence::Available) {
 
		if (m_buddies[key]->isAvailable()) {
 
			std::vector<Swift::Presence::ref> &presences = m_buddies[key]->generatePresenceStanzas(255);
 
			BOOST_FOREACH(Swift::Presence::ref &presence, presences) {
 
				m_component->getStanzaChannel()->sendPresence(presence);
 
			}
 
		}
 
	}
 
	else {
 
		LOG4CXX_WARN(logger, "handleBuddyRosterPushResponse called for unknown buddy " << key);
 
	}
 

	
 
	m_requests.remove(request);
 
	request->onResponse.disconnect_all_slots();
 
}
 

	
 
void RosterManager::handleRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> payload, Swift::ErrorPayload::ref error) {
 
	m_remoteRosterRequest.reset();
 
	if (error) {
 
		m_supportRemoteRoster = false;
 
		LOG4CXX_INFO(logger, m_user->getJID().toString() << ": This server does not support remote roster protoXEP");
 
		return;
 
	}
 

	
 
	LOG4CXX_INFO(logger, m_user->getJID().toString() << ": This server supports remote roster protoXEP");
 
	m_supportRemoteRoster = true;
 

	
 
	//If we receive empty RosterPayload on login (not register) initiate full RosterPush
 
	if(!m_buddies.empty() && payload->getItems().empty()){
 
			LOG4CXX_INFO(logger, "Received empty Roster upon login. Pushing full Roster.");
 
			for(std::map<std::string, Buddy *, std::less<std::string>, boost::pool_allocator< std::pair<std::string, Buddy *> > >::const_iterator c_it = m_buddies.begin();
 
					c_it != m_buddies.end(); c_it++) {
 
@@ -419,55 +421,55 @@ void RosterManager::handleSubscription(Swift::Presence::ref presence) {
 
					buddyInfo.alias = "";
 
					buddyInfo.legacyName = Buddy::JIDToLegacyName(presence->getTo());
 
					buddyInfo.subscription = "both";
 
					buddyInfo.flags = Buddy::buddyFlagsFromJID(presence->getTo());
 

	
 
					buddy = m_component->getFactory()->createBuddy(this, buddyInfo);
 
					onBuddyRemoved(buddy);
 
					delete buddy;
 
					response->setType(Swift::Presence::Unsubscribed);
 
					break;
 
				default:
 
					return;
 
			}
 
			m_component->getStanzaChannel()->sendPresence(response);
 
		}
 
	}
 
	else {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		Swift::Presence::ref currentPresence;
 
		response->setTo(presence->getFrom().toBare());
 
		response->setFrom(presence->getTo().toBare());
 

	
 
		Buddy *buddy = getBuddy(Buddy::JIDToLegacyName(presence->getTo()));
 
		if (buddy) {
 
			std::vector<Swift::Presence::ref> &presences = buddy->generatePresenceStanzas(255);
 
			switch (presence->getType()) {
 
				// buddy is already there, so nothing to do, just answer
 
				case Swift::Presence::Subscribe:
 
					onBuddyAdded(buddy);
 
					response->setType(Swift::Presence::Subscribed);
 
					currentPresence = buddy->generatePresenceStanza(255);
 
					if (currentPresence) {
 
					BOOST_FOREACH(Swift::Presence::ref &currentPresence, presences) {
 
						currentPresence->setTo(presence->getFrom());
 
						m_component->getStanzaChannel()->sendPresence(currentPresence);
 
					}
 
					if (buddy->getSubscription() != Buddy::Both) {
 
						buddy->setSubscription(Buddy::Both);
 
						storeBuddy(buddy);
 
					}
 
					break;
 
				// remove buddy
 
				case Swift::Presence::Unsubscribe:
 
					response->setType(Swift::Presence::Unsubscribed);
 
					onBuddyRemoved(buddy);
 
					removeBuddy(buddy->getName());
 
					buddy = NULL;
 
					break;
 
				// just send response
 
				case Swift::Presence::Unsubscribed:
 
					response->setType(Swift::Presence::Unsubscribe);
 
					// We set both here, because this Unsubscribed can be response to
 
					// subscribe presence and we don't want that unsubscribe presence
 
					// to be send later again
 
					if (buddy->getSubscription() != Buddy::Both) {
 
						buddy->setSubscription(Buddy::Both);
 
						storeBuddy(buddy);
 
@@ -566,74 +568,84 @@ void RosterManager::setStorageBackend(StorageBackend *storageBackend) {
 
Swift::RosterPayload::ref RosterManager::generateRosterPayload() {
 
	Swift::RosterPayload::ref payload = Swift::RosterPayload::ref(new Swift::RosterPayload());
 

	
 
	for (std::map<std::string, Buddy *, std::less<std::string>, boost::pool_allocator< std::pair<std::string, Buddy *> > >::iterator it = m_buddies.begin(); it != m_buddies.end(); it++) {
 
		Buddy *buddy = (*it).second;
 
		if (!buddy) {
 
			continue;
 
		}
 
		Swift::RosterItemPayload item;
 
		item.setJID(buddy->getJID().toBare());
 
		item.setName(buddy->getAlias());
 
		item.setGroups(buddy->getGroups());
 
		item.setSubscription(Swift::RosterItemPayload::Both);
 
		payload->addItem(item);
 
	}
 
	return payload;
 
}
 

	
 
void RosterManager::sendCurrentPresences(const Swift::JID &to) {
 
	for (std::map<std::string, Buddy *, std::less<std::string>, boost::pool_allocator< std::pair<std::string, Buddy *> > >::iterator it = m_buddies.begin(); it != m_buddies.end(); it++) {
 
		Buddy *buddy = (*it).second;
 
		if (!buddy) {
 
			continue;
 
		}
 
		Swift::Presence::ref presence = buddy->generatePresenceStanza(255);
 
		if (presence && presence->getType() == Swift::Presence::Available) {
 
		if (!buddy->isAvailable()) {
 
			continue;
 
		}
 
		std::vector<Swift::Presence::ref> &presences = buddy->generatePresenceStanzas(255);
 
		BOOST_FOREACH(Swift::Presence::ref &presence, presences) {
 
			presence->setTo(to);
 
			m_component->getStanzaChannel()->sendPresence(presence);
 
		}
 
	}
 
}
 

	
 
void RosterManager::sendCurrentPresence(const Swift::JID &from, const Swift::JID &to) {
 
	Buddy *buddy = getBuddy(Buddy::JIDToLegacyName(from));
 
	if (buddy) {
 
		Swift::Presence::ref presence = buddy->generatePresenceStanza(255);
 
		if (presence) {
 
		std::vector<Swift::Presence::ref> &presences = buddy->generatePresenceStanzas(255);
 
		BOOST_FOREACH(Swift::Presence::ref &presence, presences) {
 
			presence->setTo(to);
 
			m_component->getStanzaChannel()->sendPresence(presence);
 
		}
 
	}
 
	else {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setTo(to);
 
		response->setFrom(from);
 
		response->setType(Swift::Presence::Unavailable);
 
		m_component->getStanzaChannel()->sendPresence(response);
 
	}
 
}
 

	
 
void RosterManager::sendUnavailablePresences(const Swift::JID &to) {
 
	for (std::map<std::string, Buddy *, std::less<std::string>, boost::pool_allocator< std::pair<std::string, Buddy *> > >::iterator it = m_buddies.begin(); it != m_buddies.end(); it++) {
 
		Buddy *buddy = (*it).second;
 
		if (!buddy) {
 
			continue;
 
		}
 
		Swift::Presence::ref presence = buddy->generatePresenceStanza(255);
 
		if (presence && presence->getType() == Swift::Presence::Available) {
 

	
 
		if (!buddy->isAvailable()) {
 
			continue;
 
		}
 

	
 
		std::vector<Swift::Presence::ref> &presences = buddy->generatePresenceStanzas(255);
 
		BOOST_FOREACH(Swift::Presence::ref &presence, presences) {
 
			Swift::Presence::Type type = presence->getType();
 
			presence->setTo(to);
 
			presence->setType(Swift::Presence::Unavailable);
 
			m_component->getStanzaChannel()->sendPresence(presence);
 
			presence->setType(type);
 
		}
 
	}
 

	
 
	// in gateway mode, we have to send unavailable presence for transport
 
	// contact
 
	Swift::Presence::ref response = Swift::Presence::create();
 
	response->setTo(to);
 
	response->setFrom(m_component->getJID());
 
	response->setType(Swift::Presence::Unavailable);
 
	m_component->getStanzaChannel()->sendPresence(response);
 
}
 

	
 
}
src/tests/basictest.cpp
Show inline comments
 
@@ -220,48 +220,51 @@ void BasicTest::connectSecondResource() {
 
	userRegistry->onPasswordValid(Swift::JID("user@localhost/resource2"));
 

	
 
	loop->processEvents();
 

	
 
	Swift::Presence::ref response = Swift::Presence::create();
 
	response->setTo("localhost");
 
	response->setFrom("user@localhost/resource2");
 
	injectPresence(response);
 
	loop->processEvents();
 

	
 
	CPPUNIT_ASSERT_EQUAL(1, userManager->getUserCount());
 

	
 
	User *user = userManager->getUser("user@localhost");
 
	CPPUNIT_ASSERT(user);
 
	CPPUNIT_ASSERT_EQUAL(2, user->getResourceCount());
 

	
 
	CPPUNIT_ASSERT(getStanza(received2[1])->getPayload<Swift::DiscoInfo>());
 
}
 

	
 
void BasicTest::disconnectUser() {
 
	User *user = userManager->getUser("user@localhost");
 
	if (user) {
 
		user->addUserSetting("stay_connected", "0");
 
	}
 
	else {
 
		return;
 
	}
 
	received.clear();
 
	userManager->disconnectUser("user@localhost");
 
	dynamic_cast<Swift::DummyTimerFactory *>(factories->getTimerFactory())->setTime(100);
 
	loop->processEvents();
 

	
 
	CPPUNIT_ASSERT_EQUAL(0, userManager->getUserCount());
 
	CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
	CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
}
 

	
 
void BasicTest::add2Buddies() {
 
	User *user = userManager->getUser("user@localhost");
 
	CPPUNIT_ASSERT(user);
 

	
 
	std::vector<std::string> grp;
 
	grp.push_back("group1");
 
	LocalBuddy *buddy = new LocalBuddy(user->getRosterManager(), -1, "buddy1", "Buddy 1", grp, BUDDY_JID_ESCAPING);
 
	user->getRosterManager()->setBuddy(buddy);
 
	buddy->setStatus(Swift::StatusShow(Swift::StatusShow::Away), "status1");
 

	
 
	std::vector<std::string> grp2;
 
	grp2.push_back("group2");
 
	buddy = new LocalBuddy(user->getRosterManager(), -1, "buddy2", "Buddy 2", grp2, BUDDY_JID_ESCAPING);
 
	user->getRosterManager()->setBuddy(buddy);
src/tests/conversationmanager.cpp
Show inline comments
 
@@ -2,86 +2,91 @@
 
#include "transport/config.h"
 
#include "transport/storagebackend.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/conversation.h"
 
#include "transport/usermanager.h"
 
#include "transport/conversationmanager.h"
 
#include "transport/localbuddy.h"
 
#include <cppunit/TestFixture.h>
 
#include <cppunit/extensions/HelperMacros.h>
 
#include <Swiften/Swiften.h>
 
#include <Swiften/EventLoop/DummyEventLoop.h>
 
#include <Swiften/Server/Server.h>
 
#include <Swiften/Network/DummyNetworkFactories.h>
 
#include <Swiften/Network/DummyConnectionServer.h>
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Server/ServerFromClientSession.h"
 
#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
 
#include "basictest.h"
 

	
 
using namespace Transport;
 

	
 
class ConversationManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
	CPPUNIT_TEST_SUITE(ConversationManagerTest);
 
	CPPUNIT_TEST(conversationSize);
 
	CPPUNIT_TEST(handleNormalMessages);
 
	CPPUNIT_TEST(handleNormalMessagesHeadline);
 
	CPPUNIT_TEST(handleGroupchatMessages);
 
	CPPUNIT_TEST(handleGroupchatMessagesBouncer);
 
	CPPUNIT_TEST(handleGroupchatMessagesBouncerLeave);
 
	CPPUNIT_TEST(handleGroupchatMessagesTwoResources);
 
	CPPUNIT_TEST(handleChatstateMessages);
 
	CPPUNIT_TEST(handleSubjectMessages);
 
	CPPUNIT_TEST(handleParticipantChanged);
 
	CPPUNIT_TEST(handleParticipantChangedTwoResources);
 
	CPPUNIT_TEST(handlePMFromXMPP);
 
	CPPUNIT_TEST(handleGroupchatRemoved);
 
	CPPUNIT_TEST(handleNicknameConflict);
 
	CPPUNIT_TEST(handleNotAuthorized);
 
	CPPUNIT_TEST(handleSetNickname);
 
	CPPUNIT_TEST_SUITE_END();
 

	
 
	public:
 
		TestingConversation *m_conv;
 
		boost::shared_ptr<Swift::Message> m_msg;
 

	
 
		void setUp (void) {
 
			m_conv = NULL;
 
			m_msg.reset();
 
			setMeUp();
 
			connectUser();
 
			add2Buddies();
 
			factory->onMessageToSend.connect(boost::bind(&ConversationManagerTest::handleMessageReceived, this, _1, _2));
 
			received.clear();
 
		}
 

	
 
		void tearDown (void) {
 
			received.clear();
 
			disconnectUser();
 
			factory->onMessageToSend.disconnect(boost::bind(&ConversationManagerTest::handleMessageReceived, this, _1, _2));
 
			tearMeDown();
 
		}
 

	
 
	void conversationSize() {
 
		std::cout << " = " << sizeof(Conversation) << " B";
 
	}
 

	
 
	void handleMessageReceived(TestingConversation *_conv, boost::shared_ptr<Swift::Message> &_msg) {
 
		m_conv = _conv;
 
		m_msg = _msg;
 
	}
 

	
 
	void handleChatstateMessages() {
 
		User *user = userManager->getUser("user@localhost");
 

	
 
		TestingConversation *conv = new TestingConversation(user->getConversationManager(), "buddy1");
 
		user->getConversationManager()->addConversation(conv);
 
		conv->onMessageToSend.connect(boost::bind(&ConversationManagerTest::handleMessageReceived, this, _1, _2));
 

	
 
		boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
		msg->addPayload(boost::make_shared<Swift::ChatState>(Swift::ChatState::Composing));
 

	
 
		// Forward it
 
		conv->handleMessage(msg);
 
		loop->processEvents();
 
		
 
		CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[0])));
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[0]))->getPayload<Swift::ChatState>());
 
		received.clear();
 

	
 
@@ -288,96 +293,104 @@ class ConversationManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTe
 
		received.clear();
 

	
 
		// send response
 
		msg->setFrom("user@localhost/resource");
 
		msg->setTo("#room@localhost");
 
		msg->setBody("response!");
 
		msg->setType(Swift::Message::Groupchat);
 
		injectMessage(msg);
 
		loop->processEvents();
 
		
 
		CPPUNIT_ASSERT_EQUAL(0, (int) received.size());
 
		CPPUNIT_ASSERT(m_msg);
 
		CPPUNIT_ASSERT_EQUAL(std::string("response!"), m_msg->getBody());
 
	}
 

	
 
	void handleGroupchatMessagesBouncer() {
 
		User *user = userManager->getUser("user@localhost");
 
		user->addUserSetting("stay_connected", "1");
 
		TestingConversation *conv = new TestingConversation(user->getConversationManager(), "#room", true);
 
		user->getConversationManager()->addConversation(conv);
 
		conv->onMessageToSend.connect(boost::bind(&ConversationManagerTest::handleMessageReceived, this, _1, _2));
 
		conv->setNickname("nickname");
 
		conv->addJID("user@localhost/resource");
 

	
 
		boost::shared_ptr<Swift::Message> msg0(new Swift::Message());
 
		msg0->setSubject("subject");
 
		conv->handleMessage(msg0, "anotheruser");
 

	
 
		CPPUNIT_ASSERT(!user->shouldCacheMessages());
 

	
 
		// disconnectUser
 
		userManager->disconnectUser("user@localhost");
 
		dynamic_cast<Swift::DummyTimerFactory *>(factories->getTimerFactory())->setTime(10);
 
		loop->processEvents();
 

	
 
		CPPUNIT_ASSERT(user->shouldCacheMessages());
 

	
 
		// reset resources should not touch this resource
 
		user->getConversationManager()->resetResources();
 

	
 
		boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
		msg->setBody("hi there!");
 
		conv->handleMessage(msg, "anotheruser");
 

	
 
		boost::shared_ptr<Swift::Message> msg2(new Swift::Message());
 
		msg2->setBody("hi there2!");
 
		conv->handleMessage(msg2, "anotheruser");
 

	
 
		loop->processEvents();
 
		CPPUNIT_ASSERT_EQUAL(0, (int) received.size());
 

	
 
		userRegistry->isValidUserPassword(Swift::JID("user@localhost/resource"), serverFromClientSession.get(), Swift::createSafeByteArray("password"));
 
		userRegistry->onPasswordValid(Swift::JID("user@localhost/resource"));
 
		loop->processEvents();
 

	
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setTo("#room@localhost/hanzz");
 
		response->setFrom("user@localhost/resource");
 

	
 
		Swift::MUCPayload *payload = new Swift::MUCPayload();
 
		payload->setPassword("password");
 
		response->addPayload(boost::shared_ptr<Swift::Payload>(payload));
 
		injectPresence(response);
 
		loop->processEvents();
 

	
 
		CPPUNIT_ASSERT_EQUAL(3, (int) received.size());
 
		CPPUNIT_ASSERT_EQUAL(4, (int) received.size());
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[1])));
 
		CPPUNIT_ASSERT_EQUAL(std::string("hi there!"), dynamic_cast<Swift::Message *>(getStanza(received[1]))->getBody());
 
		CPPUNIT_ASSERT_EQUAL(std::string("user@localhost/resource"), dynamic_cast<Swift::Message *>(getStanza(received[1]))->getTo().toString());
 
		CPPUNIT_ASSERT_EQUAL(std::string("#room@localhost/anotheruser"), dynamic_cast<Swift::Message *>(getStanza(received[1]))->getFrom().toString());
 

	
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[2])));
 
		CPPUNIT_ASSERT_EQUAL(std::string("hi there2!"), dynamic_cast<Swift::Message *>(getStanza(received[2]))->getBody());
 
		CPPUNIT_ASSERT_EQUAL(std::string("user@localhost/resource"), dynamic_cast<Swift::Message *>(getStanza(received[2]))->getTo().toString());
 
		CPPUNIT_ASSERT_EQUAL(std::string("#room@localhost/anotheruser"), dynamic_cast<Swift::Message *>(getStanza(received[2]))->getFrom().toString());
 

	
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[3])));
 
		CPPUNIT_ASSERT_EQUAL(std::string("subject"), dynamic_cast<Swift::Message *>(getStanza(received[3]))->getSubject());
 
		CPPUNIT_ASSERT_EQUAL(std::string("user@localhost/resource"), dynamic_cast<Swift::Message *>(getStanza(received[3]))->getTo().toString());
 
		CPPUNIT_ASSERT_EQUAL(std::string("#room@localhost/anotheruser"), dynamic_cast<Swift::Message *>(getStanza(received[3]))->getFrom().toString());
 
	}
 

	
 
	void handleGroupchatMessagesBouncerLeave() {
 
		User *user = userManager->getUser("user@localhost");
 
		user->addUserSetting("stay_connected", "1");
 
		TestingConversation *conv = new TestingConversation(user->getConversationManager(), "#room", true);
 
		user->getConversationManager()->addConversation(conv);
 
		conv->onMessageToSend.connect(boost::bind(&ConversationManagerTest::handleMessageReceived, this, _1, _2));
 
		conv->setNickname("nickname");
 
		conv->addJID("user@localhost/resource");
 

	
 
		CPPUNIT_ASSERT(!user->shouldCacheMessages());
 

	
 
		Swift::Presence::ref response3 = Swift::Presence::create();
 
		response3->setType(Swift::Presence::Unavailable);
 
		response3->setTo("#room@localhost/hanzz");
 
		response3->setFrom("user@localhost/resource");
 

	
 
		Swift::MUCPayload *payload3 = new Swift::MUCPayload();
 
		payload3->setPassword("password");
 
		response3->addPayload(boost::shared_ptr<Swift::Payload>(payload3));
 
		injectPresence(response3);
 
		loop->processEvents();
 

	
src/tests/localbuddy.cpp
Show inline comments
 
#include "transport/userregistry.h"
 
#include "transport/config.h"
 
#include "transport/storagebackend.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/conversation.h"
 
#include "transport/usermanager.h"
 
#include "transport/localbuddy.h"
 
#include <cppunit/TestFixture.h>
 
#include <cppunit/extensions/HelperMacros.h>
 
#include <Swiften/Swiften.h>
 
#include <Swiften/EventLoop/DummyEventLoop.h>
 
#include <Swiften/Server/Server.h>
 
#include <Swiften/Network/DummyNetworkFactories.h>
 
#include <Swiften/Network/DummyConnectionServer.h>
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Server/ServerFromClientSession.h"
 
#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
 
#include "basictest.h"
 

	
 
using namespace Transport;
 

	
 
class LocalBuddyTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
	CPPUNIT_TEST_SUITE(LocalBuddyTest);
 
	CPPUNIT_TEST(localBuddySize);
 
	CPPUNIT_TEST(createWithInvalidName);
 
	CPPUNIT_TEST(buddyFlagsFromJID);
 
	CPPUNIT_TEST(JIDToLegacyName);
 
	CPPUNIT_TEST(getSafeName);
 
	CPPUNIT_TEST(sendPresence);
 
	CPPUNIT_TEST(setAlias);
 
	CPPUNIT_TEST_SUITE_END();
 

	
 
	public:
 
		void setUp (void) {
 
			setMeUp();
 
			connectUser();
 
			received.clear();
 
		}
 

	
 
		void tearDown (void) {
 
			received.clear();
 
			disconnectUser();
 
			tearMeDown();
 
		}
 

	
 
	void localBuddySize() {
 
		std::cout << " = " << sizeof(LocalBuddy) << " B";
 
	}
 

	
 
	void createWithInvalidName() {
 
		User *user = userManager->getUser("user@localhost");
 
		CPPUNIT_ASSERT(user);
 

	
 
		std::vector<std::string> grp;
 
		grp.push_back("group");
 

	
 
		// with BUDDY_JID_ESCAPING it escapes /
 
		LocalBuddy *buddy = new LocalBuddy(user->getRosterManager(), -1, "msn/something", "Buddy 1", grp, BUDDY_JID_ESCAPING);
 
		CPPUNIT_ASSERT(buddy->isValid());
 
		CPPUNIT_ASSERT_EQUAL(std::string("msn\\2fsomething@localhost/bot"), buddy->getJID().toString());
 
		delete buddy;
 

	
 
		// without BUDDY_JID_ESCAPING it shoudl fail
 
		buddy = new LocalBuddy(user->getRosterManager(), -1, "msn/something", "Buddy 1", grp);
 
		CPPUNIT_ASSERT(!buddy->isValid());
 
		delete buddy;
 

	
 
		buddy = new LocalBuddy(user->getRosterManager(), -1, "\xd7\x92\xd7\x9c\xd7\x99\xd7\x9d@nimbuzz.com", "Buddy 1", grp);
 
		CPPUNIT_ASSERT(!buddy->isValid());
 
		delete buddy;
 
	}
 

	
 
	void JIDToLegacyName() {
src/tests/networkpluginserver.cpp
Show inline comments
 
@@ -4,79 +4,82 @@
 
#include "transport/storagebackend.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/conversation.h"
 
#include "transport/usermanager.h"
 
#include "transport/localbuddy.h"
 
#include "transport/settingsadhoccommand.h"
 
#include "transport/adhocmanager.h"
 
#include "transport/protocol.pb.h"
 
#include "transport/networkpluginserver.h"
 
#include <cppunit/TestFixture.h>
 
#include <cppunit/extensions/HelperMacros.h>
 
#include <Swiften/Swiften.h>
 
#include <Swiften/EventLoop/DummyEventLoop.h>
 
#include <Swiften/Server/Server.h>
 
#include <Swiften/Network/DummyNetworkFactories.h>
 
#include <Swiften/Network/DummyConnectionServer.h>
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Server/ServerFromClientSession.h"
 
#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
 
#include "basictest.h"
 
#include <cppunit/TestListener.h>
 
#include <cppunit/Test.h>
 
#include <time.h>    // for clock()
 
#include <stdint.h>
 

	
 
using namespace Transport;
 

	
 
class Clock {
 
	public:
 
		double m_beginTime;
 
		double m_elapsedTime;
 

	
 
		void start() {
 
			m_beginTime = clock();
 
		}
 

	
 
		void end() {
 
			m_elapsedTime = double(clock() - m_beginTime) / CLOCKS_PER_SEC;
 
		}
 

	
 
		double elapsedTime() const {
 
			return m_elapsedTime;
 
		}
 
};
 

	
 
class NetworkPluginServerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
	CPPUNIT_TEST_SUITE(NetworkPluginServerTest);
 
	CPPUNIT_TEST(handleBuddyChangedPayload);
 
	CPPUNIT_TEST(handleBuddyChangedPayloadNoEscaping);
 
	CPPUNIT_TEST(handleBuddyChangedPayloadUserContactInRoster);
 
	CPPUNIT_TEST(handleMessageHeadline);
 
	CPPUNIT_TEST(handleConvMessageAckPayload);
 
	CPPUNIT_TEST(handleRawXML);
 
	CPPUNIT_TEST(handleRawXMLSplit);
 

	
 
	CPPUNIT_TEST(benchmarkHandleBuddyChangedPayload);
 
	CPPUNIT_TEST(benchmarkSendUnavailablePresence);
 
	CPPUNIT_TEST_SUITE_END();
 

	
 
	public:
 
		NetworkPluginServer *serv;
 

	
 
		void setUp (void) {
 
			setMeUp();
 

	
 
			serv = new NetworkPluginServer(component, cfg, userManager, NULL, NULL);
 
			connectUser();
 
			received.clear();
 
		}
 

	
 
		void tearDown (void) {
 
			received.clear();
 
			disconnectUser();
 
			delete serv;
 
			tearMeDown();
 
		}
 

	
 
		void handleConvMessageAckPayload() {
 
			handleMessageHeadline();
 
			received.clear();
 
			User *user = userManager->getUser("user@localhost");
 
@@ -119,48 +122,91 @@ class NetworkPluginServerTest : public CPPUNIT_NS :: TestFixture, public BasicTe
 
			for (int i = 0; i < 2000; i++) {
 
				pbnetwork::Buddy buddy;
 
				buddy.set_username("user@localhost");
 
				buddy.set_buddyname("buddy" + boost::lexical_cast<std::string>(i)  + "@test");
 
				buddy.set_status((pbnetwork::StatusType) 2);
 

	
 
				std::string message;
 
				buddy.SerializeToString(&message);
 
				lst2.push_back(message);
 
			}
 

	
 
			clk.start();
 
			for (int i = 0; i < 2000; i++) {
 
				serv->handleBuddyChangedPayload(lst[i]);
 
				received.clear();
 
			}
 
			for (int i = 0; i < 2000; i++) {
 
				serv->handleBuddyChangedPayload(lst2[i]);
 
				received.clear();
 
			}
 
			clk.end();
 
			std::cerr << " " << clk.elapsedTime() << " s";
 
		}
 

	
 
		void benchmarkSendUnavailablePresence() {
 
			Clock clk;
 
			std::vector<std::string> lst;
 
			for (int i = 0; i < 1000; i++) {
 
				pbnetwork::Buddy buddy;
 
				buddy.set_username("user@localhost");
 
				buddy.set_buddyname("buddy" + boost::lexical_cast<std::string>(i)  + "@test");
 
				buddy.set_status((pbnetwork::StatusType) 5);
 

	
 
				std::string message;
 
				buddy.SerializeToString(&message);
 
				lst.push_back(message);
 
			}
 

	
 
			std::vector<std::string> lst2;
 
			for (int i = 0; i < 1000; i++) {
 
				pbnetwork::Buddy buddy;
 
				buddy.set_username("user@localhost");
 
				buddy.set_buddyname("buddy" + boost::lexical_cast<std::string>(1000+i)  + "@test");
 
				buddy.set_status((pbnetwork::StatusType) 2);
 

	
 
				std::string message;
 
				buddy.SerializeToString(&message);
 
				lst2.push_back(message);
 
			}
 

	
 
			
 
			for (int i = 0; i < 1000; i++) {
 
				serv->handleBuddyChangedPayload(lst[i]);
 
				received.clear();
 
			}
 
			for (int i = 0; i < 1000; i++) {
 
				serv->handleBuddyChangedPayload(lst2[i]);
 
				received.clear();
 
			}
 

	
 
			User *user = userManager->getUser("user@localhost");
 
			clk.start();
 
			user->getRosterManager()->sendUnavailablePresences("user@localhost");
 
			clk.end();
 
			std::cerr << " " << clk.elapsedTime() << " s";
 
		}
 

	
 
		void handleBuddyChangedPayload() {
 
			User *user = userManager->getUser("user@localhost");
 

	
 
			pbnetwork::Buddy buddy;
 
			buddy.set_username("user@localhost");
 
			buddy.set_buddyname("buddy1@test");
 
			buddy.set_status(pbnetwork::STATUS_NONE);
 

	
 
			std::string message;
 
			buddy.SerializeToString(&message);
 

	
 
			serv->handleBuddyChangedPayload(message);
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
			Swift::RosterPayload::ref payload1 = getStanza(received[0])->getPayload<Swift::RosterPayload>();
 
			CPPUNIT_ASSERT_EQUAL(1, (int) payload1->getItems().size());
 
			Swift::RosterItemPayload item = payload1->getItems()[0];
 
			CPPUNIT_ASSERT_EQUAL(std::string("buddy1\\40test@localhost"), item.getJID().toString());
 
		}
 

	
 
		void handleBuddyChangedPayloadNoEscaping() {
 
			std::istringstream ifs("service.server_mode = 1\nservice.jid_escaping=0\nservice.jid=localhost\nservice.more_resources=1\n");
 
			cfg->load(ifs);
 
			User *user = userManager->getUser("user@localhost");
 

	
 
@@ -177,64 +223,106 @@ class NetworkPluginServerTest : public CPPUNIT_NS :: TestFixture, public BasicTe
 
			Swift::RosterPayload::ref payload1 = getStanza(received[0])->getPayload<Swift::RosterPayload>();
 
			CPPUNIT_ASSERT_EQUAL(1, (int) payload1->getItems().size());
 
			Swift::RosterItemPayload item = payload1->getItems()[0];
 
			CPPUNIT_ASSERT_EQUAL(std::string("buddy1%test@localhost"), item.getJID().toString());
 

	
 
			std::istringstream ifs2("service.server_mode = 1\nservice.jid_escaping=1\nservice.jid=localhost\nservice.more_resources=1\n");
 
			cfg->load(ifs2);
 
		}
 

	
 
		void handleBuddyChangedPayloadUserContactInRoster() {
 
			User *user = userManager->getUser("user@localhost");
 

	
 
			pbnetwork::Buddy buddy;
 
			buddy.set_username("user@localhost");
 
			buddy.set_buddyname("user");
 

	
 
			std::string message;
 
			buddy.SerializeToString(&message);
 

	
 
			serv->handleBuddyChangedPayload(message);
 
			CPPUNIT_ASSERT_EQUAL(0, (int) received.size());
 
		}
 

	
 
		void handleRawXML() {
 
			cfg->updateBackendConfig("[features]\nrawxml=1\n");
 
			User *user = userManager->getUser("user@localhost");
 
			std::vector<std::string> grp;
 
			grp.push_back("group1");
 
			LocalBuddy *buddy = new LocalBuddy(user->getRosterManager(), -1, "buddy1@domain.tld", "Buddy 1", grp, BUDDY_JID_ESCAPING);
 
			user->getRosterManager()->setBuddy(buddy);
 
			received.clear();
 

	
 
			std::string xml = "<presence from='buddy1@domain.tld' to='user@localhost'/>";
 

	
 
			std::string xml = "<presence from='buddy1@domain.tld/res' to='user@localhost'/>";
 
			serv->handleRawXML(xml);
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 

	
 
			std::string xml2 = "<presence from='buddy1@domain.tld/res2' to='user@localhost'/>";
 
			serv->handleRawXML(xml2);
 

	
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(std::string("buddy1\\40domain.tld@localhost"), dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getFrom().toString());
 
			CPPUNIT_ASSERT_EQUAL(std::string("buddy1\\40domain.tld@localhost/res"), dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getFrom().toString());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[1])));
 
			CPPUNIT_ASSERT_EQUAL(std::string("buddy1\\40domain.tld@localhost/res2"), dynamic_cast<Swift::Presence *>(getStanza(received[1]))->getFrom().toString());
 

	
 
			received.clear();
 
			user->getRosterManager()->sendUnavailablePresences("user@localhost");
 

	
 
			CPPUNIT_ASSERT_EQUAL(3, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(std::string("buddy1\\40domain.tld@localhost/res"), dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getFrom().toString());
 
			CPPUNIT_ASSERT_EQUAL(Swift::Presence::Unavailable, dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getType());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[1])));
 
			CPPUNIT_ASSERT_EQUAL(std::string("buddy1\\40domain.tld@localhost/res2"), dynamic_cast<Swift::Presence *>(getStanza(received[1]))->getFrom().toString());
 
			CPPUNIT_ASSERT_EQUAL(Swift::Presence::Unavailable, dynamic_cast<Swift::Presence *>(getStanza(received[1]))->getType());
 
		}
 

	
 
		void handleMessageHeadline() {
 
			User *user = userManager->getUser("user@localhost");
 

	
 
			pbnetwork::ConversationMessage m;
 
			m.set_username("user@localhost");
 
			m.set_buddyname("user");
 
			m.set_message("msg");
 
			m.set_nickname("");
 
			m.set_xhtml("");
 
			m.set_timestamp("");
 
			m.set_headline(true);
 

	
 
			std::string message;
 
			m.SerializeToString(&message);
 

	
 
			serv->handleConvMessagePayload(message, false);
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::Message::Chat, dynamic_cast<Swift::Message *>(getStanza(received[0]))->getType());
 

	
 
			received.clear();
 
			user->addUserSetting("send_headlines", "1");
 
			serv->handleConvMessagePayload(message, false);
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::Message::Headline, dynamic_cast<Swift::Message *>(getStanza(received[0]))->getType());
 
		}
 

	
 
		void handleRawXMLSplit() {
 
			cfg->updateBackendConfig("[features]\nrawxml=1\n");
 
			User *user = userManager->getUser("user@localhost");
 
			std::vector<std::string> grp;
 
			grp.push_back("group1");
 
			LocalBuddy *buddy = new LocalBuddy(user->getRosterManager(), -1, "buddy1@domain.tld", "Buddy 1", grp, BUDDY_JID_ESCAPING);
 
			user->getRosterManager()->setBuddy(buddy);
 
			received.clear();
 

	
 
			std::string xml = "<presence from='buddy1@domain.tld/res' ";
 
			serv->handleRawXML(xml);
 

	
 
			std::string xml2 = " to='user@localhost'/>";
 
			serv->handleRawXML(xml2);
 

	
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(std::string("buddy1\\40domain.tld@localhost/res"), dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getFrom().toString());
 
		}
 
};
 

	
 
CPPUNIT_TEST_SUITE_REGISTRATION (NetworkPluginServerTest);
0 comments (0 inline, 0 general)