Changeset - addac0040c4a
[Not reviewed]
0 5 0
HanzZ - 12 years ago 2013-02-13 08:06:05
hanzz.k@gmail.com
Communi: Fix wrong copyright. There is no original libcommuni code used now.
5 files changed with 90 insertions and 21 deletions:
0 comments (0 inline, 0 general)
backends/libcommuni/ircnetworkplugin.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2013, 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 "ircnetworkplugin.h"
 
#include <IrcCommand>
 
#include <IrcMessage>
 
#include "transport/logging.h"
 

	
 
DEFINE_LOGGER(logger, "IRCNetworkPlugin");
 

	
 
#define FROM_UTF8(WHAT) QString::fromUtf8((WHAT).c_str(), (WHAT).size())
 
#define TO_UTF8(WHAT) std::string((WHAT).toUtf8().data(), (WHAT).toUtf8().size())
 

	
 
IRCNetworkPlugin::IRCNetworkPlugin(Config *config, Swift::QtEventLoop *loop, const std::string &host, int port) {
 
	this->config = config;
 
	m_currentServer = 0;
 
	m_firstPing = true;
 
	m_socket = new QTcpSocket();
 
	m_socket->connectToHost(FROM_UTF8(host), port);
 
	connect(m_socket, SIGNAL(readyRead()), this, SLOT(readData()));
 

	
 
	std::string server = CONFIG_STRING_DEFAULTED(config, "service.irc_server", "");
 
	if (!server.empty()) {
 
		m_servers.push_back(server);
 
	}
 
	else {
 
		
 
		std::list<std::string> list;
 
		list = CONFIG_LIST_DEFAULTED(config, "service.irc_server", list);
 
		
 
		m_servers.insert(m_servers.begin(), list.begin(), list.end());
 
	}
 

	
 
	if (CONFIG_HAS_KEY(config, "service.irc_identify")) {
 
		m_identify = CONFIG_STRING(config, "service.irc_identify");
 
	}
 
	else {
 
		m_identify = "NickServ identify $name $password";
 
	}
 
}
 

	
 
void IRCNetworkPlugin::tryNextServer() {
 
	if (!m_servers.empty()) {
 
		int nextServer = (m_currentServer + 1) % m_servers.size();
 
		LOG4CXX_INFO(logger, "Server " << m_servers[m_currentServer] << " disconnected user. Next server to try will be " << m_servers[nextServer]);
 
		m_currentServer = nextServer;
 
	}
 
}
 

	
 
void IRCNetworkPlugin::readData() {
 
	size_t availableBytes = m_socket->bytesAvailable();
 
	if (availableBytes == 0)
 
		return;
 

	
 
	if (m_firstPing) {
 
		m_firstPing = false;
 
		// Users can join the network without registering if we allow
 
		// one user to connect multiple IRC networks.
 
		NetworkPlugin::PluginConfig cfg;
 
		if (m_servers.empty()) {
 
			cfg.setNeedRegistration(false);
 
		}
 
		cfg.setSupportMUC(true);
 
		cfg.disableJIDEscaping();
 
		sendConfig(cfg);
 
	}
 

	
 
	std::string d = std::string(m_socket->readAll().data(), availableBytes);
 
	handleDataRead(d);
 
}
 

	
 
void IRCNetworkPlugin::sendData(const std::string &string) {
 
	m_socket->write(string.c_str(), string.size());
 
}
 

	
 
MyIrcSession *IRCNetworkPlugin::createSession(const std::string &user, const std::string &hostname, const std::string &nickname, const std::string &password, const std::string &suffix) {
 
	MyIrcSession *session = new MyIrcSession(user, this, suffix);
 
	session->setUserName(FROM_UTF8(nickname));
 
	session->setNickName(FROM_UTF8(nickname));
 
	session->setRealName(FROM_UTF8(nickname));
 
	session->setHost(FROM_UTF8(hostname));
 
	session->setPort(6667);
 
// 	session->setEncoding("UTF8");
 

	
 
	if (!password.empty()) {
 
		std::string identify = m_identify;
 
		boost::replace_all(identify, "$password", password);
 
		boost::replace_all(identify, "$name", nickname);
 
		session->setIdentify(identify);
 
	}
 

	
 
	LOG4CXX_INFO(logger, user << ": Connecting " << hostname << " as " << nickname << ", suffix=" << suffix);
 

	
 
	session->open();
 

	
 
	return session;
 
}
 

	
 
void IRCNetworkPlugin::handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
	if (!m_servers.empty()) {
 
		// legacy name is user's nickname
 
		if (m_sessions[user] != NULL) {
 
			LOG4CXX_WARN(logger, user << ": Already logged in.");
 
			return;
 
		}
 

	
 
		m_sessions[user] = createSession(user, m_servers[m_currentServer], legacyName, password, "");
 
	}
 
	else {
 
		// We are waiting for first room join to connect user to IRC network, because we don't know which
 
		// network he choose...
 
		LOG4CXX_INFO(logger, user << ": Ready for connections");
 
		handleConnected(user);
 
	}
 
}
 

	
 
