a8b8e1573e2e0900eeda0f4ebe22c50098174e05
[quassel.git] / src / core / networkconnection.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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"
21
22 #include <QMetaObject>
23 #include <QMetaMethod>
24 #include <QDateTime>
25
26 #include "util.h"
27 #include "core.h"
28 #include "coresession.h"
29
30 #include "ircuser.h"
31 #include "network.h"
32 #include "identity.h"
33
34 #include "ircserverhandler.h"
35 #include "userinputhandler.h"
36 #include "ctcphandler.h"
37
38 NetworkConnection::NetworkConnection(Network *network, CoreSession *session, const QVariant &state) : QObject(network),
39     _connectionState(Network::Disconnected),
40     _network(network),
41     _coreSession(session),
42     _ircServerHandler(new IrcServerHandler(this)),
43     _userInputHandler(new UserInputHandler(this)),
44     _ctcpHandler(new CtcpHandler(this)),
45     _previousState(state)
46 {
47   connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized()));
48
49   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
50   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
51   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
52   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
53   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
54
55 }
56
57 NetworkConnection::~NetworkConnection() {
58   disconnectFromIrc();
59   delete _ircServerHandler;
60   delete _userInputHandler;
61   delete _ctcpHandler;
62 }
63
64 bool NetworkConnection::isConnected() const {
65   // return socket.state() == QAbstractSocket::ConnectedState;
66   return connectionState() == Network::Initialized;
67 }
68
69 Network::ConnectionState NetworkConnection::connectionState() const {
70   return _connectionState;
71 }
72
73 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
74   _connectionState = state;
75   network()->setConnectionState(state);
76   emit connectionStateChanged(state);
77 }
78
79 NetworkId NetworkConnection::networkId() const {
80   return network()->networkId();
81 }
82
83 QString NetworkConnection::networkName() const {
84   return network()->networkName();
85 }
86
87 Network *NetworkConnection::network() const {
88   return _network;
89 }
90
91 CoreSession *NetworkConnection::coreSession() const {
92   return _coreSession;
93 }
94
95 IrcServerHandler *NetworkConnection::ircServerHandler() const {
96   return _ircServerHandler;
97 }
98
99 UserInputHandler *NetworkConnection::userInputHandler() const {
100   return _userInputHandler;
101 }
102
103 CtcpHandler *NetworkConnection::ctcpHandler() const {
104   return _ctcpHandler;
105 }
106
107 QString NetworkConnection::serverDecode(const QByteArray &string) const {
108   return network()->decodeString(string);
109 }
110
111 QString NetworkConnection::bufferDecode(const QString &bufferName, const QByteArray &string) const {
112   Q_UNUSED(bufferName);
113   // TODO: Implement buffer-specific encodings
114   return network()->decodeString(string);
115 }
116
117 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
118   IrcUser *user = network()->ircUser(userNick);
119   if(user) return user->decodeString(string);
120   return network()->decodeString(string);
121 }
122
123 QByteArray NetworkConnection::serverEncode(const QString &string) const {
124   return network()->encodeString(string);
125 }
126
127 QByteArray NetworkConnection::bufferEncode(const QString &bufferName, const QString &string) const {
128   Q_UNUSED(bufferName);
129   // TODO: Implement buffer-specific encodings
130   return network()->encodeString(string);
131 }
132
133 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
134   IrcUser *user = network()->ircUser(userNick);
135   if(user) return user->encodeString(string);
136   return network()->encodeString(string);
137 }
138
139
140 void NetworkConnection::connectToIrc() {
141   QVariantList serverList = network()->serverList();
142   Identity *identity = coreSession()->identity(network()->identity());
143   if(!serverList.count()) {
144     qWarning() << "Server list empty, ignoring connect request!";
145     return;
146   }
147   if(!identity) {
148     qWarning() << "Invalid identity configures, ignoring connect request!";
149     return;
150   }
151   // TODO implement cycling / random servers
152   QString host = serverList[0].toMap()["Host"].toString();
153   quint16 port = serverList[0].toMap()["Port"].toUInt();
154   displayStatusMsg(QString("Connecting to %1:%2...").arg(host).arg(port));
155   socket.connectToHost(host, port);
156 }
157
158 void NetworkConnection::networkInitialized() {
159   sendPerform();
160
161     // rejoin channels we've been in
162   QStringList chans = _previousState.toStringList();
163   if(chans.count() > 0) {
164     qDebug() << "autojoining" << chans;
165     QString list = chans.join(",");
166     putCmd("join", QStringList(list));  // FIXME check for 512 byte limit!
167   }
168   // delete _previousState, we won't need it again
169   _previousState = QVariant();
170   // now we are initialized
171   setConnectionState(Network::Initialized);
172   network()->setConnected(true);
173   emit connected(networkId());
174 }
175
176 void NetworkConnection::sendPerform() {
177   foreach(QString line, network()->perform()) {
178     if(!line.isEmpty()) userInput(Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer), line);
179   }
180 }
181
182 QVariant NetworkConnection::state() const {
183   IrcUser *me = network()->ircUser(network()->myNick());
184   if(!me) return QVariant();  // this shouldn't really happen, I guess
185   return me->channels();
186 }
187
188 void NetworkConnection::disconnectFromIrc() {
189   socket.disconnectFromHost();
190 }
191
192 void NetworkConnection::socketHasData() {
193   while(socket.canReadLine()) {
194     QByteArray s = socket.readLine().trimmed();
195     ircServerHandler()->handleServerMsg(s);
196   }
197 }
198
199 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
200   qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
201   emit connectionError(socket.errorString());
202   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
203   network()->emitConnectionError(socket.errorString());
204 }
205
206 void NetworkConnection::socketConnected() {
207   //emit connected(networkId());  initialize first!
208   Identity *identity = coreSession()->identity(network()->identity());
209   if(!identity) {
210     qWarning() << "Identity invalid!";
211     disconnectFromIrc();
212     return;
213   }
214   putRawLine(QString("NICK :%1").arg(identity->nicks()[0]));  // FIXME: try more nicks if error occurs
215   putRawLine(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName()));
216 }
217
218 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
219   Network::ConnectionState state;
220   switch(socketState) {
221     case QAbstractSocket::UnconnectedState:
222       state = Network::Disconnected;
223       break;
224     case QAbstractSocket::HostLookupState:
225     case QAbstractSocket::ConnectingState:
226       state = Network::Connecting;
227       break;
228     case QAbstractSocket::ConnectedState:
229       state = Network::Initializing;
230       break;
231     case QAbstractSocket::ClosingState:
232       state = Network::Disconnecting;
233       break;
234     default:
235       state = Network::Disconnected;
236   }
237   setConnectionState(state);
238 }
239
240 void NetworkConnection::socketDisconnected() {
241   network()->setConnected(false);
242   emit disconnected(networkId());
243 }
244
245 // FIXME switch to BufferId
246 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
247   userInputHandler()->handleUserInput(buf, msg);
248 }
249
250 void NetworkConnection::putRawLine(QString s) {
251   s += "\r\n";
252   socket.write(s.toAscii());
253 }
254
255 void NetworkConnection::putCmd(QString cmd, QStringList params, QString prefix) {
256   QString msg;
257   if(!prefix.isEmpty())
258     msg += ":" + prefix + " ";
259   msg += cmd.toUpper();
260   
261   for(int i = 0; i < params.size() - 1; i++) {
262     msg += " " + params[i];
263   }
264   if(!params.isEmpty())
265     msg += " :" + params.last();
266
267   putRawLine(msg);
268 }
269
270 /* Exception classes for message handling */
271 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
272   Q_UNUSED(prefix);
273   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
274 }
275
276 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
277   Q_UNUSED(prefix);
278   _msg = QString("Unknown Command: ") + cmd + params.join(" ");
279 }