The Core Configuration Wizard is back! teH rul!
[quassel.git] / src / client / clientsyncer.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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
21 #include "clientsyncer.h"
22
23 #include "client.h"
24 #include "global.h"
25 #include "identity.h"
26 #include "ircuser.h"
27 #include "ircchannel.h"
28 #include "network.h"
29 #include "signalproxy.h"
30
31
32 ClientSyncer::ClientSyncer(QObject *parent) : QObject(parent) {
33   socket = 0;
34   blockSize = 0;
35
36   connect(Client::signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
37
38 }
39
40 ClientSyncer::~ClientSyncer() {
41
42
43 }
44
45 void ClientSyncer::coreHasData() {
46   QVariant item;
47   while(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
48     emit recvPartialItem(1,1);
49     QVariantMap msg = item.toMap();
50     if(!msg.contains("MsgType")) {
51       // This core is way too old and does not even speak our init protocol...
52       emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
53       disconnectFromCore();
54       return;
55     }
56     if(msg["MsgType"] == "ClientInitAck") {
57       clientInitAck(msg);
58     } else if(msg["MsgType"] == "ClientInitReject") {
59       emit connectionError(msg["Error"].toString());
60       disconnectFromCore();
61       return;
62     } else if(msg["MsgType"] == "CoreSetupAck") {
63       emit coreSetupSuccess();
64     } else if(msg["MsgType"] == "CoreSetupReject") {
65       emit coreSetupFailed(msg["Error"].toString());
66     } else if(msg["MsgType"] == "ClientLoginReject") {
67       emit loginFailed(msg["Error"].toString());
68     } else if(msg["MsgType"] == "ClientLoginAck") {
69       // prevent multiple signal connections
70       disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
71       connect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
72       emit loginSuccess();
73     } else if(msg["MsgType"] == "SessionInit") {
74       sessionStateReceived(msg["SessionState"].toMap());
75     } else {
76       emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
77       disconnectFromCore();
78       return;
79     }
80     /*
81     if (!msg["StartWizard"].toBool()) {
82     recvCoreState(msg["Reply"]);
83   } else {
84     qWarning("Core not configured!");
85     qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
86     emit showConfigWizard(msg);
87   }
88     blockSize = 0;
89     return;
90   }
91     */
92   }
93   if(blockSize > 0) {
94     emit recvPartialItem(socket->bytesAvailable(), blockSize);
95   }
96 }
97
98 void ClientSyncer::coreSocketError(QAbstractSocket::SocketError) {
99   emit connectionError(socket->errorString());
100   socket->deleteLater();
101 }
102
103 void ClientSyncer::disconnectFromCore() {
104   if(socket) socket->close();
105 }
106
107 void ClientSyncer::connectToCore(const QVariantMap &conn) {
108   // TODO implement SSL
109   coreConnectionInfo = conn;
110   //if(isConnected()) {
111   //  emit coreConnectionError(tr("Already connected to Core!"));
112   //  return;
113   // }
114   if(socket != 0) {
115     socket->deleteLater();
116     socket = 0;
117   }
118   if(conn["Host"].toString().isEmpty()) {
119     emit connectionError(tr("Internal connections not yet supported."));
120     return; // FIXME implement internal connections
121     //clientMode = LocalCore;
122     socket = new QBuffer(this);
123     connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
124     socket->open(QIODevice::ReadWrite);
125     //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
126     //syncToCore(state);
127     coreSocketConnected();
128   } else {
129     //clientMode = RemoteCore;
130     //emit coreConnectionMsg(tr("Connecting..."));
131     Q_ASSERT(!socket);
132     QTcpSocket *sock = new QTcpSocket(Client::instance());
133     socket = sock;
134     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
135     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
136     connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
137     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
138     connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(socketStateChanged(QAbstractSocket::SocketState)));
139     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
140   }
141 }
142
143 void ClientSyncer::coreSocketConnected() {
144   //connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
145   // Phase One: Send client info and wait for core info
146
147   //emit coreConnectionMsg(tr("Synchronizing to core..."));
148   QVariantMap clientInit;
149   clientInit["MsgType"] = "ClientInit";
150   clientInit["ClientVersion"] = Global::quasselVersion;
151   clientInit["ClientDate"] = Global::quasselDate;
152   clientInit["ClientBuild"] = Global::quasselBuild; // this is a minimum, since we probably won't update for every commit
153   clientInit["UseSsl"] = false;  // FIXME implement SSL
154   SignalProxy::writeDataToDevice(socket, clientInit);
155 }
156
157 void ClientSyncer::coreSocketDisconnected() {
158   emit socketDisconnected();
159   Client::instance()->disconnectFromCore();
160
161   // FIXME handle disconnects gracefully in here as well!
162
163   coreConnectionInfo.clear();
164   netsToSync.clear();
165   channelsToSync.clear();
166   usersToSync.clear();
167   blockSize = 0;
168   //restartPhaseNull();
169 }
170
171 void ClientSyncer::clientInitAck(const QVariantMap &msg) {
172   // Core has accepted our version info and sent its own. Let's see if we accept it as well...
173   if(msg["CoreBuild"].toUInt() < Global::coreBuildNeeded) {
174     emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
175         "Need at least a Core Version %1 (Build >= %2) to connect.").arg(Global::quasselVersion).arg(Global::quasselBuild));
176     disconnectFromCore();
177     return;
178   }
179   emit connectionMsg(msg["CoreInfo"].toString());
180   if(!msg["Configured"].toBool()) {
181     // start wizard
182     emit startCoreSetup(msg["StorageBackends"].toList());
183   } else if(msg["LoginEnabled"].toBool()) {
184     emit startLogin();
185   }
186 }
187
188 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
189   QVariantMap setup;
190   setup["MsgType"] = "CoreSetupData";
191   setup["SetupData"] = setupData;
192   SignalProxy::writeDataToDevice(socket, setup);
193 }
194
195 void ClientSyncer::loginToCore(const QString &user, const QString &passwd) {
196   emit connectionMsg(tr("Logging in..."));
197   QVariantMap clientLogin;
198   clientLogin["MsgType"] = "ClientLogin";
199   clientLogin["User"] = user;
200   clientLogin["Password"] = passwd;
201   SignalProxy::writeDataToDevice(socket, clientLogin);
202 }
203
204 void ClientSyncer::sessionStateReceived(const QVariantMap &state) {
205   emit sessionProgress(1, 1);
206   disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
207   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
208   //Client::signalProxy()->addPeer(socket);
209   Client::instance()->setConnectedToCore(socket, coreConnectionInfo["AccountId"].value<AccountId>());
210   syncToCore(state);
211 }
212
213 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
214
215   // create identities
216   foreach(QVariant vid, sessionState["Identities"].toList()) {
217     Client::instance()->coreIdentityCreated(vid.value<Identity>());
218   }
219
220   // create buffers
221   // FIXME: get rid of this crap
222   QVariantList bufferinfos = sessionState["BufferInfos"].toList();
223   foreach(QVariant vinfo, bufferinfos) Client::buffer(vinfo.value<BufferInfo>());  // create Buffers and BufferItems
224
225   QVariantList networkids = sessionState["NetworkIds"].toList();
226
227   // prepare sync progress thingys... FIXME: Care about removal of networks
228   numNetsToSync = networkids.count();
229   numChannelsToSync = 0; //sessionState["IrcChannelCount"].toUInt();
230   numUsersToSync = 0; // sessionState["IrcUserCount"].toUInt(); qDebug() << numUsersToSync;
231   emit networksProgress(0, numNetsToSync);
232   emit channelsProgress(0, numChannelsToSync);
233   emit ircUsersProgress(0, numUsersToSync);
234
235   // create network objects
236   foreach(QVariant networkid, networkids) {
237     NetworkId netid = networkid.value<NetworkId>();
238     Network *net = new Network(netid, Client::instance());
239     netsToSync.insert(net);
240     connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
241     connect(net, SIGNAL(ircUserInitDone(IrcUser *)), this, SLOT(ircUserInitDone(IrcUser *)));
242     connect(net, SIGNAL(ircUserAdded(IrcUser *)), this, SLOT(ircUserAdded(IrcUser *)));
243     connect(net, SIGNAL(ircUserRemoved(QObject *)), this, SLOT(ircUserRemoved(QObject *)));
244     connect(net, SIGNAL(ircChannelInitDone(IrcChannel *)), this, SLOT(ircChannelInitDone(IrcChannel *)));
245     connect(net, SIGNAL(ircChannelAdded(IrcChannel *)), this, SLOT(ircChannelAdded(IrcChannel *)));
246     connect(net, SIGNAL(ircChannelRemoved(QObject *)), this, SLOT(ircChannelRemoved(QObject *)));
247     Client::addNetwork(net);
248   }
249   checkSyncState();
250 }
251
252 void ClientSyncer::networkInitDone() {
253   netsToSync.remove(sender());
254   emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
255   checkSyncState();
256 }
257
258 void ClientSyncer::ircChannelInitDone(IrcChannel *chan) {
259   channelsToSync.remove(chan);
260   emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
261   checkSyncState();
262 }
263
264 void ClientSyncer::ircChannelAdded(IrcChannel *chan) {
265   if(!chan->isInitialized()) {
266     channelsToSync.insert(chan);
267     numChannelsToSync++;
268     emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
269     checkSyncState();
270   }
271 }
272
273 void ClientSyncer::ircChannelRemoved(QObject *chan) {
274   if(channelsToSync.contains(chan)) {
275     numChannelsToSync--;
276     channelsToSync.remove(chan);
277     emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
278     checkSyncState();
279   }
280 }
281
282 void ClientSyncer::ircUserInitDone(IrcUser *user) {
283   usersToSync.remove(user);
284   emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
285   checkSyncState();
286 }
287
288 void ClientSyncer::ircUserAdded(IrcUser *user) {
289   if(!user->isInitialized()) {
290     usersToSync.insert(user);
291     numUsersToSync++;
292     emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
293     checkSyncState();
294   }
295 }
296
297 void ClientSyncer::ircUserRemoved(QObject *user) {
298   if(usersToSync.contains(user)) {
299     numUsersToSync--;
300     usersToSync.remove(user);
301     emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
302     checkSyncState();
303   }
304 }
305
306 void ClientSyncer::checkSyncState() {
307   if(usersToSync.count() + channelsToSync.count() + netsToSync.count() == 0) {
308     // done syncing!
309     /*
310     qDebug() << "done";
311     foreach(Network *net, _networks.values()) {
312       //disconnect(net, 0, this, SLOT(networkInitDone()));
313       //disconnect(net, 0, this, SLOT(ircUserInitDone(IrcUser *)));
314       //disconnect(net, 0, this, SLOT(ircUserAdded(IrcUser *)));
315       //disconnect(net, 0, this, SLOT(ircUserRemoved(QObject *)));
316       //disconnect(net, 0, this, SLOT(ircChannelInitDone(IrcChannel *)));
317       //disconnect(net, 0, this, SLOT(ircChannelAdded(IrcChannel *)));
318       //disconnect(net, 0, this, SLOT(ircChannelRemoved(QObject *)));
319       qDebug() << "disconnecting";
320       disconnect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
321       disconnect(net, SIGNAL(ircUserInitDone(IrcUser *)), this, SLOT(ircUserInitDone(IrcUser *)));
322       disconnect(net, SIGNAL(ircUserAdded(IrcUser *)), this, SLOT(ircUserAdded(IrcUser *)));
323       disconnect(net, SIGNAL(ircUserRemoved(QObject *)), this, SLOT(ircUserRemoved(QObject *)));
324       disconnect(net, SIGNAL(ircChannelInitDone(IrcChannel *)), this, SLOT(ircChannelInitDone(IrcChannel *)));
325       disconnect(net, SIGNAL(ircChannelAdded(IrcChannel *)), this, SLOT(ircChannelAdded(IrcChannel *)));
326       disconnect(net, SIGNAL(ircChannelRemoved(QObject *)), this, SLOT(ircChannelRemoved(QObject *)));
327     }
328     */
329
330     Client::instance()->setSyncedToCore();
331     emit syncFinished();
332     //emit connected();
333     //emit connectionStateChanged(true);
334
335   }
336 }
337