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