void IRCNetworkPlugin::handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
	if (m_sessions[user] == NULL) {
 
		LOG4CXX_WARN(logger, user << ": Already disconnected.");
 
		return;
 
	}
 
	LOG4CXX_INFO(logger, user << ": Disconnecting.");
 
	m_sessions[user]->close();
 
	m_sessions[user]->deleteLater();
 
	m_sessions.erase(user);
 
}
 

	
 
std::string IRCNetworkPlugin::getSessionName(const std::string &user, const std::string &legacyName) {
 
	std::string u = user;
 
	if (!CONFIG_BOOL(config, "service.server_mode") && m_servers.empty()) {
 
		u = user + legacyName.substr(legacyName.find("@") + 1);
 
		if (u.find("/") != std::string::npos) {
 
			u = u.substr(0, u.find("/"));
 
		}
 
	}
 
	return u;
 
}
 

	
 
std::string IRCNetworkPlugin::getTargetName(const std::string &legacyName) {
 
	std::string r = legacyName;
 
// 	if (!CONFIG_BOOL(config, "service.server_mode")) {
 
		if (legacyName.find("/") == std::string::npos) {
 
			r = legacyName.substr(0, r.find("@"));
 
		}
 
		else {
 
			r = legacyName.substr(legacyName.find("/") + 1);
 
		}
 
// 	}
 
	return r;
 
}
 

	
 
void IRCNetworkPlugin::handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &/*xhtml*/, const std::string &/*id*/) {
 
	std::string session = getSessionName(user, legacyName);
 
	if (m_sessions[session] == NULL) {
 
		LOG4CXX_WARN(logger, user << ": Session name: " << session << ", No session for user");
 
		return;
 
	}
 

	
 
	std::string target = getTargetName(legacyName);
 
	// We are sending PM message. On XMPP side, user is sending PM using the particular channel,
 
	// for example #room@irc.freenode.org/hanzz. On IRC side, we are forwarding this message
 
	// just to "hanzz". Therefore we have to somewhere store, that message from "hanzz" should
 
	// be mapped to #room@irc.freenode.org/hanzz.
 
	if (legacyName.find("/") != std::string::npos) {
 
		m_sessions[session]->addPM(target, legacyName.substr(0, legacyName.find("@")));
 
	}
 

	
 
	LOG4CXX_INFO(logger, user << ": Session name: " << session << ", message to " << target);
 

	
 
	if (message.find("/me") == 0) {
 
		m_sessions[session]->sendCommand(IrcCommand::createCtcpAction(FROM_UTF8(target), FROM_UTF8(message.substr(4))));
 
	}
 
	else {
 
		m_sessions[session]->sendCommand(IrcCommand::createMessage(FROM_UTF8(target), FROM_UTF8(message)));
 
	}
 

	
 
	if (target.find("#") == 0) {
 
		handleMessage(user, legacyName, message, TO_UTF8(m_sessions[session]->nickName()));
 
	}
 
}
 

	
 
void IRCNetworkPlugin::handleRoomSubjectChangedRequest(const std::string &user, const std::string &room, const std::string &message) {
 
	std::string session = getSessionName(user, room);
 
	if (m_sessions[session] == NULL) {
 
		LOG4CXX_WARN(logger, user << ": Session name: " << session << ", No session for user");
 
		return;
 
	}
 

	
 
	std::string target = getTargetName(room);
 
	m_sessions[session]->sendCommand(IrcCommand::createTopic(FROM_UTF8(target), FROM_UTF8(message)));
 
}
 

	
 
void IRCNetworkPlugin::handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &password) {
 
	std::string session = getSessionName(user, room);
 
	std::string target = getTargetName(room);
 

	
 
	LOG4CXX_INFO(logger, user << ": Session name: " << session << ", Joining room " << target);
 
	if (m_sessions[session] == NULL) {
 
		if (m_servers.empty()) {
 
			// in gateway mode we want to login this user to network according to legacyName
 
			if (room.find("@") != std::string::npos) {
 
				// suffix is %irc.freenode.net to let MyIrcSession return #room%irc.freenode.net
 
				m_sessions[session] = createSession(user, room.substr(room.find("@") + 1), nickname, "", room.substr(room.find("@")));
 
			}
 
			else {
 
				LOG4CXX_WARN(logger, user << ": There's no proper server defined in room to which this user wants to join: " << room);
 
				return;
 
			}
 
		}
 
		else {
 
			LOG4CXX_WARN(logger, user << ": Join room requested for unconnected user");
 
			return;
 
		}
 
	}
 

	
 
	m_sessions[session]->addAutoJoinChannel(target, password);
 
	m_sessions[session]->sendCommand(IrcCommand::createJoin(FROM_UTF8(target), FROM_UTF8(password)));
 
	m_sessions[session]->rooms += 1;
 
	// update nickname, because we have nickname per session, no nickname per room.
 
	handleRoomNicknameChanged(user, target, TO_UTF8(m_sessions[session]->nickName()));
 
}
 

	
 
