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