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