Add initial implementation for showing and kicking connected clients
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "coresession.h"
22
23 #include <QtScript>
24
25 #include "core.h"
26 #include "coreuserinputhandler.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coredccconfig.h"
31 #include "coreeventmanager.h"
32 #include "coreidentity.h"
33 #include "coreignorelistmanager.h"
34 #include "coreirclisthelper.h"
35 #include "corenetwork.h"
36 #include "corenetworkconfig.h"
37 #include "coresessioneventprocessor.h"
38 #include "coretransfermanager.h"
39 #include "coreusersettings.h"
40 #include "ctcpparser.h"
41 #include "eventstringifier.h"
42 #include "internalpeer.h"
43 #include "ircchannel.h"
44 #include "ircparser.h"
45 #include "ircuser.h"
46 #include "logger.h"
47 #include "messageevent.h"
48 #include "remotepeer.h"
49 #include "storage.h"
50 #include "util.h"
51
52
53 class ProcessMessagesEvent : public QEvent
54 {
55 public:
56     ProcessMessagesEvent() : QEvent(QEvent::User) {}
57 };
58
59
60 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
61     : QObject(parent),
62     _user(uid),
63     _signalProxy(new SignalProxy(SignalProxy::Server, this)),
64     _aliasManager(this),
65     _bufferSyncer(new CoreBufferSyncer(this)),
66     _backlogManager(new CoreBacklogManager(this)),
67     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
68     _dccConfig(new CoreDccConfig(this)),
69     _ircListHelper(new CoreIrcListHelper(this)),
70     _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
71     _coreInfo(this),
72     _transferManager(new CoreTransferManager(this)),
73     _eventManager(new CoreEventManager(this)),
74     _eventStringifier(new EventStringifier(this)),
75     _sessionEventProcessor(new CoreSessionEventProcessor(this)),
76     _ctcpParser(new CtcpParser(this)),
77     _ircParser(new IrcParser(this)),
78     scriptEngine(new QScriptEngine(this)),
79     _processMessages(false),
80     _ignoreListManager(this)
81 {
82     SignalProxy *p = signalProxy();
83     p->setHeartBeatInterval(30);
84     p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
85
86     connect(p, SIGNAL(peerRemoved(Peer*)), SLOT(removeClient(Peer*)));
87
88     connect(p, SIGNAL(connected()), SLOT(clientsConnected()));
89     connect(p, SIGNAL(disconnected()), SLOT(clientsDisconnected()));
90
91     p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
92     p->attachSignal(this, SIGNAL(displayMsg(Message)));
93     p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
94
95     p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
96     p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
97     p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
98     p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
99
100     p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
101     p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
102     p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
103     p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
104
105     p->attachSlot(SIGNAL(changePassword(PeerPtr,QString,QString,QString)), this, SLOT(changePassword(PeerPtr,QString,QString,QString)));
106     p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr,bool)));
107
108     p->attachSlot(SIGNAL(kickClient(int)), this, SLOT(kickClient(int)));
109
110     loadSettings();
111     initScriptEngine();
112
113     eventManager()->registerObject(ircParser(), EventManager::NormalPriority);
114     eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
115     eventManager()->registerObject(ctcpParser(), EventManager::NormalPriority);
116     eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority);
117     eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
118     // some events need to be handled after msg generation
119     eventManager()->registerObject(sessionEventProcessor(), EventManager::LowPriority, "lateProcess");
120     eventManager()->registerObject(ctcpParser(), EventManager::LowPriority, "send");
121
122     // periodically save our session state
123     connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
124
125     p->synchronize(_bufferSyncer);
126     p->synchronize(&aliasManager());
127     p->synchronize(_backlogManager);
128     p->synchronize(dccConfig());
129     p->synchronize(ircListHelper());
130     p->synchronize(networkConfig());
131     p->synchronize(&_coreInfo);
132     p->synchronize(&_ignoreListManager);
133     p->synchronize(transferManager());
134     // Restore session state
135     if (restoreState)
136         restoreSessionState();
137
138     emit initialized();
139 }
140
141
142 CoreSession::~CoreSession()
143 {
144     saveSessionState();
145
146     /* Why partially duplicate CoreNetwork destructor?  When each CoreNetwork quits in the
147      * destructor, disconnections are processed in sequence for each object.  For many IRC servers
148      * on a slow network, this could significantly delay core shutdown [msecs wait * network count].
149      *
150      * Here, CoreSession first calls disconnect on all networks, letting them all start
151      * disconnecting before beginning to sequentially wait for each network.  Ideally, after the
152      * first network is disconnected, the other networks will have already closed.  Worst-case may
153      * still wait [msecs wait time * num. of networks], but the risk should be much lower.
154      *
155      * CoreNetwork should still do cleanup in its own destructor in case a network is deleted
156      * outside of deleting the whole CoreSession.
157      *
158      * If this proves to be problematic in the future, there's an alternative Qt signal-based system
159      * implemented in another pull request that guarentees a maximum amount of time to disconnect,
160      * but at the cost of more complex code.
161      *
162      * See https://github.com/quassel/quassel/pull/203
163      */
164
165     foreach(CoreNetwork *net, _networks.values()) {
166         // Request each network properly disconnect, but don't count as user-requested disconnect
167         if (net->socketConnected()) {
168             // Only try if the socket's fully connected (not initializing or disconnecting).
169             // Force an immediate disconnect, jumping the command queue.  Ensures the proper QUIT is
170             // shown even if other messages are queued.
171             net->disconnectFromIrc(false, QString(), false, true);
172         }
173     }
174
175     // Process the putCmd events that trigger the quit.  Without this, shutting down the core
176     // results in abrubtly closing the socket rather than sending the QUIT as expected.
177     QCoreApplication::processEvents();
178
179     foreach(CoreNetwork *net, _networks.values()) {
180         // Wait briefly for each network to disconnect.  Sometimes it takes a little while to send.
181         if (!net->forceDisconnect()) {
182             qWarning() << "Timed out quitting network" << net->networkName() <<
183                           "(user ID " << net->userId() << ")";
184         }
185         // Delete the network now that it's closed
186         delete net;
187     }
188 }
189
190
191 CoreNetwork *CoreSession::network(NetworkId id) const
192 {
193     if (_networks.contains(id)) return _networks[id];
194     return 0;
195 }
196
197
198 CoreIdentity *CoreSession::identity(IdentityId id) const
199 {
200     if (_identities.contains(id)) return _identities[id];
201     return 0;
202 }
203
204
205 void CoreSession::loadSettings()
206 {
207     CoreUserSettings s(user());
208
209     // migrate to db
210     QList<IdentityId> ids = s.identityIds();
211     QList<NetworkInfo> networkInfos = Core::networks(user());
212     foreach(IdentityId id, ids) {
213         CoreIdentity identity(s.identity(id));
214         IdentityId newId = Core::createIdentity(user(), identity);
215         QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
216         while (networkIter != networkInfos.end()) {
217             if (networkIter->identity == id) {
218                 networkIter->identity = newId;
219                 Core::updateNetwork(user(), *networkIter);
220                 networkIter = networkInfos.erase(networkIter);
221             }
222             else {
223                 ++networkIter;
224             }
225         }
226         s.removeIdentity(id);
227     }
228     // end of migration
229
230     foreach(CoreIdentity identity, Core::identities(user())) {
231         createIdentity(identity);
232     }
233
234     foreach(NetworkInfo info, Core::networks(user())) {
235         createNetwork(info);
236     }
237 }
238
239
240 void CoreSession::saveSessionState() const
241 {
242     _bufferSyncer->storeDirtyIds();
243     _bufferViewManager->saveBufferViews();
244     _networkConfig->save();
245 }
246
247
248 void CoreSession::restoreSessionState()
249 {
250     QList<NetworkId> nets = Core::connectedNetworks(user());
251     CoreNetwork *net = 0;
252     foreach(NetworkId id, nets) {
253         net = network(id);
254         Q_ASSERT(net);
255         net->connectToIrc();
256     }
257 }
258
259
260 void CoreSession::addClient(RemotePeer *peer)
261 {
262     peer->dispatch(sessionState());
263     signalProxy()->addPeer(peer);
264 }
265
266
267 void CoreSession::addClient(InternalPeer *peer)
268 {
269     signalProxy()->addPeer(peer);
270     emit sessionState(sessionState());
271 }
272
273
274 void CoreSession::removeClient(Peer *peer)
275 {
276     RemotePeer *p = qobject_cast<RemotePeer *>(peer);
277     if (p)
278         quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
279 }
280
281
282 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
283 {
284     return Core::persistentChannels(user(), id);
285 }
286
287
288 // FIXME switch to BufferId
289 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
290 {
291     CoreNetwork *net = network(bufinfo.networkId());
292     if (net) {
293         net->userInput(bufinfo, msg);
294     }
295     else {
296         qWarning() << "Trying to send to unconnected network:" << msg;
297     }
298 }
299
300
301 // ALL messages coming pass through these functions before going to the GUI.
302 // So this is the perfect place for storing the backlog and log stuff.
303 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
304     const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
305 {
306     // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
307     // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
308     // KDE's notifications), hence we remove those just to be safe.
309     QString text = text_;
310     text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
311     RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
312
313     // check for HardStrictness ignore
314     CoreNetwork *currentNetwork = network(networkId);
315     QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
316     if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
317         return;
318
319     _messageQueue << rawMsg;
320     if (!_processMessages) {
321         _processMessages = true;
322         QCoreApplication::postEvent(this, new ProcessMessagesEvent());
323     }
324 }
325
326
327 void CoreSession::recvStatusMsgFromServer(QString msg)
328 {
329     CoreNetwork *net = qobject_cast<CoreNetwork *>(sender());
330     Q_ASSERT(net);
331     emit displayStatusMsg(net->networkName(), msg);
332 }
333
334
335 void CoreSession::processMessageEvent(MessageEvent *event)
336 {
337     recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
338         event->target().isNull() ? "" : event->target(),
339         event->text().isNull() ? "" : event->text(),
340         event->sender().isNull() ? "" : event->sender(),
341         event->msgFlags());
342 }
343
344
345 QList<BufferInfo> CoreSession::buffers() const
346 {
347     return Core::requestBuffers(user());
348 }
349
350
351 void CoreSession::customEvent(QEvent *event)
352 {
353     if (event->type() != QEvent::User)
354         return;
355
356     processMessages();
357     event->accept();
358 }
359
360
361 void CoreSession::processMessages()
362 {
363     if (_messageQueue.count() == 1) {
364         const RawMessage &rawMsg = _messageQueue.first();
365         bool createBuffer = !(rawMsg.flags & Message::Redirected);
366         BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
367         if (!bufferInfo.isValid()) {
368             Q_ASSERT(!createBuffer);
369             bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
370         }
371         Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
372                     senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
373         if(Core::storeMessage(msg))
374             emit displayMsg(msg);
375     }
376     else {
377         QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
378         MessageList messages;
379         QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
380         BufferInfo bufferInfo;
381         for (int i = 0; i < _messageQueue.count(); i++) {
382             const RawMessage &rawMsg = _messageQueue.at(i);
383             if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
384                 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
385             }
386             else {
387                 bool createBuffer = !(rawMsg.flags & Message::Redirected);
388                 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
389                 if (!bufferInfo.isValid()) {
390                     Q_ASSERT(!createBuffer);
391                     redirectedMessages << rawMsg;
392                     continue;
393                 }
394                 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
395             }
396             Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
397                         senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
398             messages << msg;
399         }
400
401         // recheck if there exists a buffer to store a redirected message in
402         for (int i = 0; i < redirectedMessages.count(); i++) {
403             const RawMessage &rawMsg = redirectedMessages.at(i);
404             if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
405                 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
406             }
407             else {
408                 // no luck -> we store them in the StatusBuffer
409                 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
410                 // add the StatusBuffer to the Cache in case there are more Messages for the original target
411                 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
412             }
413             Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
414                         senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
415             messages << msg;
416         }
417
418         if(Core::storeMessages(messages)) {
419             // FIXME: extend protocol to a displayMessages(MessageList)
420             for (int i = 0; i < messages.count(); i++) {
421                 emit displayMsg(messages[i]);
422             }
423         }
424     }
425     _processMessages = false;
426     _messageQueue.clear();
427 }
428
429 QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const
430 {
431     CoreNetwork *currentNetwork = network(bufferInfo.networkId());
432     if (!currentNetwork) {
433         return {};
434     }
435
436     if (bufferInfo.type() != BufferInfo::ChannelBuffer) {
437         return {};
438     }
439
440     IrcChannel *currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName());
441     if (!currentChannel) {
442         return {};
443     }
444
445     const QString modes = currentChannel->userModes(nickFromMask(sender).toLower());
446     return currentNetwork->modesToPrefixes(modes);
447 }
448
449 Protocol::SessionState CoreSession::sessionState() const
450 {
451     QVariantList bufferInfos;
452     QVariantList networkIds;
453     QVariantList identities;
454
455     foreach(const BufferInfo &id, buffers())
456         bufferInfos << QVariant::fromValue(id);
457     foreach(const NetworkId &id, _networks.keys())
458         networkIds << QVariant::fromValue(id);
459     foreach(const Identity *i, _identities.values())
460         identities << QVariant::fromValue(*i);
461
462     return Protocol::SessionState(identities, bufferInfos, networkIds);
463 }
464
465
466 void CoreSession::initScriptEngine()
467 {
468     signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
469     signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
470
471     // FIXME
472     //QScriptValue storage_ = scriptEngine->newQObject(storage);
473     //scriptEngine->globalObject().setProperty("storage", storage_);
474 }
475
476
477 void CoreSession::scriptRequest(QString script)
478 {
479     emit scriptResult(scriptEngine->evaluate(script).toString());
480 }
481
482
483 /*** Identity Handling ***/
484 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
485 {
486 #ifndef HAVE_SSL
487     Q_UNUSED(additional)
488 #endif
489
490     CoreIdentity coreIdentity(identity);
491 #ifdef HAVE_SSL
492     if (additional.contains("KeyPem"))
493         coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
494     if (additional.contains("CertPem"))
495         coreIdentity.setSslCert(additional["CertPem"].toByteArray());
496 #endif
497     qDebug() << Q_FUNC_INFO;
498     IdentityId id = Core::createIdentity(user(), coreIdentity);
499     if (!id.isValid())
500         return;
501     else
502         createIdentity(coreIdentity);
503 }
504
505
506 void CoreSession::createIdentity(const CoreIdentity &identity)
507 {
508     CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
509     _identities[identity.id()] = coreIdentity;
510     // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
511     coreIdentity->synchronize(signalProxy());
512     connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
513     emit identityCreated(*coreIdentity);
514 }
515
516
517 void CoreSession::updateIdentityBySender()
518 {
519     CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
520     if (!identity)
521         return;
522     Core::updateIdentity(user(), *identity);
523 }
524
525
526 void CoreSession::removeIdentity(IdentityId id)
527 {
528     CoreIdentity *identity = _identities.take(id);
529     if (identity) {
530         emit identityRemoved(id);
531         Core::removeIdentity(user(), id);
532         identity->deleteLater();
533     }
534 }
535
536
537 /*** Network Handling ***/
538
539 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
540 {
541     NetworkInfo info = info_;
542     int id;
543
544     if (!info.networkId.isValid())
545         Core::createNetwork(user(), info);
546
547     if (!info.networkId.isValid()) {
548         qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
549         return;
550     }
551
552     id = info.networkId.toInt();
553     if (!_networks.contains(id)) {
554         // create persistent chans
555         QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
556         foreach(QString channel, persistentChans) {
557             if (!rx.exactMatch(channel)) {
558                 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
559                 continue;
560             }
561             Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
562             Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
563             if (!rx.cap(2).isEmpty())
564                 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
565         }
566
567         CoreNetwork *net = new CoreNetwork(id, this);
568         connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
569             SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
570         connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
571         connect(net, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
572
573         net->setNetworkInfo(info);
574         net->setProxy(signalProxy());
575         _networks[id] = net;
576         signalProxy()->synchronize(net);
577         emit networkCreated(id);
578     }
579     else {
580         qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
581         _networks[info.networkId]->requestSetNetworkInfo(info);
582     }
583 }
584
585
586 void CoreSession::removeNetwork(NetworkId id)
587 {
588     // Make sure the network is disconnected!
589     CoreNetwork *net = network(id);
590     if (!net)
591         return;
592
593     if (net->connectionState() != Network::Disconnected) {
594         // make sure we no longer receive data from the tcp buffer
595         disconnect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), this, 0);
596         disconnect(net, SIGNAL(displayStatusMsg(QString)), this, 0);
597         connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
598         net->disconnectFromIrc();
599     }
600     else {
601         destroyNetwork(id);
602     }
603 }
604
605
606 void CoreSession::destroyNetwork(NetworkId id)
607 {
608     QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
609     Network *net = _networks.take(id);
610     if (net && Core::removeNetwork(user(), id)) {
611         // make sure that all unprocessed RawMessages from this network are removed
612         QList<RawMessage>::iterator messageIter = _messageQueue.begin();
613         while (messageIter != _messageQueue.end()) {
614             if (messageIter->networkId == id) {
615                 messageIter = _messageQueue.erase(messageIter);
616             }
617             else {
618                 ++messageIter;
619             }
620         }
621         // remove buffers from syncer
622         foreach(BufferId bufferId, removedBuffers) {
623             _bufferSyncer->removeBuffer(bufferId);
624         }
625         emit networkRemoved(id);
626         net->deleteLater();
627     }
628 }
629
630
631 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
632 {
633     BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
634     if (bufferInfo.isValid()) {
635         _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
636     }
637 }
638
639
640 void CoreSession::clientsConnected()
641 {
642     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
643     Identity *identity = 0;
644     CoreNetwork *net = 0;
645     IrcUser *me = 0;
646     while (netIter != _networks.end()) {
647         net = *netIter;
648         ++netIter;
649
650         if (!net->isConnected())
651             continue;
652         identity = net->identityPtr();
653         if (!identity)
654             continue;
655         me = net->me();
656         if (!me)
657             continue;
658
659         if (identity->detachAwayEnabled() && me->isAway()) {
660             net->userInputHandler()->handleAway(BufferInfo(), QString());
661         }
662     }
663 }
664
665
666 void CoreSession::clientsDisconnected()
667 {
668     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
669     Identity *identity = 0;
670     CoreNetwork *net = 0;
671     IrcUser *me = 0;
672     QString awayReason;
673     while (netIter != _networks.end()) {
674         net = *netIter;
675         ++netIter;
676
677         if (!net->isConnected())
678             continue;
679
680         identity = net->identityPtr();
681         if (!identity)
682             continue;
683         me = net->me();
684         if (!me)
685             continue;
686
687         if (identity->detachAwayEnabled() && !me->isAway()) {
688             if (!identity->detachAwayReason().isEmpty())
689                 awayReason = identity->detachAwayReason();
690             net->setAutoAwayActive(true);
691             // Allow handleAway() to format the current date/time in the string.
692             net->userInputHandler()->handleAway(BufferInfo(), awayReason);
693         }
694     }
695 }
696
697
698 void CoreSession::globalAway(const QString &msg, const bool skipFormatting)
699 {
700     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
701     CoreNetwork *net = 0;
702     while (netIter != _networks.end()) {
703         net = *netIter;
704         ++netIter;
705
706         if (!net->isConnected())
707             continue;
708
709         net->userInputHandler()->issueAway(msg, false /* no force away */, skipFormatting);
710     }
711 }
712
713 void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword)
714 {
715     bool success = false;
716     UserId uid = Core::validateUser(userName, oldPassword);
717     if (uid.isValid() && uid == user())
718         success = Core::changeUserPassword(uid, newPassword);
719
720     emit passwordChanged(peer, success);
721 }
722
723 void CoreSession::kickClient(int peerId) {
724     auto peer = signalProxy()->peerById(peerId);
725     if (!peer) {
726         qWarning() << "Invalid peer Id: " << peerId;
727     }
728     peer->close("Terminated by user action");
729 }