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