added missing queries
[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 "ircchannel.h"
31 #include "ircuser.h"
32 #include "network.h"
33 #include "identity.h"
34
35 #include "ircserverhandler.h"
36 #include "userinputhandler.h"
37 #include "ctcphandler.h"
38
39 NetworkConnection::NetworkConnection(Network *network, CoreSession *session, const QVariant &state) : QObject(network),
40     _connectionState(Network::Disconnected),
41     _network(network),
42     _coreSession(session),
43     _ircServerHandler(new IrcServerHandler(this)),
44     _userInputHandler(new UserInputHandler(this)),
45     _ctcpHandler(new CtcpHandler(this)),
46     _previousState(state)
47 {
48   connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
49
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()));
55
56 }
57
58 NetworkConnection::~NetworkConnection() {
59   disconnectFromIrc();
60   delete _ircServerHandler;
61   delete _userInputHandler;
62   delete _ctcpHandler;
63 }
64
65 bool NetworkConnection::isConnected() const {
66   // return socket.state() == QAbstractSocket::ConnectedState;
67   return connectionState() == Network::Initialized;
68 }
69
70 Network::ConnectionState NetworkConnection::connectionState() const {
71   return _connectionState;
72 }
73
74 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
75   _connectionState = state;
76   network()->setConnectionState(state);
77   emit connectionStateChanged(state);
78 }
79
80 NetworkId NetworkConnection::networkId() const {
81   return network()->networkId();
82 }
83
84 QString NetworkConnection::networkName() const {
85   return network()->networkName();
86 }
87
88 Identity *NetworkConnection::identity() const {
89   return coreSession()->identity(network()->identity());
90 }
91
92 Network *NetworkConnection::network() const {
93   return _network;
94 }
95
96 CoreSession *NetworkConnection::coreSession() const {
97   return _coreSession;
98 }
99
100 IrcServerHandler *NetworkConnection::ircServerHandler() const {
101   return _ircServerHandler;
102 }
103
104 UserInputHandler *NetworkConnection::userInputHandler() const {
105   return _userInputHandler;
106 }
107
108 CtcpHandler *NetworkConnection::ctcpHandler() const {
109   return _ctcpHandler;
110 }
111
112 QString NetworkConnection::serverDecode(const QByteArray &string) const {
113   return network()->decodeServerString(string);
114 }
115
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);
120   }
121   return network()->decodeString(string);
122 }
123
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);
128 }
129
130 QByteArray NetworkConnection::serverEncode(const QString &string) const {
131   return network()->encodeServerString(string);
132 }
133
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);
138   }
139   return network()->encodeString(string);
140 }
141
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);
146 }
147
148
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!";
154     return;
155   }
156   if(!identity) {
157     qWarning() << "Invalid identity configures, ignoring connect request!";
158     return;
159   }
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);
165 }
166
167 void NetworkConnection::networkInitialized(const QString &currentServer) {
168   if(currentServer.isEmpty()) return;
169
170   sendPerform();
171
172     // rejoin channels we've been in
173   QStringList chans = _previousState.toStringList();
174   if(chans.count() > 0) {
175     qDebug() << "autojoining" << chans;
176     QVariantList list;
177     list << serverEncode(chans.join(",")); // TODO add channel passwords
178     putCmd("JOIN", list);  // FIXME check for 512 byte limit!
179   }
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());
186 }
187
188 void NetworkConnection::sendPerform() {
189   BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
190   // do auto identify
191   if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
192     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
193   }
194   // send perform list
195   foreach(QString line, network()->perform()) {
196     if(!line.isEmpty()) userInput(statusBuf, line);
197   }
198 }
199
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();
204 }
205
206 void NetworkConnection::disconnectFromIrc() {
207   if(socket.state() < QAbstractSocket::ConnectedState) {
208     setConnectionState(Network::Disconnected);
209     socketDisconnected();
210   } else socket.disconnectFromHost();
211 }
212
213 void NetworkConnection::socketHasData() {
214   while(socket.canReadLine()) {
215     QByteArray s = socket.readLine().trimmed();
216     ircServerHandler()->handleServerMsg(s);
217   }
218 }
219
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());
225 }
226
227 void NetworkConnection::socketConnected() {
228   //emit connected(networkId());  initialize first!
229   Identity *identity = coreSession()->identity(network()->identity());
230   if(!identity) {
231     qWarning() << "Identity invalid!";
232     disconnectFromIrc();
233     return;
234   }
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())));
237 }
238
239 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
240   Network::ConnectionState state;
241   switch(socketState) {
242     case QAbstractSocket::UnconnectedState:
243       state = Network::Disconnected;
244       break;
245     case QAbstractSocket::HostLookupState:
246     case QAbstractSocket::ConnectingState:
247       state = Network::Connecting;
248       break;
249     case QAbstractSocket::ConnectedState:
250       state = Network::Initializing;
251       break;
252     case QAbstractSocket::ClosingState:
253       state = Network::Disconnecting;
254       break;
255     default:
256       state = Network::Disconnected;
257   }
258   setConnectionState(state);
259 }
260
261 void NetworkConnection::socketDisconnected() {
262   network()->setConnected(false);
263   emit disconnected(networkId());
264 }
265
266 // FIXME switch to BufferId
267 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
268   userInputHandler()->handleUserInput(buf, msg);
269 }
270
271 void NetworkConnection::putRawLine(QByteArray s) {
272   s += "\r\n";
273   socket.write(s);
274 }
275
276 void NetworkConnection::putCmd(const QString &cmd, const QVariantList &params, const QByteArray &prefix) {
277   QByteArray msg;
278   if(!prefix.isEmpty())
279     msg += ":" + prefix + " ";
280   msg += cmd.toUpper().toAscii();
281
282   for(int i = 0; i < params.size() - 1; i++) {
283     msg += " " + params[i].toByteArray();
284   }
285   if(!params.isEmpty())
286     msg += " :" + params.last().toByteArray();
287
288   putRawLine(msg);
289 }
290
291 /* Exception classes for message handling */
292 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
293   Q_UNUSED(prefix);
294   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
295 }
296
297 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
298   Q_UNUSED(prefix);
299   _msg = QString("Unknown Command: ") + cmd + params.join(" ");
300 }