void IRCNetworkPlugin::handleLeaveRoomRequest(const std::string &user, const std::string &room) {
 
	std::string session = getSessionName(user, room);
 
	std::string target = getTargetName(room);
 

	
 
	LOG4CXX_INFO(logger, user << ": Session name: " << session << ", Leaving room " << target);
 
	if (m_sessions[session] == NULL)
 
		return;
 

	
 
	m_sessions[session]->sendCommand(IrcCommand::createPart(FROM_UTF8(target)));
 
	m_sessions[session]->removeAutoJoinChannel(target);
 
	m_sessions[session]->rooms -= 1;
 

	
 
	if (m_sessions[session]->rooms <= 0 && m_servers.empty()) {
 
		LOG4CXX_INFO(logger, user << ": Session name: " << session << ", User is not in any room, disconnecting from network");
 
		m_sessions[session]->close();
 
		m_sessions[session]->deleteLater();
 
		m_sessions.erase(session);
 
	}
 
}
backends/libcommuni/ircnetworkplugin.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2013, 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
 
 */
 

	
 
#pragma once
 

	
 
#include "transport/config.h"
 
#include "transport/networkplugin.h"
 
#include "session.h"
 
#include <QtCore>
 
#include <QtNetwork>
 
#include "Swiften/EventLoop/Qt/QtEventLoop.h"
 
#include "ircnetworkplugin.h"
 

	
 

	
 
class IRCNetworkPlugin : public QObject, public NetworkPlugin {
 
	Q_OBJECT
 

	
 
	public:
 
		IRCNetworkPlugin(Config *config, Swift::QtEventLoop *loop, const std::string &host, int port);
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password);
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName);
 

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &/*xhtml*/, const std::string &/*id*/);
 

	
 
		void handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &password);
 

	
 
		void handleLeaveRoomRequest(const std::string &user, const std::string &room);
 

	
 
		void handleRoomSubjectChangedRequest(const std::string &user, const std::string &room, const std::string &message);
 

	
 
		void tryNextServer();
 

	
 
	public slots:
 
		void readData();
 
		void sendData(const std::string &string);
 

	
 
	private:
 
		MyIrcSession *createSession(const std::string &user, const std::string &hostname, const std::string &nickname, const std::string &password, const std::string &suffix = "");
 
		std::string getSessionName(const std::string &user, const std::string &legacyName);
 
		std::string getTargetName(const std::string &legacyName);
 

	
 
	private:
 
		Config *config;
 
		QTcpSocket *m_socket;
 
		std::map<std::string, MyIrcSession *> m_sessions;
 
		std::vector<std::string> m_servers;
 
		int m_currentServer;
 
		std::string m_identify;
 
		bool m_firstPing;
 
};
backends/libcommuni/main.cpp
Show inline comments
 
