1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
20 #include "networkconnection.h"
22 #include <QMetaObject>
23 #include <QMetaMethod>
28 #include "coresession.h"
30 #include "ircchannel.h"
35 #include "ircserverhandler.h"
36 #include "userinputhandler.h"
37 #include "ctcphandler.h"
39 NetworkConnection::NetworkConnection(Network *network, CoreSession *session, const QVariant &state) : QObject(network),
40 _connectionState(Network::Disconnected),
42 _coreSession(session),
43 _ircServerHandler(new IrcServerHandler(this)),
44 _userInputHandler(new UserInputHandler(this)),
45 _ctcpHandler(new CtcpHandler(this)),
48 connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
50 connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
51 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
52 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
53 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
54 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
58 NetworkConnection::~NetworkConnection() {
60 delete _ircServerHandler;
61 delete _userInputHandler;
65 bool NetworkConnection::isConnected() const {
66 // return socket.state() == QAbstractSocket::ConnectedState;
67 return connectionState() == Network::Initialized;
70 Network::ConnectionState NetworkConnection::connectionState() const {
71 return _connectionState;
74 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
75 _connectionState = state;
76 network()->setConnectionState(state);
77 emit connectionStateChanged(state);
80 NetworkId NetworkConnection::networkId() const {
81 return network()->networkId();
84 QString NetworkConnection::networkName() const {
85 return network()->networkName();
88 Identity *NetworkConnection::identity() const {
89 return coreSession()->identity(network()->identity());
92 Network *NetworkConnection::network() const {
96 CoreSession *NetworkConnection::coreSession() const {
100 IrcServerHandler *NetworkConnection::ircServerHandler() const {
101 return _ircServerHandler;
104 UserInputHandler *NetworkConnection::userInputHandler() const {
105 return _userInputHandler;
108 CtcpHandler *NetworkConnection::ctcpHandler() const {
112 QString NetworkConnection::serverDecode(const QByteArray &string) const {
113 return network()->decodeServerString(string);
116 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
117 if(!bufferName.isEmpty()) {
118 IrcChannel *channel = network()->ircChannel(bufferName);
119 if(channel) return channel->decodeString(string);
121 return network()->decodeString(string);
124 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
125 IrcUser *user = network()->ircUser(userNick);
126 if(user) return user->decodeString(string);
127 return network()->decodeString(string);
130 QByteArray NetworkConnection::serverEncode(const QString &string) const {
131 return network()->encodeServerString(string);
134 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
135 if(!bufferName.isEmpty()) {
136 IrcChannel *channel = network()->ircChannel(bufferName);
137 if(channel) return channel->encodeString(string);
139 return network()->encodeString(string);
142 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
143 IrcUser *user = network()->ircUser(userNick);
144 if(user) return user->encodeString(string);
145 return network()->encodeString(string);
149 void NetworkConnection::connectToIrc() {
150 QVariantList serverList = network()->serverList();
151 Identity *identity = coreSession()->identity(network()->identity());
152 if(!serverList.count()) {
153 qWarning() << "Server list empty, ignoring connect request!";
157 qWarning() << "Invalid identity configures, ignoring connect request!";
160 // TODO implement cycling / random servers
161 QString host = serverList[0].toMap()["Host"].toString();
162 quint16 port = serverList[0].toMap()["Port"].toUInt();
163 displayStatusMsg(QString("Connecting to %1:%2...").arg(host).arg(port));
164 socket.connectToHost(host, port);
167 void NetworkConnection::networkInitialized(const QString ¤tServer) {
168 if(currentServer.isEmpty()) return;
172 // rejoin channels we've been in
173 QStringList chans = _previousState.toStringList();
174 if(chans.count() > 0) {
175 qDebug() << "autojoining" << chans;
177 list << serverEncode(chans.join(",")); // TODO add channel passwords
178 putCmd("JOIN", list); // FIXME check for 512 byte limit!
180 // delete _previousState, we won't need it again
181 _previousState = QVariant();
182 // now we are initialized
183 setConnectionState(Network::Initialized);
184 network()->setConnected(true);
185 emit connected(networkId());
188 void NetworkConnection::sendPerform() {
189 BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
191 if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
192 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
195 foreach(QString line, network()->perform()) {
196 if(!line.isEmpty()) userInput(statusBuf, line);
200 QVariant NetworkConnection::state() const {
201 IrcUser *me = network()->ircUser(network()->myNick());
202 if(!me) return QVariant(); // this shouldn't really happen, I guess
203 return me->channels();
206 void NetworkConnection::disconnectFromIrc() {
207 if(socket.state() < QAbstractSocket::ConnectedState) {
208 setConnectionState(Network::Disconnected);
209 socketDisconnected();
210 } else socket.disconnectFromHost();
213 void NetworkConnection::socketHasData() {
214 while(socket.canReadLine()) {
215 QByteArray s = socket.readLine().trimmed();
216 ircServerHandler()->handleServerMsg(s);
220 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
221 qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
222 emit connectionError(socket.errorString());
223 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
224 network()->emitConnectionError(socket.errorString());
227 void NetworkConnection::socketConnected() {
228 //emit connected(networkId()); initialize first!
229 Identity *identity = coreSession()->identity(network()->identity());
231 qWarning() << "Identity invalid!";
235 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0]))); // FIXME: try more nicks if error occurs
236 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
239 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
240 Network::ConnectionState state;
241 switch(socketState) {
242 case QAbstractSocket::UnconnectedState:
243 state = Network::Disconnected;
245 case QAbstractSocket::HostLookupState:
246 case QAbstractSocket::ConnectingState:
247 state = Network::Connecting;
249 case QAbstractSocket::ConnectedState:
250 state = Network::Initializing;
252 case QAbstractSocket::ClosingState:
253 state = Network::Disconnecting;
256 state = Network::Disconnected;
258 setConnectionState(state);
261 void NetworkConnection::socketDisconnected() {
262 network()->setConnected(false);
263 emit disconnected(networkId());
266 // FIXME switch to BufferId
267 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
268 userInputHandler()->handleUserInput(buf, msg);
271 void NetworkConnection::putRawLine(QByteArray s) {
276 void NetworkConnection::putCmd(const QString &cmd, const QVariantList ¶ms, const QByteArray &prefix) {
278 if(!prefix.isEmpty())
279 msg += ":" + prefix + " ";
280 msg += cmd.toUpper().toAscii();
282 for(int i = 0; i < params.size() - 1; i++) {
283 msg += " " + params[i].toByteArray();
285 if(!params.isEmpty())
286 msg += " :" + params.last().toByteArray();
291 /* Exception classes for message handling */
292 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
294 _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
297 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
299 _msg = QString("Unknown Command: ") + cmd + params.join(" ");