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