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