/*
 
 * Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * This example is free, and not covered by LGPL license. There is no
 
 * restriction applied to their modification, redistribution, using and so on.
 
 * You can study them, modify them, use them in your own program - either
 
 * completely or partially. By using it you may give me some credits in your
 
 * program, but you don't have to.
 
 * Copyright (C) 2013, 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 "transport/config.h"
 
#include "transport/networkplugin.h"
 
#include "transport/logging.h"
 
#include "session.h"
 
#include <QtCore>
 
#include <QtNetwork>
 
#include "Swiften/EventLoop/Qt/QtEventLoop.h"
 
#include "ircnetworkplugin.h"
 

	
 
using namespace boost::program_options;
 
using namespace Transport;
 

	
 
NetworkPlugin * np = NULL;
 

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

	
 
	std::string error;
 
	Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
 
	if (cfg == NULL) {
 
		std::cerr << error;
 
		return 1;
 
	}
 

	
 
	Logging::initBackendLogging(cfg);
 

	
 
	QCoreApplication app(argc, argv);
 

	
 
	Swift::QtEventLoop eventLoop;
 

	
 

	
 
	np = new IRCNetworkPlugin(cfg, &eventLoop, host, port);
 
	return app.exec();
 
}
backends/libcommuni/session.cpp
Show inline comments
 
/*
 
 * Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * This example is free, and not covered by LGPL license. There is no
 
 * restriction applied to their modification, redistribution, using and so on.
 
 * You can study them, modify them, use them in your own program - either
 
 * completely or partially. By using it you may give me some credits in your
 
 * program, but you don't have to.
 
 * Copyright (C) 2013, 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 "session.h"
 
#include <QtCore>
 
#include <iostream>
 
#include <IrcCommand>
 
#include <IrcMessage>
 

	
 
#include "ircnetworkplugin.h"
 

	
 
#define FROM_UTF8(WHAT) QString::fromUtf8((WHAT).c_str(), (WHAT).size())
 
#define TO_UTF8(WHAT) std::string((WHAT).toUtf8().data(), (WHAT).toUtf8().size())
 

	
 
#include "transport/logging.h"
 

	
 
DEFINE_LOGGER(logger, "IRCSession");
 

	
 
static bool sentList;
 

	
 
MyIrcSession::MyIrcSession(const std::string &user, IRCNetworkPlugin *np, const std::string &suffix, QObject* parent) : IrcSession(parent)
 
{
 
	this->np = np;
 
	this->user = user;
 
	this->suffix = suffix;
 
	m_connected = false;
 
	rooms = 0;
 
	connect(this, SIGNAL(disconnected()), SLOT(on_disconnected()));
 
	connect(this, SIGNAL(socketError(QAbstractSocket::SocketError)), SLOT(on_socketError(QAbstractSocket::SocketError)));
 
	connect(this, SIGNAL(connected()), SLOT(on_connected()));
 
	connect(this, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
 

	
 
	m_awayTimer = new QTimer(this);
 
	connect(m_awayTimer, SIGNAL(timeout()), this, SLOT(awayTimeout()));
 
	m_awayTimer->start(5*1000);
 
}
 

	
 
MyIrcSession::~MyIrcSession() {
 
	delete m_awayTimer;
 
}
 

	
 
void MyIrcSession::on_connected() {
 
	m_connected = true;
 
	if (suffix.empty()) {
 
		np->handleConnected(user);
 
// 		if (!sentList) {
 
// 			sendCommand(IrcCommand::createList("", ""));
 
// 			sentList = true;
 
// 		}
 
	}
 

	
 
// 	sendCommand(IrcCommand::createCapability("REQ", QStringList("away-notify")));
 

	
 
	for(AutoJoinMap::iterator it = m_autoJoin.begin(); it != m_autoJoin.end(); it++) {
 
		sendCommand(IrcCommand::createJoin(FROM_UTF8(it->second->getChannel()), FROM_UTF8(it->second->getPassword())));
 
	}
 

	
 
	if (getIdentify().find(" ") != std::string::npos) {
 
		std::string to = getIdentify().substr(0, getIdentify().find(" "));
 
		std::string what = getIdentify().substr(getIdentify().find(" ") + 1);
 
		sendCommand(IrcCommand::createMessage(FROM_UTF8(to), FROM_UTF8(what)));
 
	}
 
}
 

	
 
void MyIrcSession::on_socketError(QAbstractSocket::SocketError error) {
 
	std::string reason;
 
	switch(error) {
 
		case QAbstractSocket::ConnectionRefusedError: reason = "The connection was refused by the peer (or timed out)."; break;
 
		case QAbstractSocket::RemoteHostClosedError: reason = "The remote host closed the connection."; break;
 
		case QAbstractSocket::HostNotFoundError: reason = "The host address was not found."; break;
 
		case QAbstractSocket::SocketAccessError: reason = "The socket operation failed because the application lacked the required privileges."; break;
 
		case QAbstractSocket::SocketResourceError: reason = "The local system ran out of resources."; break;
 
		case QAbstractSocket::SocketTimeoutError: reason = "The socket operation timed out."; break;
 
		case QAbstractSocket::DatagramTooLargeError: reason = "The datagram was larger than the operating system's limit."; break;
 
		case QAbstractSocket::NetworkError: reason = "An error occurred with the network."; break;
 
		case QAbstractSocket::SslHandshakeFailedError: reason = "The SSL/TLS handshake failed, so the connection was closed"; break;
 
		case QAbstractSocket::UnknownSocketError: reason = "An unidentified error occurred."; break;
 
		default: reason= "Unknown error."; break;
 
	};
 

	
 
	if (!suffix.empty()) {
 
		for(AutoJoinMap::iterator it = m_autoJoin.begin(); it != m_autoJoin.end(); it++) {
 
			np->handleParticipantChanged(user, TO_UTF8(nickName()), it->second->getChannel() + suffix, pbnetwork::PARTICIPANT_FLAG_ROOM_NOT_FOUND, pbnetwork::STATUS_NONE, reason);
 
		}
 
	}
 
	else {
 
		np->handleDisconnected(user, 0, reason);
 
		np->tryNextServer();
 
	}
 
	m_connected = false;
 
}
 

	
 
void MyIrcSession::on_disconnected() {
 
	if (suffix.empty()) {
 
		np->handleDisconnected(user, 0, "");
 
		np->tryNextServer();
 
	}
 
	m_connected = false;
 
}
 

	
 
bool MyIrcSession::correctNickname(std::string &nickname) {
 
	bool flags = 0;
 
	switch(nickname.at(0)) {
 
		case '@': nickname = nickname.substr(1); flags = 1; break;
 
		case '+': nickname = nickname.substr(1); break;
 
		case '~': nickname = nickname.substr(1); break;
 
		case '&': nickname = nickname.substr(1); break;
 
		case '%': nickname = nickname.substr(1); break;
 
		default: break;
 
	}
 
	return flags;
 
}
 

	
 
void MyIrcSession::on_joined(IrcMessage *message) {
 
	IrcJoinMessage *m = (IrcJoinMessage *) message;
 
	std::string nickname = TO_UTF8(m->sender().name());
 
	bool op = correctNickname(nickname);
 
	getIRCBuddy(TO_UTF8(m->channel().toLower()), nickname).setOp(op);
 
	np->handleParticipantChanged(user, nickname, TO_UTF8(m->channel().toLower()) + suffix, op, pbnetwork::STATUS_ONLINE);
 
	LOG4CXX_INFO(logger, user << ": " << nickname << " joined " << TO_UTF8(m->channel().toLower()) + suffix);
 
}
 

	
 

	
 
void MyIrcSession::on_parted(IrcMessage *message) {
 
	IrcPartMessage *m = (IrcPartMessage *) message;
 
	std::string nickname = TO_UTF8(m->sender().name());
 
	bool op = correctNickname(nickname);
 
	removeIRCBuddy(TO_UTF8(m->channel().toLower()), nickname);
 
	LOG4CXX_INFO(logger, user << ": " << nickname << " parted " << TO_UTF8(m->channel().toLower()) + suffix);
 
	np->handleParticipantChanged(user, nickname, TO_UTF8(m->channel().toLower()) + suffix, op, pbnetwork::STATUS_NONE, TO_UTF8(m->reason()));
 
}
 

	
 
void MyIrcSession::on_quit(IrcMessage *message) {
 
	IrcQuitMessage *m = (IrcQuitMessage *) message;
 
	std::string nickname = TO_UTF8(m->sender().name());
 
	bool op = correctNickname(nickname);
 

	
 
	for(AutoJoinMap::iterator it = m_autoJoin.begin(); it != m_autoJoin.end(); it++) {
 
		if (!hasIRCBuddy(it->second->getChannel(), nickname)) {
 
			continue;
 
		}
 
		removeIRCBuddy(it->second->getChannel(), nickname);
 
		LOG4CXX_INFO(logger, user << ": " << nickname << " quit " << it->second->getChannel() + suffix);
 
		np->handleParticipantChanged(user, nickname, it->second->getChannel() + suffix, op, pbnetwork::STATUS_NONE, TO_UTF8(m->reason()));
 
	}
 
}
 

	
 
void MyIrcSession::on_nickChanged(IrcMessage *message) {
 
	IrcNickMessage *m = (IrcNickMessage *) message;
 
	std::string nickname = TO_UTF8(m->sender().name());
 
	correctNickname(nickname);
 

	
 
	for(AutoJoinMap::iterator it = m_autoJoin.begin(); it != m_autoJoin.end(); it++) {
 
		if (!hasIRCBuddy(it->second->getChannel(), nickname)) {
 
			continue;
 
		}
 
		IRCBuddy &buddy = getIRCBuddy(it->second->getChannel(), nickname);
 
		LOG4CXX_INFO(logger, user << ": " << nickname << " changed nickname to " << TO_UTF8(m->nick()));
 
		np->handleParticipantChanged(user, nickname, it->second->getChannel() + suffix,(int) buddy.isOp(), pbnetwork::STATUS_ONLINE, "", TO_UTF8(m->nick()));
 
	}
 
}
 

	
 
void MyIrcSession::on_modeChanged(IrcMessage *message) {
 
	IrcModeMessage *m = (IrcModeMessage *) message;
 

	
 
	// mode changed: "#testik" "HanzZ" "+o" "hanzz_k"
 
	std::string nickname = TO_UTF8(m->argument());
 
	std::string mode = TO_UTF8(m->mode());
 
	if (nickname.empty())
 
		return;
 

	
 
	correctNickname(nickname);
 

	
 
	if (!hasIRCBuddy(TO_UTF8(m->target().toLower()), nickname)) {
 
		return;
 
	}
 
	IRCBuddy &buddy = getIRCBuddy(TO_UTF8(m->target().toLower()), nickname);
 
	if (mode == "+o") {
 
		buddy.setOp(true);
 
	}
 
	else {
 
		buddy.setOp(false);
 
	}
 
	
 
	np->handleParticipantChanged(user, nickname, TO_UTF8(m->target().toLower()) + suffix,(int) buddy.isOp(), pbnetwork::STATUS_ONLINE, "");
 

	
 
	LOG4CXX_INFO(logger, user << ": " << nickname << " changed mode to " << mode << " in " << TO_UTF8(m->target().toLower()));
 
}
 

	
 
void MyIrcSession::on_topicChanged(IrcMessage *message) {
 
	IrcTopicMessage *m = (IrcTopicMessage *) message;
 

	
 
	std::string nickname = TO_UTF8(m->sender().name());
 
	correctNickname(nickname);
 

	
 
	LOG4CXX_INFO(logger, user << ": " << nickname << " topic changed to " << TO_UTF8(m->topic()));
 
	np->handleSubject(user, TO_UTF8(m->channel().toLower()) + suffix, TO_UTF8(m->topic()), nickname);
 
}
 

	
 
void MyIrcSession::on_messageReceived(IrcMessage *message) {
 
	IrcPrivateMessage *m = (IrcPrivateMessage *) message;
 
	if (m->isRequest()) {
 
		QString request = m->message().split(" ", QString::SkipEmptyParts).value(0).toUpper();
 
		if (request == "PING" || request == "TIME" || request == "VERSION") {
 
			LOG4CXX_INFO(logger, user << ": " << TO_UTF8(request) << " received and has been answered");
 
			return;
 
		}
 
	}
 

	
 
	QString msg = m->message();
 
	if (m->isAction()) {
 
		msg = QString("/me ") + msg;
 
	}
 

	
 
	std::string target = TO_UTF8(m->target().toLower());
 
	LOG4CXX_INFO(logger, user << ": Message from " << target);
 
	if (target.find("#") == 0) {
 
		std::string nickname = TO_UTF8(m->sender().name());
 
		correctNickname(nickname);
 
		np->handleMessage(user, target + suffix, TO_UTF8(msg), nickname);
 
	}
 
	else {
 
		std::string nickname = TO_UTF8(m->sender().name());
 
		correctNickname(nickname);
 
		if (m_pms.find(nickname) != m_pms.end()) {
 
			if (hasIRCBuddy(m_pms[nickname], nickname)) {
 
				LOG4CXX_INFO(logger, nickname);
 
				np->handleMessage(user, m_pms[nickname] + suffix, TO_UTF8(msg), nickname, "", "", false, true);
 
				return;
 
			}
 
			else {
 
				nickname = nickname + suffix;
 
			}
 
		}
 
		else {
 
			nickname = nickname + suffix;
 
		}
 

	
 
		LOG4CXX_INFO(logger, nickname);
 
		np->handleMessage(user, nickname, TO_UTF8(msg));
 
	}
 
}
 

	
 
void MyIrcSession::on_numericMessageReceived(IrcMessage *message) {
 
	QString channel;
 
	QStringList members;
 
	std::string nick;
 

	
 
	IrcNumericMessage *m = (IrcNumericMessage *) message;
 
	QStringList parameters = m->parameters();
 
	switch (m->code()) {
 
		case 301:
 
			break;
 
		case 315:
 
			LOG4CXX_INFO(logger, "End of /who request " << TO_UTF8(parameters[1]));
 
			break;
 
		case 332:
 
			m_topicData = TO_UTF8(parameters[2]);
 
			break;
 
		case 333:
 
			nick = TO_UTF8(parameters[2]);
 
			if (nick.find("!") != std::string::npos) {
 
				nick = nick.substr(0, nick.find("!"));
 
			}
 
			if (nick.find("/") != std::string::npos) {
 
				nick = nick.substr(0, nick.find("/"));
 
			}
 
			np->handleSubject(user, TO_UTF8(parameters[1].toLower()) + suffix, m_topicData, nick);
 
			break;
 
		case 352: {
 
			channel = parameters[1].toLower();
 
			nick = TO_UTF8(parameters[5]);
 
			IRCBuddy &buddy = getIRCBuddy(TO_UTF8(channel), nick);
 

	
 
			if (parameters[6].toUpper().startsWith("G")) {
 
				if (!buddy.isAway()) {
 
					buddy.setAway(true);
 
					np->handleParticipantChanged(user, nick, TO_UTF8(channel) + suffix, buddy.isOp(), pbnetwork::STATUS_AWAY);
 
				}
 
			}
 
			else if (buddy.isAway()) {
 
				buddy.setAway(false);
 
				np->handleParticipantChanged(user, nick, TO_UTF8(channel) + suffix, buddy.isOp(), pbnetwork::STATUS_ONLINE);
 
			}
 
			break;
 
		}
 
		case 353:
 
			channel = parameters[2].toLower();
 
			members = parameters[3].split(" ");
 

	
 
			LOG4CXX_INFO(logger, user << ": Received members for " << TO_UTF8(channel) << suffix);
 
			for (int i = 0; i < members.size(); i++) {
 
				bool op = 0;
 
				std::string nickname = TO_UTF8(members.at(i));
 
				op = correctNickname(nickname);
 
				IRCBuddy &buddy = getIRCBuddy(TO_UTF8(channel), nickname);
 
				buddy.setOp(op);
 
				np->handleParticipantChanged(user, nickname, TO_UTF8(channel) + suffix, buddy.isOp(), pbnetwork::STATUS_ONLINE);
 
			}
 

	
 
			break;
 
		case 366:
 
			// ask /who to get away states
 
			channel = parameters[1].toLower();
 
			LOG4CXX_INFO(logger, user << "Asking /who for channel " << TO_UTF8(channel));
 
			sendCommand(IrcCommand::createWho(channel));
 
			break;
 
		case 432:
 
			np->handleDisconnected(user, pbnetwork::CONNECTION_ERROR_INVALID_USERNAME, "Erroneous Nickname");
 
			break;
 
		case 433:
 
			for(AutoJoinMap::iterator it = m_autoJoin.begin(); it != m_autoJoin.end(); it++) {
 
				np->handleParticipantChanged(user, TO_UTF8(nickName()), it->second->getChannel() + suffix, pbnetwork::PARTICIPANT_FLAG_CONFLICT);
 
			}
 
			if (suffix.empty()) {
 
				np->handleDisconnected(user, pbnetwork::CONNECTION_ERROR_INVALID_USERNAME, "Nickname is already in use");
 
			}
 
			break;
 
		case 436:
 
			for(AutoJoinMap::iterator it = m_autoJoin.begin(); it != m_autoJoin.end(); it++) {
 
				np->handleParticipantChanged(user, TO_UTF8(nickName()), it->second->getChannel() + suffix, pbnetwork::PARTICIPANT_FLAG_CONFLICT);
 
			}
 
			np->handleDisconnected(user, pbnetwork::CONNECTION_ERROR_INVALID_USERNAME, "Nickname collision KILL");
 
		case 464:
 
			for(AutoJoinMap::iterator it = m_autoJoin.begin(); it != m_autoJoin.end(); it++) {
 
				np->handleParticipantChanged(user, TO_UTF8(nickName()), it->second->getChannel() + suffix, pbnetwork::PARTICIPANT_FLAG_NOT_AUTHORIZED);
 
			}
 
			if (suffix.empty()) {
 
				np->handleDisconnected(user, pbnetwork::CONNECTION_ERROR_INVALID_USERNAME, "Password incorrect");
 
			}
 
		case 321:
 
			m_rooms.clear();
 
			m_names.clear();
 
			break;
 
		case 322:
 
			m_rooms.push_back(TO_UTF8(parameters[1]));
 
			m_names.push_back(TO_UTF8(parameters[1]));
 
			break;
 
		case 323:
 
			np->handleRoomList("", m_rooms, m_names);
 
			break;
 
		default:
 
			break;
 
	}
 

	
 
	if (m->code() >= 400 && m->code() < 500) {
 
			LOG4CXX_INFO(logger, user << ": Error message received: " << message->toData().data());
 
	}
 
}
 

	
 
void MyIrcSession::awayTimeout() {
 
	for(AutoJoinMap::iterator it = m_autoJoin.begin(); it != m_autoJoin.end(); it++) {
 
		if (it->second->shouldAskWho()) {
 
			LOG4CXX_INFO(logger, "The time has come. Asking /who " << it->second->getChannel() << " again to get current away states.");
 
			sendCommand(IrcCommand::createWho(FROM_UTF8(it->second->getChannel())));
 
		}
 
	}
 
}
 

	
 
void MyIrcSession::onMessageReceived(IrcMessage *message) {
 
// 	LOG4CXX_INFO(logger, user << ": " << TO_UTF8(message->toString()));
 
	switch (message->type()) {
 
		case IrcMessage::Join:
 
			on_joined(message);
 
			break;
 
		case IrcMessage::Part:
 
			on_parted(message);
 
			break;
 
		case IrcMessage::Quit:
 
			on_quit(message);
 
			break;
 
		case IrcMessage::Nick:
 
			on_nickChanged(message);
 
			break;
 
		case IrcMessage::Mode:
 
			on_modeChanged(message);
 
			break;
 
		case IrcMessage::Topic:
 
			on_topicChanged(message);
 
			break;
 
		case IrcMessage::Private:
 
			on_messageReceived(message);
 
			break;
 
		case IrcMessage::Numeric:
 
			on_numericMessageReceived(message);
backends/libcommuni/session.h
Show inline comments
 
/*
 
 * Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * This example is free, and not covered by LGPL license. There is no
 
 * restriction applied to their modification, redistribution, using and so on.
 
 * You can study them, modify them, use them in your own program - either
 
 * completely or partially. By using it you may give me some credits in your
 
 * program, but you don't have to.
 
 * Copyright (C) 2013, 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
 
 */
 

	
 
