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