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