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