fixing output issues with IPv6 host addresses
[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 #include "userinputhandler.h"
27
28 #include "signalproxy.h"
29 #include "buffersyncer.h"
30 #include "corebacklogmanager.h"
31 #include "corebufferviewmanager.h"
32 #include "coreirclisthelper.h"
33 #include "storage.h"
34
35 #include "corenetwork.h"
36 #include "ircuser.h"
37 #include "ircchannel.h"
38 #include "identity.h"
39
40 #include "util.h"
41 #include "coreusersettings.h"
42
43 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
44   : QObject(parent),
45     _user(uid),
46     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
47     _bufferSyncer(new BufferSyncer(this)),
48     _backlogManager(new CoreBacklogManager(this)),
49     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
50     _ircListHelper(new CoreIrcListHelper(this)),
51     scriptEngine(new QScriptEngine(this))
52 {
53
54   SignalProxy *p = signalProxy();
55   connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
56   
57   //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
58   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
59   p->attachSignal(this, SIGNAL(displayMsg(Message)));
60   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
61   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
62
63   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
64   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
65   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
66   p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
67   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
68
69   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
70   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
71   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
72   p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
73   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
74
75   loadSettings();
76   initScriptEngine();
77
78   // init BufferSyncer
79   QHash<BufferId, MsgId> lastSeenHash = Core::bufferLastSeenMsgIds(user());
80   foreach(BufferId id, lastSeenHash.keys())
81     _bufferSyncer->requestSetLastSeenMsg(id, lastSeenHash[id]);
82   
83   connect(_bufferSyncer, SIGNAL(lastSeenMsgSet(BufferId, MsgId)), this, SLOT(storeBufferLastSeenMsg(BufferId, MsgId)));
84   connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
85   connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
86   connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
87   p->synchronize(_bufferSyncer);
88
89
90   // init BacklogManager;
91   p->synchronize(_backlogManager);
92
93   // init IrcListHelper;
94   p->synchronize(ircListHelper());
95   
96   // Restore session state
97   if(restoreState) restoreSessionState();
98
99   emit initialized();
100 }
101
102 CoreSession::~CoreSession() {
103   saveSessionState();
104   foreach(NetworkConnection *conn, _connections.values()) {
105     delete conn;
106   }
107   foreach(CoreNetwork *net, _networks.values()) {
108     delete net;
109   }
110 }
111
112 UserId CoreSession::user() const {
113   return _user;
114 }
115
116 CoreNetwork *CoreSession::network(NetworkId id) const {
117   if(_networks.contains(id)) return _networks[id];
118   return 0;
119 }
120
121 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
122   if(_connections.contains(id)) return _connections[id];
123   return 0;
124 }
125
126 Identity *CoreSession::identity(IdentityId id) const {
127   if(_identities.contains(id)) return _identities[id];
128   return 0;
129 }
130
131 void CoreSession::loadSettings() {
132   CoreUserSettings s(user());
133
134   foreach(IdentityId id, s.identityIds()) {
135     Identity *i = new Identity(s.identity(id), this);
136     if(!i->isValid()) {
137       qWarning() << QString("Invalid identity! Removing...");
138       s.removeIdentity(id);
139       delete i;
140       continue;
141     }
142     if(_identities.contains(i->id())) {
143       qWarning() << "Duplicate identity, ignoring!";
144       delete i;
145       continue;
146     }
147     _identities[i->id()] = i;
148     signalProxy()->synchronize(i);
149   }
150   if(!_identities.count()) {
151     Identity i(1);
152     i.setToDefaults();
153     i.setIdentityName(tr("Default Identity"));
154     createIdentity(i);
155   }
156
157   foreach(NetworkInfo info, Core::networks(user())) {
158     createNetwork(info);
159   }
160 }
161
162 void CoreSession::saveSessionState() const {
163
164 }
165
166 void CoreSession::restoreSessionState() {
167   QList<NetworkId> nets = Core::connectedNetworks(user());
168   foreach(NetworkId id, nets) {
169     connectToNetwork(id);
170   }
171 }
172
173 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
174   if(uid == user()) emit bufferInfoUpdated(bufinfo);
175 }
176
177 void CoreSession::connectToNetwork(NetworkId id) {
178   CoreNetwork *net = network(id);
179   if(!net) {
180     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
181     return;
182   }
183
184   NetworkConnection *conn = networkConnection(id);
185   if(!conn) {
186     conn = new NetworkConnection(net, this);
187     _connections[id] = conn;
188     attachNetworkConnection(conn);
189   }
190   conn->connectToIrc();
191 }
192
193 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
194   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
195   connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
196
197   // I guess we don't need these anymore, client-side can just connect the network's signals directly
198   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
199   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
200
201   connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
202           this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
203   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
204
205   connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
206           this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
207   connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
208           this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
209   connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
210           this, SLOT(channelParted(NetworkId, const QString &)));
211 }
212
213 void CoreSession::disconnectFromNetwork(NetworkId id) {
214   if(!_connections.contains(id))
215     return;
216   
217   //_connections[id]->disconnectFromIrc();
218   _connections[id]->userInputHandler()->handleQuit(BufferInfo(), QString());
219 }
220
221 void CoreSession::networkStateRequested() {
222 }
223
224 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
225   QIODevice *device = qobject_cast<QIODevice *>(dev);
226   if(!device) {
227     qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
228   } else {
229     signalProxy()->addPeer(device);
230     QVariantMap reply;
231     reply["MsgType"] = "SessionInit";
232     reply["SessionState"] = sessionState();
233     SignalProxy::writeDataToDevice(device, reply);
234   }
235 }
236
237 void CoreSession::removeClient(QIODevice *iodev) {
238   // no checks for validity check - privateslot...
239   QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
240   if(socket)
241     qDebug() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
242   else
243     qDebug() << "Local client disconnedted.";
244   disconnect(socket, 0, this, 0);
245   socket->deleteLater();
246 }
247
248 SignalProxy *CoreSession::signalProxy() const {
249   return _signalProxy;
250 }
251
252 // FIXME we need a sane way for creating buffers!
253 void CoreSession::networkConnected(NetworkId networkid) {
254   Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
255   Core::setNetworkConnected(user(), networkid, true);
256 }
257
258 // called now only on /quit and requested disconnects, not on normal disconnects!
259 void CoreSession::networkDisconnected(NetworkId networkid) {
260   // if the network has already been removed, we don't have a networkconnection left either, so we don't do anything
261   // make sure to not depend on the network still existing when calling this function!
262   if(_connections.contains(networkid)) {
263     Core::setNetworkConnected(user(), networkid, false);
264     _connections.take(networkid)->deleteLater();
265   }
266 }
267
268 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
269   Core::setChannelPersistent(user(), id, channel, true);
270   Core::setPersistentChannelKey(user(), id, channel, key);
271 }
272
273 void CoreSession::channelParted(NetworkId id, const QString &channel) {
274   Core::setChannelPersistent(user(), id, channel, false);
275 }
276
277 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
278   return Core::persistentChannels(user(), id);
279   return QHash<QString, QString>();
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:" << msg;
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,
295                                         QString target, QString text, QString sender, Message::Flags 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::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
345   Core::setBufferLastSeenMsg(user(), buffer, msgId);
346 }
347
348 void CoreSession::initScriptEngine() {
349   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
350   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
351
352   // FIXME
353   //QScriptValue storage_ = scriptEngine->newQObject(storage);
354   //scriptEngine->globalObject().setProperty("storage", storage_);
355 }
356
357 void CoreSession::scriptRequest(QString script) {
358   emit scriptResult(scriptEngine->evaluate(script).toString());
359 }
360
361 /*** Identity Handling ***/
362
363 void CoreSession::createIdentity(const Identity &id) {
364   // find free ID
365   int i;
366   for(i = 1; i <= _identities.count(); i++) {
367     if(!_identities.keys().contains(i)) break;
368   }
369   //qDebug() << "found free id" << i;
370   Identity *newId = new Identity(id, this);
371   newId->setId(i);
372   _identities[i] = newId;
373   signalProxy()->synchronize(newId);
374   CoreUserSettings s(user());
375   s.storeIdentity(*newId);
376   emit identityCreated(*newId);
377 }
378
379 void CoreSession::updateIdentity(const Identity &id) {
380   if(!_identities.contains(id.id())) {
381     qWarning() << "Update request for unknown identity received!";
382     return;
383   }
384   _identities[id.id()]->update(id);
385
386   CoreUserSettings s(user());
387   s.storeIdentity(id);
388 }
389
390 void CoreSession::removeIdentity(IdentityId id) {
391   Identity *i = _identities.take(id);
392   if(i) {
393     emit identityRemoved(id);
394     CoreUserSettings s(user());
395     s.removeIdentity(id);
396     i->deleteLater();
397   }
398 }
399
400 /*** Network Handling ***/
401
402 void CoreSession::createNetwork(const NetworkInfo &info_) {
403   NetworkInfo info = info_;
404   int id;
405
406   if(!info.networkId.isValid())
407     Core::createNetwork(user(), info);
408
409   if(!info.networkId.isValid()) {
410     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
411     return;
412   }
413
414   id = info.networkId.toInt();
415   if(!_networks.contains(id)) {
416     CoreNetwork *net = new CoreNetwork(id, this);
417     connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
418     connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
419     net->setNetworkInfo(info);
420     net->setProxy(signalProxy());
421     _networks[id] = net;
422     signalProxy()->synchronize(net);
423     emit networkCreated(id);
424   } else {
425     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
426     updateNetwork(info);
427   }
428 }
429
430 // FIXME: move to CoreNetwork
431 void CoreSession::updateNetwork(const NetworkInfo &info) {
432   if(!_networks.contains(info.networkId)) {
433     qWarning() << "Update request for unknown network received!";
434     return;
435   }
436   _networks[info.networkId]->setNetworkInfo(info);
437   Core::updateNetwork(user(), info);
438 }
439
440 void CoreSession::removeNetwork(NetworkId id) {
441   // Make sure the network is disconnected!
442   NetworkConnection *conn = _connections.value(id, 0);
443   if(conn) {
444     if(conn->connectionState() != Network::Disconnected) {
445       connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
446       conn->disconnectFromIrc();
447     } else {
448       _connections.take(id)->deleteLater();  // TODO make this saner
449       destroyNetwork(id);
450     }
451   } else {
452     destroyNetwork(id);
453   }
454 }
455
456 void CoreSession::destroyNetwork(NetworkId id) {
457   if(_connections.contains(id)) {
458     // this can happen if the network was reconnecting while being removed
459     _connections.take(id)->deleteLater();
460   }
461   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
462   Network *net = _networks.take(id);
463   if(net && Core::removeNetwork(user(), id)) {
464     foreach(BufferId bufferId, removedBuffers) {
465       _bufferSyncer->removeBuffer(bufferId);
466     }
467     emit networkRemoved(id);
468     net->deleteLater();
469   }
470 }
471
472 void CoreSession::removeBufferRequested(BufferId bufferId) {
473   BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
474   if(!bufferInfo.isValid()) {
475     qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
476     return;
477   }
478   
479   if(bufferInfo.type() == BufferInfo::StatusBuffer) {
480     qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
481     return;
482   }
483   
484   if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
485     CoreNetwork *net = network(bufferInfo.networkId());
486     if(!net) {
487       qWarning() << "CoreSession::removeBufferRequested(): Received BufferInfo with unknown networkId!";
488       return;
489     }
490     IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
491     if(chan) {
492       qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
493       return;
494     }
495   }
496   if(Core::removeBuffer(user(), bufferId))
497     emit bufferRemoved(bufferId);
498 }
499
500 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
501   BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
502   if(bufferId.isValid()) {
503     emit bufferRenamed(bufferId, newName);
504   }
505 }