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