#ifndef SESSION_H
 
#define SESSION_H
 

	
 
#include <IrcSession>
 
#include <transport/networkplugin.h>
 
#include "Swiften/Swiften.h"
 
#include <boost/smart_ptr/make_shared.hpp>
 
#include <QTimer>
 

	
 
using namespace Transport;
 

	
 
class IRCNetworkPlugin;
 

	
 
class MyIrcSession : public IrcSession
 
{
 
    Q_OBJECT
 

	
 
public:
 
	class AutoJoinChannel {
 
		public:
 
			AutoJoinChannel(const std::string &channel = "", const std::string &password = "", int awayCycle = 12) : m_channel(channel), m_password(password),
 
				m_awayCycle(awayCycle), m_currentAwayTick(0) {}
 
			virtual ~AutoJoinChannel() {}
 

	
 
			const std::string &getChannel() { return m_channel; }
 
			const std::string &getPassword() { return m_password; }
 
			bool shouldAskWho() {
 
				if (m_currentAwayTick == m_awayCycle) {
 
					m_currentAwayTick = 0;
 
					return true;
 
				}
 
				m_currentAwayTick++;
 
				return false;
 
			}
 

	
 
		private:
 
			std::string m_channel;
 
			std::string m_password;
 
			int m_awayCycle;
 
