ab543118b84e1a37cfec9d5febc2a0fbc49bc659
[quassel.git] / src / client / client.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
21 #include "client.h"
22
23 #include "bufferinfo.h"
24 #include "global.h"
25 #include "identity.h"
26 #include "ircchannel.h"
27 #include "ircuser.h"
28 #include "message.h"
29 #include "networkinfo.h"
30 #include "networkmodel.h"
31 #include "quasselui.h"
32 #include "signalproxy.h"
33 #include "util.h"
34
35 QPointer<Client> Client::instanceptr = 0;
36
37 /*** Initialization/destruction ***/
38
39 Client *Client::instance() {
40   if(!instanceptr)
41     instanceptr = new Client();
42   return instanceptr;
43 }
44
45 void Client::destroy() {
46   delete instanceptr;
47 }
48
49 void Client::init(AbstractUi *ui) {
50   instance()->mainUi = ui;
51   instance()->init();
52 }
53
54 Client::Client(QObject *parent)
55     : QObject(parent),
56     socket(0),
57     _signalProxy(new SignalProxy(SignalProxy::Client, this)),
58     mainUi(0),
59     _networkModel(0),
60     connectedToCore(false)
61 {
62
63 }
64
65 Client::~Client() {
66
67 }
68
69 void Client::init() {
70   blockSize = 0;
71
72   _networkModel = new NetworkModel(this);
73
74   connect(this, SIGNAL(bufferSelected(Buffer *)),
75           _networkModel, SLOT(selectBuffer(Buffer *)));
76   connect(this, SIGNAL(bufferUpdated(Buffer *)),
77           _networkModel, SLOT(bufferUpdated(Buffer *)));
78   connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)),
79           _networkModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
80
81   SignalProxy *p = signalProxy();
82   p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)),
83                   SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
84   p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)),
85                 this, SLOT(recvSessionData(const QString &, const QVariant &)));
86   p->attachSlot(SIGNAL(coreState(const QVariant &)),
87                 this, SLOT(recvCoreState(const QVariant &)));
88   p->attachSlot(SIGNAL(networkConnected(uint)),
89                 this, SLOT(networkConnected(uint)));
90   p->attachSlot(SIGNAL(networkDisconnected(uint)),
91                 this, SLOT(networkDisconnected(uint)));
92   p->attachSlot(SIGNAL(displayMsg(const Message &)),
93                 this, SLOT(recvMessage(const Message &)));
94   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
95                 this, SLOT(recvStatusMsg(QString, QString)));
96
97
98   p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
99   p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
100   p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
101   p->attachSignal(this, SIGNAL(requestNetworkStates()));
102
103   p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &)), SIGNAL(createIdentity(const Identity &)));
104   p->attachSignal(this, SIGNAL(requestUpdateIdentity(const Identity &)), SIGNAL(updateIdentity(const Identity &)));
105   p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
106   p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
107   p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
108
109   connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
110   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
111   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
112   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
113
114   layoutTimer = new QTimer(this);
115   layoutTimer->setInterval(0);
116   layoutTimer->setSingleShot(false);
117   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
118
119 }
120
121 /*** public static methods ***/
122
123
124 QList<NetworkInfo *> Client::networkInfos() {
125   return instance()->_networkInfo.values();
126 }
127
128 NetworkInfo *Client::networkInfo(uint networkid) {
129   if(instance()->_networkInfo.contains(networkid))
130     return instance()->_networkInfo[networkid];
131   else
132     return 0;
133 }
134
135 QList<BufferInfo> Client::allBufferInfos() {
136   QList<BufferInfo> bufferids;
137   foreach(Buffer *buffer, buffers()) {
138     bufferids << buffer->bufferInfo();
139   }
140   return bufferids;
141 }
142
143 QList<Buffer *> Client::buffers() {
144   return instance()->_buffers.values();
145 }
146
147 Buffer *Client::buffer(uint bufferUid) {
148   if(instance()->_buffers.contains(bufferUid))
149     return instance()->_buffers[bufferUid];
150   else
151     return 0;
152 }
153
154 Buffer *Client::buffer(BufferInfo id) {
155   Buffer *buff = buffer(id.uid());
156
157   if(!buff) {
158     Client *client = Client::instance();
159     buff = new Buffer(id, client);
160
161     connect(buff, SIGNAL(userInput(BufferInfo, QString)),
162             client, SLOT(userInput(BufferInfo, QString)));
163     connect(buff, SIGNAL(bufferUpdated(Buffer *)),
164             client, SIGNAL(bufferUpdated(Buffer *)));
165     connect(buff, SIGNAL(destroyed()),
166             client, SLOT(bufferDestroyed()));
167     client->_buffers[id.uid()] = buff;
168     emit client->bufferUpdated(buff);
169   }
170   Q_ASSERT(buff);
171   return buff;
172 }
173
174 // FIXME switch to netids!
175 // WHEN IS THIS NEEDED ANYHOW!?
176 // ...only for finding the Buffer for a channel, I guess...
177 BufferInfo Client::bufferInfo(QString net, QString buf) {
178   foreach(Buffer *buffer_, buffers()) {
179     BufferInfo bufferInfo = buffer_->bufferInfo();
180     if(!bufferInfo.network().compare(net, Qt::CaseInsensitive) && !bufferInfo.buffer().compare(buf, Qt::CaseInsensitive))
181       return bufferInfo;
182   }
183   Q_ASSERT(false);  // should never happen!
184   return BufferInfo();
185 }
186
187 BufferInfo Client::statusBufferInfo(QString net) {
188   return bufferInfo(net, "");
189 }
190
191 NetworkModel *Client::networkModel() {
192   return instance()->_networkModel;
193 }
194
195 SignalProxy *Client::signalProxy() {
196   return instance()->_signalProxy;
197 }
198
199
200 /*** Identity handling ***/
201
202 QList<IdentityId> Client::identityIds() {
203   return instance()->_identities.keys();
204 }
205
206 const Identity * Client::identity(IdentityId id) {
207   if(instance()->_identities.contains(id)) return instance()->_identities[id];
208   else return 0;
209 }
210
211
212 void Client::createIdentity(const Identity &id) {
213   emit instance()->requestCreateIdentity(id);
214 }
215
216 void Client::updateIdentity(const Identity &id) {
217   emit instance()->requestUpdateIdentity(id);
218 }
219
220 void Client::removeIdentity(IdentityId id) {
221   emit instance()->requestRemoveIdentity(id);
222 }
223
224 void Client::coreIdentityCreated(const Identity &other) {
225   if(!_identities.contains(other.id())) {
226     Identity *identity = new Identity(other, this);
227     _identities[other.id()] = identity;
228     identity->setInitialized();
229     signalProxy()->synchronize(identity);
230     emit identityCreated(other.id());
231   } else {
232     qWarning() << tr("Identity already exists in client!");
233   }
234 }
235
236 void Client::coreIdentityRemoved(IdentityId id) {
237   if(_identities.contains(id)) {
238     emit identityRemoved(id);
239     Identity *i = _identities.take(id);
240     i->deleteLater();
241   }
242 }
243
244 /***  ***/
245
246
247 bool Client::isConnected() {
248   return instance()->connectedToCore;
249 }
250
251 void Client::fakeInput(uint bufferUid, QString message) {
252   Buffer *buff = buffer(bufferUid);
253   if(!buff)
254     qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
255   else
256     emit instance()->sendInput(buff->bufferInfo(), message);
257 }
258
259 void Client::fakeInput(BufferInfo bufferInfo, QString message) {
260   fakeInput(bufferInfo, message);
261 }
262
263 void Client::connectToCore(const QVariantMap &conn) {
264   // TODO implement SSL
265   coreConnectionInfo = conn;
266   if(isConnected()) {
267     emit coreConnectionError(tr("Already connected to Core!"));
268     return;
269   }
270   
271   if(socket != 0)
272     socket->deleteLater();
273   
274   if(conn["Host"].toString().isEmpty()) {
275     clientMode = LocalCore;
276     socket = new QBuffer(this);
277     connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
278     socket->open(QIODevice::ReadWrite);
279     //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
280     //syncToCore(state);
281     coreSocketConnected();
282   } else {
283     clientMode = RemoteCore;
284     emit coreConnectionMsg(tr("Connecting..."));
285     Q_ASSERT(!socket);
286     QTcpSocket *sock = new QTcpSocket(this);
287     socket = sock;
288     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
289     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
290     connect(signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
291     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
292     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
293   }
294 }
295
296 void Client::disconnectFromCore() {
297   socket->close();
298 }
299
300 void Client::setCoreConfiguration(const QVariantMap &settings) {
301   SignalProxy::writeDataToDevice(socket, settings);
302 }
303
304 void Client::coreSocketConnected() {
305   connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
306   emit coreConnectionMsg(tr("Synchronizing to core..."));
307   QVariantMap clientInit;
308   clientInit["GuiProtocol"] = GUI_PROTOCOL;
309   clientInit["User"] = coreConnectionInfo["User"].toString();
310   clientInit["Password"] = coreConnectionInfo["Password"].toString();
311   SignalProxy::writeDataToDevice(socket, clientInit);
312 }
313
314 void Client::coreSocketDisconnected() {
315   instance()->connectedToCore = false;
316   emit disconnected();
317   emit coreConnectionStateChanged(false);
318   socket->deleteLater();
319   blockSize = 0;
320
321   /* Clear internal data. Hopefully nothing relies on it at this point. */
322   _networkModel->clear();
323
324   QHash<uint, Buffer *>::iterator bufferIter =  _buffers.begin();
325   while(bufferIter != _buffers.end()) {
326     Buffer *buffer = bufferIter.value();
327     disconnect(buffer, SIGNAL(destroyed()), this, 0);
328     bufferIter = _buffers.erase(bufferIter);
329     buffer->deleteLater();
330   }
331   Q_ASSERT(_buffers.isEmpty());
332
333
334   QHash<uint, NetworkInfo*>::iterator netIter = _networkInfo.begin();
335   while(netIter != _networkInfo.end()) {
336     NetworkInfo *net = netIter.value();
337     disconnect(net, SIGNAL(destroyed()), this, 0);
338     netIter = _networkInfo.erase(netIter);
339     net->deleteLater();
340   }
341   Q_ASSERT(_networkInfo.isEmpty());
342
343   coreConnectionInfo.clear();
344   sessionData.clear();
345   layoutQueue.clear();
346   layoutTimer->stop();
347 }
348
349 void Client::recvCoreState(const QVariant &state) {
350   disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
351   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
352   signalProxy()->addPeer(socket);
353   syncToCore(state);
354 }
355
356 // TODO: auth errors
357 void Client::syncToCore(const QVariant &coreState) {
358   if(!coreState.toMap().contains("SessionState")) {
359     emit coreConnectionError(tr("Invalid data received from core!"));
360     disconnectFromCore();
361     return;
362   }
363
364   QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
365
366   // store sessionData
367   QVariantMap sessData = sessionState["SessionData"].toMap();
368   foreach(QString key, sessData.keys())
369     recvSessionData(key, sessData[key]);
370
371   // create identities
372   foreach(QVariant vid, sessionState["Identities"].toList()) {
373     Identity *id = new Identity(vid.value<Identity>(), this);
374     _identities[id->id()] = id;
375     signalProxy()->synchronize(id);
376     qDebug() << "received identity" << id->identityName();
377   }
378
379   // store Buffer details
380   QVariantList coreBuffers = sessionState["Buffers"].toList();
381   /* make lookups by id faster */
382   foreach(QVariant vid, coreBuffers) {
383     buffer(vid.value<BufferInfo>()); // create all buffers, so we see them in the network views
384   }
385
386   // create networkInfo objects
387   QVariantList networkids = sessionState["Networks"].toList();
388   foreach(QVariant networkid, networkids) {
389     networkConnected(networkid.toUInt());
390   }
391
392   instance()->connectedToCore = true;
393   updateCoreConnectionProgress();
394
395 }
396
397 void Client::updateCoreConnectionProgress() {
398   // we'll do this in three steps:
399   // 1.) networks
400   // 2.) channels
401   // 3.) ircusers
402
403   int numNets = networkInfos().count();
404   int numNetsWaiting = 0;
405
406   int numIrcUsers = 0;
407   int numIrcUsersWaiting = 0;
408
409   int numChannels = 0;
410   int numChannelsWaiting = 0;
411
412   foreach(NetworkInfo *net, networkInfos()) {
413     if(! net->initialized())
414       numNetsWaiting++;
415
416     numIrcUsers += net->ircUsers().count();
417     foreach(IrcUser *user, net->ircUsers()) {
418       if(! user->initialized())
419         numIrcUsersWaiting++;
420     }
421
422     numChannels += net->ircChannels().count();
423     foreach(IrcChannel *channel, net->ircChannels()) {
424       if(! channel->initialized())
425         numChannelsWaiting++;
426     }
427   }
428
429   if(numNetsWaiting > 0) {
430     emit coreConnectionMsg(tr("Requesting network states..."));
431     emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
432     return;
433   }
434
435   if(numIrcUsersWaiting > 0) {
436     emit coreConnectionMsg(tr("Requesting User states..."));
437     emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
438     return;
439   }
440
441   if(numChannelsWaiting > 0) {
442     emit coreConnectionMsg(tr("Requesting Channel states..."));
443     emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
444     return;
445   }
446
447   emit coreConnectionProgress(1,1);
448   emit connected();
449   emit coreConnectionStateChanged(true);
450   foreach(NetworkInfo *net, networkInfos()) {
451     disconnect(net, 0, this, SLOT(updateCoreConnectionProgress()));
452   }
453
454   // signalProxy()->dumpProxyStats();
455 }
456
457 void Client::recvSessionData(const QString &key, const QVariant &data) {
458   sessionData[key] = data;
459   emit sessionDataChanged(key, data);
460   emit sessionDataChanged(key);
461 }
462
463 void Client::storeSessionData(const QString &key, const QVariant &data) {
464   // Not sure if this is a good idea, but we'll try it anyway:
465   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
466   // rather than immediately.
467   emit instance()->sendSessionData(key, data);
468 }
469
470 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
471   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
472   else return def;
473 }
474
475 QStringList Client::sessionDataKeys() {
476   return instance()->sessionData.keys();
477 }
478
479 void Client::coreSocketError(QAbstractSocket::SocketError) {
480   emit coreConnectionError(socket->errorString());
481   socket->deleteLater();
482 }
483
484 void Client::coreHasData() {
485   QVariant item;
486   if(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
487     emit recvPartialItem(1,1);
488     QVariantMap msg = item.toMap();
489     if (!msg["StartWizard"].toBool()) {
490       recvCoreState(msg["Reply"]);
491     } else {
492       qWarning("Core not configured!");
493       qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
494       emit showConfigWizard(msg);
495     }
496     blockSize = 0;
497     return;
498   }
499   if(blockSize > 0) {
500     emit recvPartialItem(socket->bytesAvailable(), blockSize);
501   }
502 }
503
504 void Client::networkConnected(uint netid) {
505   // TODO: create statusBuffer / switch to networkids
506   //BufferInfo id = statusBufferInfo(net);
507   //Buffer *b = buffer(id);
508   //b->setActive(true);
509
510   NetworkInfo *netinfo = new NetworkInfo(netid, this);
511   netinfo->setProxy(signalProxy());
512   networkModel()->attachNetworkInfo(netinfo);
513   
514   if(!isConnected()) {
515     connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
516     connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
517     connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
518   }
519   connect(netinfo, SIGNAL(ircChannelAdded(QString)), this, SLOT(ircChannelAdded(QString)));
520   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkInfoDestroyed()));
521   _networkInfo[netid] = netinfo;
522 }
523
524 void Client::networkDisconnected(uint networkid) {
525   foreach(Buffer *buffer, buffers()) {
526     if(buffer->bufferInfo().networkId() != networkid)
527       continue;
528
529     //buffer->displayMsg(Message(bufferid, Message::Server, tr("Server disconnected."))); FIXME
530     buffer->setActive(false);
531   }
532
533   Q_ASSERT(networkInfo(networkid));
534   if(!networkInfo(networkid)->initialized()) {
535     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
536     updateCoreConnectionProgress();
537   }
538 }
539
540 void Client::ircChannelAdded(QString chanName) {
541   NetworkInfo *netInfo = qobject_cast<NetworkInfo*>(sender());
542   Q_ASSERT(netInfo);
543   Buffer *buf = buffer(bufferInfo(netInfo->networkName(), chanName));
544   Q_ASSERT(buf);
545   buf->setIrcChannel(netInfo->ircChannel(chanName));
546
547 }
548
549 void Client::updateBufferInfo(BufferInfo id) {
550   buffer(id)->updateBufferInfo(id);
551 }
552
553 void Client::bufferDestroyed() {
554   Buffer *buffer = static_cast<Buffer *>(sender());
555   uint bufferUid = buffer->uid();
556   if(_buffers.contains(bufferUid))
557     _buffers.remove(bufferUid);
558 }
559
560 void Client::networkInfoDestroyed() {
561   NetworkInfo *netinfo = static_cast<NetworkInfo *>(sender());
562   uint networkId = netinfo->networkId();
563   if(_networkInfo.contains(networkId))
564     _networkInfo.remove(networkId);
565 }
566
567 void Client::recvMessage(const Message &msg) {
568   Buffer *b = buffer(msg.buffer());
569
570   Buffer::ActivityLevel level = Buffer::OtherActivity;
571   if(msg.type() == Message::Plain || msg.type() == Message::Notice){
572     level |= Buffer::NewMessage;
573   }
574   if(msg.flags() & Message::Highlight){
575     level |= Buffer::Highlight;
576   }
577   emit bufferActivity(level, b);
578
579   b->appendMsg(msg);
580 }
581
582 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
583   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
584 }
585
586 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
587   Buffer *b = buffer(id);
588   foreach(QVariant v, msgs) {
589     Message msg = v.value<Message>();
590     b->prependMsg(msg);
591     if(!layoutQueue.contains(b)) layoutQueue.append(b);
592   }
593   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
594 }
595
596 void Client::layoutMsg() {
597   if(layoutQueue.count()) {
598     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
599     if(b->layoutMsg())
600       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
601   }
602   
603   if(!layoutQueue.count())
604     layoutTimer->stop();
605 }
606
607 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
608   return instance()->mainUi->layoutMsg(msg);
609 }
610
611 void Client::userInput(BufferInfo id, QString msg) {
612   emit sendInput(id, msg);
613 }
614