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