e96dfd4877bbbcc2951033ce6ce9849304f4e5aa
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
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 <QtScript>
22
23 #include "core.h"
24 #include "coresession.h"
25 #include "networkconnection.h"
26 #include "userinputhandler.h"
27
28 #include "signalproxy.h"
29 #include "buffersyncer.h"
30 #include "corebacklogmanager.h"
31 #include "corebufferviewmanager.h"
32 #include "coreirclisthelper.h"
33 #include "storage.h"
34
35 #include "corenetwork.h"
36 #include "ircuser.h"
37 #include "ircchannel.h"
38 #include "identity.h"
39
40 #include "util.h"
41 #include "coreusersettings.h"
42
43 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
44   : QObject(parent),
45     _user(uid),
46     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
47     _bufferSyncer(new BufferSyncer(this)),
48     _backlogManager(new CoreBacklogManager(this)),
49     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
50     _ircListHelper(new CoreIrcListHelper(this)),
51     scriptEngine(new QScriptEngine(this))
52 {
53
54   SignalProxy *p = signalProxy();
55   connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
56   
57   //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
58   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
59   p->attachSignal(this, SIGNAL(displayMsg(Message)));
60   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
61   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
62
63   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
64   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
65   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
66   p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
67   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
68
69   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
70   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
71   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
72   p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
73   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
74
75   loadSettings();
76   initScriptEngine();
77
78   // init BufferSyncer
79   QHash<BufferId, MsgId> lastSeenHash = Core::bufferLastSeenMsgIds(user());
80   foreach(BufferId id, lastSeenHash.keys())
81     _bufferSyncer->requestSetLastSeenMsg(id, lastSeenHash[id]);
82   
83   connect(_bufferSyncer, SIGNAL(lastSeenMsgSet(BufferId, MsgId)), this, SLOT(storeBufferLastSeenMsg(BufferId, MsgId)));
84   connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
85   connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
86   connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
87   p->synchronize(_bufferSyncer);
88
89
90   // init BacklogManager;
91   p->synchronize(_backlogManager);
92
93   // init IrcListHelper;
94   p->synchronize(ircListHelper());
95   
96   // Restore session state
97   if(restoreState) restoreSessionState();
98
99   emit initialized();
100 }
101
102 CoreSession::~CoreSession() {
103   saveSessionState();
104   foreach(NetworkConnection *conn, _connections.values()) {
105     delete conn;
106   }
107   foreach(CoreNetwork *net, _networks.values()) {
108     delete net;
109   }
110 }
111
112 UserId CoreSession::user() const {
113   return _user;
114 }
115
116 CoreNetwork *CoreSession::network(NetworkId id) const {
117   if(_networks.contains(id)) return _networks[id];
118   return 0;
119 }
120
121 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
122   if(_connections.contains(id)) return _connections[id];
123   return 0;
124 }
125
126 Identity *CoreSession::identity(IdentityId id) const {
127   if(_identities.contains(id)) return _identities[id];
128   return 0;
129 }
130
131 void CoreSession::loadSettings() {
132   CoreUserSettings s(user());
133
134   foreach(IdentityId id, s.identityIds()) {
135     Identity *i = new Identity(s.identity(id), this);
136     if(!i->isValid()) {
137       qWarning() << QString("Invalid identity! Removing...");
138       s.removeIdentity(id);
139       delete i;
140       continue;
141     }
142     if(_identities.contains(i->id())) {
143       qWarning() << "Duplicate identity, ignoring!";
144       delete i;
145       continue;
146     }
147     _identities[i->id()] = i;
148     signalProxy()->synchronize(i);
149   }
150   if(!_identities.count()) {
151     Identity i(1);
152     i.setToDefaults();
153     i.setIdentityName(tr("Default Identity"));
154     createIdentity(i);
155   }
156
157   foreach(NetworkInfo info, Core::networks(user())) {
158     createNetwork(info);
159   }
160 }
161
162 void CoreSession::saveSessionState() const {
163
164 }
165
166 void CoreSession::restoreSessionState() {
167   QList<NetworkId> nets = Core::connectedNetworks(user());
168   foreach(NetworkId id, nets) {
169     connectToNetwork(id);
170   }
171 }
172
173 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
174   if(uid == user()) emit bufferInfoUpdated(bufinfo);
175 }
176
177 void CoreSession::connectToNetwork(NetworkId id) {
178   CoreNetwork *net = network(id);
179   if(!net) {
180     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
181     return;
182   }
183
184   NetworkConnection *conn = networkConnection(id);
185   if(!conn) {
186     conn = new NetworkConnection(net, this);
187     _connections[id] = conn;
188     attachNetworkConnection(conn);
189   }
190   conn->connectToIrc();
191 }
192
193 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
194   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
195   connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
196
197   // I guess we don't need these anymore, client-side can just connect the network's signals directly
198   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
199   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
200
201   connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
202           this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
203   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
204
205   connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
206           this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
207   connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
208           this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
209   connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
210           this, SLOT(channelParted(NetworkId, const QString &)));
211 }
212
213 void CoreSession::disconnectFromNetwork(NetworkId id) {
214   if(!_connections.contains(id))
215     return;
216   
217   //_connections[id]->disconnectFromIrc();
218   _connections[id]->userInputHandler()->handleQuit(BufferInfo(), QString());
219 }
220
221 void CoreSession::networkStateRequested() {
222 }
223
224 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
225   QIODevice *device = qobject_cast<QIODevice *>(dev);
226   if(!device) {
227     qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
228   } else {
229     signalProxy()->addPeer(device);
230     QVariantMap reply;
231     reply["MsgType"] = "SessionInit";
232     reply["SessionState"] = sessionState();
233     SignalProxy::writeDataToDevice(device, reply);
234   }
235 }
236
237 void CoreSession::removeClient(QIODevice *iodev) {
238   // no checks for validity check - privateslot...
239   QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
240   if(socket)
241     qDebug() << qPrintable(tr("Client %1 disconnected (UserId: %2).").arg(socket->peerAddress().toString()).arg(user().toInt()));
242   else
243     qDebug() << "Local client disconnedted.";
244   disconnect(socket, 0, this, 0);
245   socket->deleteLater();
246 }
247
248 SignalProxy *CoreSession::signalProxy() const {
249   return _signalProxy;
250 }
251
252 // FIXME we need a sane way for creating buffers!
253 void CoreSession::networkConnected(NetworkId networkid) {
254   Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
255   Core::setNetworkConnected(user(), networkid, true);
256 }
257
258 // called now only on /quit and requested disconnects, not on normal disconnects!
259 void CoreSession::networkDisconnected(NetworkId networkid) {
260   // if the network has already been removed, we don't have a networkconnection left either, so we don't do anything
261   // make sure to not depend on the network still existing when calling this function!
262   if(_connections.contains(networkid)) {
263     Core::setNetworkConnected(user(), networkid, false);
264     _connections.take(networkid)->deleteLater();
265   }
266 }
267
268 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
269   Core::setChannelPersistent(user(), id, channel, true);
270   Core::setPersistentChannelKey(user(), id, channel, key);
271 }
272
273 void CoreSession::channelParted(NetworkId id, const QString &channel) {
274   Core::setChannelPersistent(user(), id, channel, false);
275 }
276
277 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
278   return Core::persistentChannels(user(), id);
279   return QHash<QString, QString>();
280 }
281
282 // FIXME switch to BufferId
283 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
284   NetworkConnection *conn = networkConnection(bufinfo.networkId());
285   if(conn) {
286     conn->userInput(bufinfo, msg);
287   } else {
288     qWarning() << "Trying to send to unconnected network:" << msg;
289   }
290 }
291
292 // ALL messages coming pass through these functions before going to the GUI.
293 // So this is the perfect place for storing the backlog and log stuff.
294 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
295   NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
296   Q_ASSERT(netCon);
297   
298   BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
299   Message msg(bufferInfo, type, text, sender, flags);
300   msg.setMsgId(Core::storeMessage(msg));
301   Q_ASSERT(msg.msgId() != 0);
302   emit displayMsg(msg);
303 }
304
305 void CoreSession::recvStatusMsgFromServer(QString msg) {
306   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
307   Q_ASSERT(s);
308   emit displayStatusMsg(s->networkName(), msg);
309 }
310
311 QList<BufferInfo> CoreSession::buffers() const {
312   return Core::requestBuffers(user());
313 }
314
315
316 QVariant CoreSession::sessionState() {
317   QVariantMap v;
318
319   QVariantList bufs;
320   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
321   v["BufferInfos"] = bufs;
322   QVariantList networkids;
323   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
324   v["NetworkIds"] = networkids;
325
326   quint32 ircusercount = 0;
327   quint32 ircchannelcount = 0;
328   foreach(Network *net, _networks.values()) {
329     ircusercount += net->ircUserCount();
330     ircchannelcount += net->ircChannelCount();
331   }
332   v["IrcUserCount"] = ircusercount;
333   v["IrcChannelCount"] = ircchannelcount;
334
335   QList<QVariant> idlist;
336   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
337   v["Identities"] = idlist;
338
339   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
340   return v;
341 }
342
343 void CoreSession::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
344   Core::setBufferLastSeenMsg(user(), buffer, msgId);
345 }
346
347 void CoreSession::initScriptEngine() {
348   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
349   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
350
351   // FIXME
352   //QScriptValue storage_ = scriptEngine->newQObject(storage);
353   //scriptEngine->globalObject().setProperty("storage", storage_);
354 }
355
356 void CoreSession::scriptRequest(QString script) {
357   emit scriptResult(scriptEngine->evaluate(script).toString());
358 }
359
360 /*** Identity Handling ***/
361
362 void CoreSession::createIdentity(const Identity &id) {
363   // find free ID
364   int i;
365   for(i = 1; i <= _identities.count(); i++) {
366     if(!_identities.keys().contains(i)) break;
367   }
368   //qDebug() << "found free id" << i;
369   Identity *newId = new Identity(id, this);
370   newId->setId(i);
371   _identities[i] = newId;
372   signalProxy()->synchronize(newId);
373   CoreUserSettings s(user());
374   s.storeIdentity(*newId);
375   emit identityCreated(*newId);
376 }
377
378 void CoreSession::updateIdentity(const Identity &id) {
379   if(!_identities.contains(id.id())) {
380     qWarning() << "Update request for unknown identity received!";
381     return;
382   }
383   _identities[id.id()]->update(id);
384
385   CoreUserSettings s(user());
386   s.storeIdentity(id);
387 }
388
389 void CoreSession::removeIdentity(IdentityId id) {
390   Identity *i = _identities.take(id);
391   if(i) {
392     emit identityRemoved(id);
393     CoreUserSettings s(user());
394     s.removeIdentity(id);
395     i->deleteLater();
396   }
397 }
398
399 /*** Network Handling ***/
400
401 void CoreSession::createNetwork(const NetworkInfo &info_) {
402   NetworkInfo info = info_;
403   int id;
404
405   if(!info.networkId.isValid())
406     Core::createNetwork(user(), info);
407
408   if(!info.networkId.isValid()) {
409     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
410     return;
411   }
412
413   id = info.networkId.toInt();
414   if(!_networks.contains(id)) {
415     CoreNetwork *net = new CoreNetwork(id, this);
416     connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
417     connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
418     net->setNetworkInfo(info);
419     net->setProxy(signalProxy());
420     _networks[id] = net;
421     signalProxy()->synchronize(net);
422     emit networkCreated(id);
423   } else {
424     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
425     updateNetwork(info);
426   }
427 }
428
429 // FIXME: move to CoreNetwork
430 void CoreSession::updateNetwork(const NetworkInfo &info) {
431   if(!_networks.contains(info.networkId)) {
432     qWarning() << "Update request for unknown network received!";
433     return;
434   }
435   _networks[info.networkId]->setNetworkInfo(info);
436   Core::updateNetwork(user(), info);
437 }
438
439 void CoreSession::removeNetwork(NetworkId id) {
440   // Make sure the network is disconnected!
441   NetworkConnection *conn = _connections.value(id, 0);
442   if(conn) {
443     if(conn->connectionState() != Network::Disconnected) {
444       connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
445       conn->disconnectFromIrc();
446     } else {
447       _connections.take(id)->deleteLater();  // TODO make this saner
448       destroyNetwork(id);
449     }
450   } else {
451     destroyNetwork(id);
452   }
453 }
454
455 void CoreSession::destroyNetwork(NetworkId id) {
456   if(_connections.contains(id)) {
457     // this can happen if the network was reconnecting while being removed
458     _connections.take(id)->deleteLater();
459   }
460   Network *net = _networks.take(id);
461   if(net && Core::removeNetwork(user(), id)) {
462     emit networkRemoved(id);
463     net->deleteLater();
464   }
465 }
466
467 void CoreSession::removeBufferRequested(BufferId bufferId) {
468   BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
469   if(!bufferInfo.isValid()) {
470     qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
471     return;
472   }
473   
474   if(bufferInfo.type() == BufferInfo::StatusBuffer) {
475     qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
476     return;
477   }
478   
479   if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
480     CoreNetwork *net = network(bufferInfo.networkId());
481     if(!net) {
482       qWarning() << "CoreSession::removeBufferRequested(): Received BufferInfo with unknown networkId!";
483       return;
484     }
485     IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
486     if(chan) {
487       qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
488       return;
489     }
490   }
491   if(Core::removeBuffer(user(), bufferId))
492     emit bufferRemoved(bufferId);
493 }
494
495 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
496   BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
497   if(bufferId.isValid()) {
498     emit bufferRenamed(bufferId, newName);
499   }
500 }