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