			int m_currentAwayTick;
 
	};
 

	
 
	class IRCBuddy {
 
		public:
 
			IRCBuddy(bool op = false, bool away = false) : m_op(op), m_away(away) {};
 

	
 
			void setOp(bool op) { m_op = op; }
 
			bool isOp() { return m_op; }
 
			void setAway(bool away) { m_away = away; }
 
			bool isAway() { return m_away; }
 
		
 
		private:
 
			bool m_op;
 
			bool m_away;
 
	};
 

	
 
	typedef std::map<std::string, boost::shared_ptr<AutoJoinChannel> > AutoJoinMap;
 
	typedef std::map<std::string, std::map<std::string, IRCBuddy> > IRCBuddyMap;
 

	
 
	MyIrcSession(const std::string &user, IRCNetworkPlugin *np, const std::string &suffix = "", QObject* parent = 0);
 
	virtual ~MyIrcSession();
 

	
 
	void addAutoJoinChannel(const std::string &channel, const std::string &password) {
 
		m_autoJoin[channel] = boost::make_shared<AutoJoinChannel>(channel, password, 12 + m_autoJoin.size());
 
	}
 

	
 
	void removeAutoJoinChannel(const std::string &channel) {
 
		m_autoJoin.erase(channel);
 
		removeIRCBuddies(channel);
 
	}
 

	
 
