The Quassel Core now remembers on exit which networks where connected and which channels
[quassel.git] / src / core / server.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by the Quassel IRC Team                         *
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 "server.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 "networkinfo.h"
32
33 #include "ircserverhandler.h"
34 #include "userinputhandler.h"
35 #include "ctcphandler.h"
36
37 Server::Server(UserId uid, NetworkId networkId, QString net, const QVariant &state)
38   : _userId(uid),
39     _networkId(networkId),
40     _ircServerHandler(new IrcServerHandler(this)),
41     _userInputHandler(new UserInputHandler(this)),
42     _ctcpHandler(new CtcpHandler(this)),
43     _networkInfo(new NetworkInfo(networkId, this)),
44     _previousState(state)
45 {
46   connect(networkInfo(), SIGNAL(currentServerSet(const QString &)), this, SLOT(sendPerform()));
47   networkInfo()->setNetworkName(net);
48   networkInfo()->setProxy(coreSession()->signalProxy());
49 }
50
51 Server::~Server() {
52   delete _ircServerHandler;
53   delete _userInputHandler;
54   delete _ctcpHandler;
55 }
56
57 void Server::run() {
58   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
59   connect(&socket, SIGNAL(disconnected()), this, SLOT(quit()));
60   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
61   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
62   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
63   connect(this, SIGNAL(finished()), this, SLOT(threadFinished()));
64
65   exec();
66 }
67
68 void Server::connectToIrc(QString net) {
69   if(net != networkName())
70     return; // not me!
71   
72   CoreSession *sess = coreSession();
73   networkSettings = sess->retrieveSessionData("Networks").toMap()[net].toMap();
74   identity = sess->retrieveSessionData("Identities").toMap()[networkSettings["Identity"].toString()].toMap();
75
76   //FIXME this will result in a pretty fuckup if there are no servers in the list
77   QList<QVariant> servers = networkSettings["Servers"].toList();
78   QString host = servers[0].toMap()["Address"].toString();
79   quint16 port = servers[0].toMap()["Port"].toUInt();
80   displayStatusMsg(QString("Connecting to %1:%2...").arg(host).arg(port));
81   socket.connectToHost(host, port);
82 }
83
84 void Server::sendPerform() {
85   // TODO: reimplement perform List!
86   //// send performlist
87   //QStringList performList = networkSettings["Perform"].toString().split( "\n" );
88   //int count = performList.count();
89   //for(int a = 0; a < count; a++) {
90   //  if(!performList[a].isEmpty() ) {
91   //    userInput(network, "", performList[a]);
92   //  }
93   //}
94
95   // rejoin channels we've been in
96   QStringList chans = _previousState.toStringList();
97   if(chans.count() > 0) {
98     qDebug() << "autojoining" << chans;
99     QString list = chans.join(",");
100     putCmd("join", QStringList(list));
101   }
102   // delete _previousState, we won't need it again
103   _previousState = QVariant();
104 }
105
106 QVariant Server::state() {
107   IrcUser *me = networkInfo()->ircUser(networkInfo()->myNick());
108   if(!me) return QVariant();  // this shouldn't really happen, I guess
109   return me->channels();
110 }
111
112 void Server::disconnectFromIrc(QString net) {
113   if(net != networkName())
114     return; // not me!
115   socket.disconnectFromHost();
116 }
117
118 void Server::socketHasData() {
119   while(socket.canReadLine()) {
120     QByteArray s = socket.readLine().trimmed();
121     ircServerHandler()->handleServerMsg(s);
122   }
123 }
124
125 void Server::socketError( QAbstractSocket::SocketError err ) {
126   //qDebug() << "Socket Error!";
127 }
128
129 void Server::socketConnected() {
130   emit connected(networkId());
131   putRawLine(QString("NICK :%1").arg(identity["NickList"].toStringList()[0]));  // FIXME: try more nicks if error occurs
132   putRawLine(QString("USER %1 8 * :%2").arg(identity["Ident"].toString()).arg(identity["RealName"].toString()));
133 }
134
135 void Server::threadFinished() {
136   // the Socket::disconnected() is connect to this::quit()
137   // so after the event loop is finished we're beeing called
138   // and propagate the disconnect
139   emit disconnected(networkId());
140 }
141
142 void Server::socketStateChanged(QAbstractSocket::SocketState state) {
143   //qDebug() << "Socket state changed: " << state;
144 }
145
146 void Server::userInput(uint netid, QString buf, QString msg) {
147   if(netid != networkId())
148     return; // not me!
149   userInputHandler()->handleUserInput(buf, msg);
150 }
151
152 void Server::putRawLine(QString s) {
153   s += "\r\n";
154   socket.write(s.toAscii());
155 }
156
157 void Server::putCmd(QString cmd, QStringList params, QString prefix) {
158   QString msg;
159   if(!prefix.isEmpty())
160     msg += ":" + prefix + " ";
161   msg += cmd.toUpper();
162   
163   for(int i = 0; i < params.size() - 1; i++) {
164     msg += " " + params[i];
165   }
166   if(!params.isEmpty())
167     msg += " :" + params.last();
168
169   putRawLine(msg);
170 }
171
172
173 uint Server::networkId() const {
174   return _networkId;
175 }
176
177 QString Server::networkName() const {
178   return networkInfo()->networkName();
179 }
180
181 CoreSession *Server::coreSession() const {
182   return Core::session(userId());
183 }
184
185 /* Exception classes for message handling */
186 Server::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
187   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
188 }
189
190 Server::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
191   _msg = QString("Unknown Command: ") + cmd;
192 }