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