	// We are sending PM message. On XMPP side, user is sending PM using the particular channel,
 
	// for example #room@irc.freenode.org/hanzz. On IRC side, we are forwarding this message
 
	// just to "hanzz". Therefore we have to somewhere store, that message from "hanzz" should
 
	// be mapped to #room@irc.freenode.org/hanzz.
 
	void addPM(const std::string &name, const std::string &room) {
 
		m_pms[name] = room;
 
	}
 

	
 
	void setIdentify(const std::string &identify) {
 
		m_identify = identify;
 
	}
 

	
 
	const std::string  &getIdentify() {
 
		return m_identify;
 
	}
 

	
 
	bool hasIRCBuddy(const std::string &channel, const std::string &name) {
 
		return m_buddies[channel].find(name) != m_buddies[channel].end();
 
	}
 

	
 
	IRCBuddy &getIRCBuddy(const std::string &channel, const std::string &name) {
 
		return m_buddies[channel][name];
 
	}
 

	
 
	void removeIRCBuddy(const std::string &channel, const std::string &name) {
 
		m_buddies[channel].erase(name);
 
	}
 

	
 
	void removeIRCBuddies(const std::string &channel) {
 
		m_buddies.erase(channel);
 
	}
 

	
 
	bool correctNickname(std::string &nickname);
 

	
 
