ded76eff0c7d302cf69cebfa4df9c310c86c08cc
[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 #include "logger.h"
43
44 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
45   : QObject(parent),
46     _user(uid),
47     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
48     _aliasManager(this),
49     _bufferSyncer(new BufferSyncer(this)),
50     _backlogManager(new CoreBacklogManager(this)),
51     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
52     _ircListHelper(new CoreIrcListHelper(this)),
53     _coreInfo(this),
54     scriptEngine(new QScriptEngine(this))
55 {
56
57   SignalProxy *p = signalProxy();
58   connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
59
60   //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
61   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
62   p->attachSignal(this, SIGNAL(displayMsg(Message)));
63   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
64   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
65
66   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
67   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
68   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(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(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
75
76   loadSettings();
77   initScriptEngine();
78
79   // init BufferSyncer
80   QHash<BufferId, MsgId> lastSeenHash = Core::bufferLastSeenMsgIds(user());
81   foreach(BufferId id, lastSeenHash.keys())
82     _bufferSyncer->requestSetLastSeenMsg(id, lastSeenHash[id]);
83
84   connect(_bufferSyncer, SIGNAL(lastSeenMsgSet(BufferId, MsgId)), this, SLOT(storeBufferLastSeenMsg(BufferId, MsgId)));
85   connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
86   connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
87   connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
88   p->synchronize(_bufferSyncer);
89
90
91   // init alias manager
92   p->synchronize(&aliasManager());
93
94   // init BacklogManager
95   p->synchronize(_backlogManager);
96
97   // init IrcListHelper
98   p->synchronize(ircListHelper());
99
100   // init CoreInfo
101   p->synchronize(&_coreInfo);
102
103   // Restore session state
104   if(restoreState) restoreSessionState();
105
106   emit initialized();
107 }
108
109 CoreSession::~CoreSession() {
110   saveSessionState();
111   foreach(NetworkConnection *conn, _connections.values()) {
112     delete conn;
113   }
114   foreach(CoreNetwork *net, _networks.values()) {
115     delete net;
116   }
117 }
118
119 UserId CoreSession::user() const {
120   return _user;
121 }
122
123 CoreNetwork *CoreSession::network(NetworkId id) const {
124   if(_networks.contains(id)) return _networks[id];
125   return 0;
126 }
127
128 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
129   if(_connections.contains(id)) return _connections[id];
130   return 0;
131 }
132
133 Identity *CoreSession::identity(IdentityId id) const {
134   if(_identities.contains(id)) return _identities[id];
135   return 0;
136 }
137
138 void CoreSession::loadSettings() {
139   CoreUserSettings s(user());
140
141   foreach(IdentityId id, s.identityIds()) {
142     Identity *i = new Identity(s.identity(id), this);
143     if(!i->isValid()) {
144       quWarning() << "Invalid identity! Removing...";
145       s.removeIdentity(id);
146       delete i;
147       continue;
148     }
149     if(_identities.contains(i->id())) {
150       quWarning() << "Duplicate identity, ignoring!";
151       delete i;
152       continue;
153     }
154     connect(i, SIGNAL(updated(const QVariantMap &)), this, SLOT(identityUpdated(const QVariantMap &)));
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     quWarning() << "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     quError() << "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   QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
247   if(socket)
248     quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
249   iodev->deleteLater();
250 }
251
252 SignalProxy *CoreSession::signalProxy() const {
253   return _signalProxy;
254 }
255
256 // FIXME we need a sane way for creating buffers!
257 void CoreSession::networkConnected(NetworkId networkid) {
258   Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
259   Core::setNetworkConnected(user(), networkid, true);
260 }
261
262 // called now only on /quit and requested disconnects, not on normal disconnects!
263 void CoreSession::networkDisconnected(NetworkId networkid) {
264   // if the network has already been removed, we don't have a networkconnection left either, so we don't do anything
265   // make sure to not depend on the network still existing when calling this function!
266   if(_connections.contains(networkid)) {
267     Core::setNetworkConnected(user(), networkid, false);
268     _connections.take(networkid)->deleteLater();
269   }
270 }
271
272 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
273   Core::setChannelPersistent(user(), id, channel, true);
274   Core::setPersistentChannelKey(user(), id, channel, key);
275 }
276
277 void CoreSession::channelParted(NetworkId id, const QString &channel) {
278   Core::setChannelPersistent(user(), id, channel, false);
279 }
280
281 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
282   return Core::persistentChannels(user(), id);
283   return QHash<QString, QString>();
284 }
285
286 // FIXME switch to BufferId
287 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
288   NetworkConnection *conn = networkConnection(bufinfo.networkId());
289   if(conn) {
290     conn->userInput(bufinfo, msg);
291   } else {
292     quWarning() << "Trying to send to unconnected network:" << msg;
293   }
294 }
295
296 // ALL messages coming pass through these functions before going to the GUI.
297 // So this is the perfect place for storing the backlog and log stuff.
298 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType,
299                                         QString target, QString text, QString sender, Message::Flags flags) {
300   NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
301   Q_ASSERT(netCon);
302
303   BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
304   Message msg(bufferInfo, type, text, sender, flags);
305   msg.setMsgId(Core::storeMessage(msg));
306   Q_ASSERT(msg.msgId() != 0);
307   emit displayMsg(msg);
308 }
309
310 void CoreSession::recvStatusMsgFromServer(QString msg) {
311   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
312   Q_ASSERT(s);
313   emit displayStatusMsg(s->networkName(), msg);
314 }
315
316 QList<BufferInfo> CoreSession::buffers() const {
317   return Core::requestBuffers(user());
318 }
319
320
321 QVariant CoreSession::sessionState() {
322   QVariantMap v;
323
324   QVariantList bufs;
325   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
326   v["BufferInfos"] = bufs;
327   QVariantList networkids;
328   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
329   v["NetworkIds"] = networkids;
330
331   quint32 ircusercount = 0;
332   quint32 ircchannelcount = 0;
333   foreach(Network *net, _networks.values()) {
334     ircusercount += net->ircUserCount();
335     ircchannelcount += net->ircChannelCount();
336   }
337   v["IrcUserCount"] = ircusercount;
338   v["IrcChannelCount"] = ircchannelcount;
339
340   QList<QVariant> idlist;
341   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
342   v["Identities"] = idlist;
343
344   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
345   return v;
346 }
347
348 void CoreSession::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
349   Core::setBufferLastSeenMsg(user(), buffer, msgId);
350 }
351
352 void CoreSession::initScriptEngine() {
353   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
354   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
355
356   // FIXME
357   //QScriptValue storage_ = scriptEngine->newQObject(storage);
358   //scriptEngine->globalObject().setProperty("storage", storage_);
359 }
360
361 void CoreSession::scriptRequest(QString script) {
362   emit scriptResult(scriptEngine->evaluate(script).toString());
363 }
364
365 /*** Identity Handling ***/
366
367 void CoreSession::createIdentity(const Identity &id) {
368   // find free ID
369   int i;
370   for(i = 1; i <= _identities.count(); i++) {
371     if(!_identities.keys().contains(i)) break;
372   }
373   //qDebug() << "found free id" << i;
374   Identity *newId = new Identity(id, this);
375   newId->setId(i);
376   _identities[i] = newId;
377   signalProxy()->synchronize(newId);
378   CoreUserSettings s(user());
379   s.storeIdentity(*newId);
380   connect(newId, SIGNAL(updated(const QVariantMap &)), this, SLOT(identityUpdated(const QVariantMap &)));
381   emit identityCreated(*newId);
382 }
383
384 void CoreSession::removeIdentity(IdentityId id) {
385   Identity *i = _identities.take(id);
386   if(i) {
387     emit identityRemoved(id);
388     CoreUserSettings s(user());
389     s.removeIdentity(id);
390     i->deleteLater();
391   }
392 }
393
394 void CoreSession::identityUpdated(const QVariantMap &data) {
395   IdentityId id = data.value("identityId", 0).value<IdentityId>();
396   if(!id.isValid() || !_identities.contains(id)) {
397     quWarning() << "Update request for unknown identity received!";
398     return;
399   }
400   CoreUserSettings s(user());
401   s.storeIdentity(*_identities.value(id));
402 }
403
404 /*** Network Handling ***/
405
406 void CoreSession::createNetwork(const NetworkInfo &info_) {
407   NetworkInfo info = info_;
408   int id;
409
410   if(!info.networkId.isValid())
411     Core::createNetwork(user(), info);
412
413   if(!info.networkId.isValid()) {
414     quWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
415     return;
416   }
417
418   id = info.networkId.toInt();
419   if(!_networks.contains(id)) {
420     CoreNetwork *net = new CoreNetwork(id, this);
421     connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
422     connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
423     net->setNetworkInfo(info);
424     net->setProxy(signalProxy());
425     _networks[id] = net;
426     signalProxy()->synchronize(net);
427     emit networkCreated(id);
428   } else {
429     quWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
430     _networks[info.networkId]->requestSetNetworkInfo(info);
431   }
432 }
433
434 void CoreSession::removeNetwork(NetworkId id) {
435   // Make sure the network is disconnected!
436   NetworkConnection *conn = _connections.value(id, 0);
437   if(conn) {
438     if(conn->connectionState() != Network::Disconnected) {
439       connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
440       conn->disconnectFromIrc();
441     } else {
442       _connections.take(id)->deleteLater();  // TODO make this saner
443       destroyNetwork(id);
444     }
445   } else {
446     destroyNetwork(id);
447   }
448 }
449
450 void CoreSession::destroyNetwork(NetworkId id) {
451   if(_connections.contains(id)) {
452     // this can happen if the network was reconnecting while being removed
453     _connections.take(id)->deleteLater();
454   }
455   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
456   Network *net = _networks.take(id);
457   if(net && Core::removeNetwork(user(), id)) {
458     foreach(BufferId bufferId, removedBuffers) {
459       _bufferSyncer->removeBuffer(bufferId);
460     }
461     emit networkRemoved(id);
462     net->deleteLater();
463   }
464 }
465
466 void CoreSession::removeBufferRequested(BufferId bufferId) {
467   BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
468   if(!bufferInfo.isValid()) {
469     quWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
470     return;
471   }
472
473   if(bufferInfo.type() == BufferInfo::StatusBuffer) {
474     quWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
475     return;
476   }
477
478   if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
479     CoreNetwork *net = network(bufferInfo.networkId());
480     if(!net) {
481       quWarning() << "CoreSession::removeBufferRequested(): Received BufferInfo with unknown networkId!";
482       return;
483     }
484     IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
485     if(chan) {
486       quWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
487       return;
488     }
489   }
490   if(Core::removeBuffer(user(), bufferId))
491     emit bufferRemoved(bufferId);
492 }
493
494 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
495   BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
496   if(bufferId.isValid()) {
497     emit bufferRenamed(bufferId, newName);
498   }
499 }