	void on_joined(IrcMessage *message);
 
	void on_parted(IrcMessage *message);
 
	void on_quit(IrcMessage *message);
 
	void on_nickChanged(IrcMessage *message);
 
	void on_modeChanged(IrcMessage *message);
 
	void on_topicChanged(IrcMessage *message);
 
	void on_messageReceived(IrcMessage *message);
 
	void on_numericMessageReceived(IrcMessage *message);
 

	
 
	std::string suffix;
 
	int rooms;
 

	
 
protected Q_SLOTS:
 
	void on_connected();
 
	void on_disconnected();
 
	void on_socketError(QAbstractSocket::SocketError error);
 

	
 
	void onMessageReceived(IrcMessage* message);
 
	void awayTimeout();
 

	
 
protected:
 
	IRCNetworkPlugin *np;
 
	std::string user;
 
	std::string m_identify;
 
	AutoJoinMap m_autoJoin;
 
	std::string m_topicData;
 
	bool m_connected;
 
	std::list<std::string> m_rooms;
 
	std::list<std::string> m_names;
 
	std::map<std::string, std::string> m_pms;
 
	IRCBuddyMap m_buddies;
 
	QTimer *m_awayTimer;
 
};
 

	
 
#endif // SESSION_H
0 comments (0 inline, 0 general)