64f46088cee5bc70908f91d2c8534fe890ce0664
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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     signalProxy()->setTargetPeer(peer);
266
267     peer->dispatch(sessionState());
268     signalProxy()->addPeer(peer);
269
270     signalProxy()->setTargetPeer(nullptr);
271 }
272
273
274 void CoreSession::addClient(InternalPeer *peer)
275 {
276     signalProxy()->addPeer(peer);
277     emit sessionState(sessionState());
278 }
279
280
281 void CoreSession::removeClient(Peer *peer)
282 {
283     RemotePeer *p = qobject_cast<RemotePeer *>(peer);
284     if (p)
285         quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
286 }
287
288
289 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
290 {
291     return Core::persistentChannels(user(), id);
292 }
293
294
295 QHash<QString, QByteArray> CoreSession::bufferCiphers(NetworkId id) const
296 {
297     return Core::bufferCiphers(user(), id);
298 }
299
300 void CoreSession::setBufferCipher(NetworkId id, const QString &bufferName, const QByteArray &cipher) const
301 {
302     Core::setBufferCipher(user(), id, bufferName, cipher);
303 }
304
305
306 // FIXME switch to BufferId
307 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
308 {
309     CoreNetwork *net = network(bufinfo.networkId());
310     if (net) {
311         net->userInput(bufinfo, msg);
312     }
313     else {
314         qWarning() << "Trying to send to unconnected network:" << msg;
315     }
316 }
317
318
319 // ALL messages coming pass through these functions before going to the GUI.
320 // So this is the perfect place for storing the backlog and log stuff.
321 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
322     const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
323 {
324     // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
325     // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
326     // KDE's notifications), hence we remove those just to be safe.
327     QString text = text_;
328     text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
329     RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
330
331     // check for HardStrictness ignore
332     CoreNetwork *currentNetwork = network(networkId);
333     QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
334     if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
335         return;
336
337     if (_highlightRuleManager.match(rawMsg, currentNetwork->myNick(), currentNetwork->identityPtr()->nicks()))
338         rawMsg.flags |= Message::Flag::Highlight;
339
340     _messageQueue << rawMsg;
341     if (!_processMessages) {
342         _processMessages = true;
343         QCoreApplication::postEvent(this, new ProcessMessagesEvent());
344     }
345 }
346
347
348 void CoreSession::recvStatusMsgFromServer(QString msg)
349 {
350     CoreNetwork *net = qobject_cast<CoreNetwork *>(sender());
351     Q_ASSERT(net);
352     emit displayStatusMsg(net->networkName(), msg);
353 }
354
355
356 void CoreSession::processMessageEvent(MessageEvent *event)
357 {
358     recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
359         event->target().isNull() ? "" : event->target(),
360         event->text().isNull() ? "" : event->text(),
361         event->sender().isNull() ? "" : event->sender(),
362         event->msgFlags());
363 }
364
365
366 QList<BufferInfo> CoreSession::buffers() const
367 {
368     return Core::requestBuffers(user());
369 }
370
371
372 void CoreSession::customEvent(QEvent *event)
373 {
374     if (event->type() != QEvent::User)
375         return;
376
377     processMessages();
378     event->accept();
379 }
380
381
382 void CoreSession::processMessages()
383 {
384     if (_messageQueue.count() == 1) {
385         const RawMessage &rawMsg = _messageQueue.first();
386         bool createBuffer = !(rawMsg.flags & Message::Redirected);
387         BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
388         if (!bufferInfo.isValid()) {
389             Q_ASSERT(!createBuffer);
390             bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
391         }
392         Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo),
393                     realName(rawMsg.sender, rawMsg.networkId),  avatarUrl(rawMsg.sender, rawMsg.networkId),
394                     rawMsg.flags);
395         if(Core::storeMessage(msg))
396             emit displayMsg(msg);
397     }
398     else {
399         QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
400         MessageList messages;
401         QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
402         BufferInfo bufferInfo;
403         for (int i = 0; i < _messageQueue.count(); i++) {
404             const RawMessage &rawMsg = _messageQueue.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                 bool createBuffer = !(rawMsg.flags & Message::Redirected);
410                 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
411                 if (!bufferInfo.isValid()) {
412                     Q_ASSERT(!createBuffer);
413                     redirectedMessages << rawMsg;
414                     continue;
415                 }
416                 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
417             }
418             Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo),
419                         realName(rawMsg.sender, rawMsg.networkId),  avatarUrl(rawMsg.sender, rawMsg.networkId),
420                         rawMsg.flags);
421             messages << msg;
422         }
423
424         // recheck if there exists a buffer to store a redirected message in
425         for (int i = 0; i < redirectedMessages.count(); i++) {
426             const RawMessage &rawMsg = redirectedMessages.at(i);
427             if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
428                 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
429             }
430             else {
431                 // no luck -> we store them in the StatusBuffer
432                 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
433                 // add the StatusBuffer to the Cache in case there are more Messages for the original target
434                 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
435             }
436             Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo),
437                         realName(rawMsg.sender, rawMsg.networkId),  avatarUrl(rawMsg.sender, rawMsg.networkId),
438                         rawMsg.flags);
439             messages << msg;
440         }
441
442         if(Core::storeMessages(messages)) {
443             // FIXME: extend protocol to a displayMessages(MessageList)
444             for (int i = 0; i < messages.count(); i++) {
445                 emit displayMsg(messages[i]);
446             }
447         }
448     }
449     _processMessages = false;
450     _messageQueue.clear();
451 }
452
453 QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const
454 {
455     CoreNetwork *currentNetwork = network(bufferInfo.networkId());
456     if (!currentNetwork) {
457         return {};
458     }
459
460     if (bufferInfo.type() != BufferInfo::ChannelBuffer) {
461         return {};
462     }
463
464     IrcChannel *currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName());
465     if (!currentChannel) {
466         return {};
467     }
468
469     const QString modes = currentChannel->userModes(nickFromMask(sender).toLower());
470     return currentNetwork->modesToPrefixes(modes);
471 }
472
473 QString CoreSession::realName(const QString &sender, NetworkId networkId) const
474 {
475     CoreNetwork *currentNetwork = network(networkId);
476     if (!currentNetwork) {
477         return {};
478     }
479
480     IrcUser *currentUser = currentNetwork->ircUser(nickFromMask(sender));
481     if (!currentUser) {
482         return {};
483     }
484
485     return currentUser->realName();
486 }
487
488 QString CoreSession::avatarUrl(const QString &sender, NetworkId networkId) const
489 {
490     Q_UNUSED(sender);
491     Q_UNUSED(networkId);
492     // Currently we do not have a way to retrieve this value yet.
493     //
494     // This likely will require implementing IRCv3's METADATA spec.
495     // See https://ircv3.net/irc/
496     // And https://blog.irccloud.com/avatars/
497     return "";
498 }
499
500 Protocol::SessionState CoreSession::sessionState() const
501 {
502     QVariantList bufferInfos;
503     QVariantList networkIds;
504     QVariantList identities;
505
506     foreach(const BufferInfo &id, buffers())
507         bufferInfos << QVariant::fromValue(id);
508     foreach(const NetworkId &id, _networks.keys())
509         networkIds << QVariant::fromValue(id);
510     foreach(const Identity *i, _identities.values())
511         identities << QVariant::fromValue(*i);
512
513     return Protocol::SessionState(identities, bufferInfos, networkIds);
514 }
515
516
517 void CoreSession::initScriptEngine()
518 {
519     signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
520     signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
521
522     // FIXME
523     //QScriptValue storage_ = scriptEngine->newQObject(storage);
524     //scriptEngine->globalObject().setProperty("storage", storage_);
525 }
526
527
528 void CoreSession::scriptRequest(QString script)
529 {
530     emit scriptResult(scriptEngine->evaluate(script).toString());
531 }
532
533
534 /*** Identity Handling ***/
535 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
536 {
537 #ifndef HAVE_SSL
538     Q_UNUSED(additional)
539 #endif
540
541     CoreIdentity coreIdentity(identity);
542 #ifdef HAVE_SSL
543     if (additional.contains("KeyPem"))
544         coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
545     if (additional.contains("CertPem"))
546         coreIdentity.setSslCert(additional["CertPem"].toByteArray());
547 #endif
548     qDebug() << Q_FUNC_INFO;
549     IdentityId id = Core::createIdentity(user(), coreIdentity);
550     if (!id.isValid())
551         return;
552     else
553         createIdentity(coreIdentity);
554 }
555
556 const QString CoreSession::strictSysident() {
557     return Core::instance()->strictSysIdent(_user);
558 }
559
560 void CoreSession::createIdentity(const CoreIdentity &identity)
561 {
562     CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
563     _identities[identity.id()] = coreIdentity;
564     // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
565     coreIdentity->synchronize(signalProxy());
566     connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
567     emit identityCreated(*coreIdentity);
568 }
569
570
571 void CoreSession::updateIdentityBySender()
572 {
573     CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
574     if (!identity)
575         return;
576     Core::updateIdentity(user(), *identity);
577 }
578
579
580 void CoreSession::removeIdentity(IdentityId id)
581 {
582     CoreIdentity *identity = _identities.take(id);
583     if (identity) {
584         emit identityRemoved(id);
585         Core::removeIdentity(user(), id);
586         identity->deleteLater();
587     }
588 }
589
590
591 /*** Network Handling ***/
592
593 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
594 {
595     NetworkInfo info = info_;
596     int id;
597
598     if (!info.networkId.isValid())
599         Core::createNetwork(user(), info);
600
601     if (!info.networkId.isValid()) {
602         qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
603         return;
604     }
605
606     id = info.networkId.toInt();
607     if (!_networks.contains(id)) {
608         // create persistent chans
609         QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
610         foreach(QString channel, persistentChans) {
611             if (!rx.exactMatch(channel)) {
612                 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
613                 continue;
614             }
615             Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
616             Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
617             if (!rx.cap(2).isEmpty())
618                 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
619         }
620
621         CoreNetwork *net = new CoreNetwork(id, this);
622         connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
623             SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
624         connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
625         connect(net, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
626
627         net->setNetworkInfo(info);
628         net->setProxy(signalProxy());
629         _networks[id] = net;
630         signalProxy()->synchronize(net);
631         emit networkCreated(id);
632     }
633     else {
634         qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
635         _networks[info.networkId]->requestSetNetworkInfo(info);
636     }
637 }
638
639
640 void CoreSession::removeNetwork(NetworkId id)
641 {
642     // Make sure the network is disconnected!
643     CoreNetwork *net = network(id);
644     if (!net)
645         return;
646
647     if (net->connectionState() != Network::Disconnected) {
648         // make sure we no longer receive data from the tcp buffer
649         disconnect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), this, 0);
650         disconnect(net, SIGNAL(displayStatusMsg(QString)), this, 0);
651         connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
652         net->disconnectFromIrc();
653     }
654     else {
655         destroyNetwork(id);
656     }
657 }
658
659
660 void CoreSession::destroyNetwork(NetworkId id)
661 {
662     QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
663     Network *net = _networks.take(id);
664     if (net && Core::removeNetwork(user(), id)) {
665         // make sure that all unprocessed RawMessages from this network are removed
666         QList<RawMessage>::iterator messageIter = _messageQueue.begin();
667         while (messageIter != _messageQueue.end()) {
668             if (messageIter->networkId == id) {
669                 messageIter = _messageQueue.erase(messageIter);
670             }
671             else {
672                 ++messageIter;
673             }
674         }
675         // remove buffers from syncer
676         foreach(BufferId bufferId, removedBuffers) {
677             _bufferSyncer->removeBuffer(bufferId);
678         }
679         emit networkRemoved(id);
680         net->deleteLater();
681     }
682 }
683
684
685 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
686 {
687     BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
688     if (bufferInfo.isValid()) {
689         _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
690     }
691 }
692
693
694 void CoreSession::clientsConnected()
695 {
696     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
697     Identity *identity = 0;
698     CoreNetwork *net = 0;
699     IrcUser *me = 0;
700     while (netIter != _networks.end()) {
701         net = *netIter;
702         ++netIter;
703
704         if (!net->isConnected())
705             continue;
706         identity = net->identityPtr();
707         if (!identity)
708             continue;
709         me = net->me();
710         if (!me)
711             continue;
712
713         if (identity->detachAwayEnabled() && me->isAway()) {
714             net->userInputHandler()->handleAway(BufferInfo(), QString());
715         }
716     }
717 }
718
719
720 void CoreSession::clientsDisconnected()
721 {
722     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
723     Identity *identity = 0;
724     CoreNetwork *net = 0;
725     IrcUser *me = 0;
726     QString awayReason;
727     while (netIter != _networks.end()) {
728         net = *netIter;
729         ++netIter;
730
731         if (!net->isConnected())
732             continue;
733
734         identity = net->identityPtr();
735         if (!identity)
736             continue;
737         me = net->me();
738         if (!me)
739             continue;
740
741         if (identity->detachAwayEnabled() && !me->isAway()) {
742             if (!identity->detachAwayReason().isEmpty())
743                 awayReason = identity->detachAwayReason();
744             net->setAutoAwayActive(true);
745             // Allow handleAway() to format the current date/time in the string.
746             net->userInputHandler()->handleAway(BufferInfo(), awayReason);
747         }
748     }
749 }
750
751
752 void CoreSession::globalAway(const QString &msg, const bool skipFormatting)
753 {
754     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
755     CoreNetwork *net = 0;
756     while (netIter != _networks.end()) {
757         net = *netIter;
758         ++netIter;
759
760         if (!net->isConnected())
761             continue;
762
763         net->userInputHandler()->issueAway(msg, false /* no force away */, skipFormatting);
764     }
765 }
766
767 void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword) {
768     Q_UNUSED(peer);
769
770     bool success = false;
771     UserId uid = Core::validateUser(userName, oldPassword);
772     if (uid.isValid() && uid == user())
773         success = Core::changeUserPassword(uid, newPassword);
774
775     signalProxy()->restrictTargetPeers(signalProxy()->sourcePeer(), [&]{
776         emit passwordChanged(nullptr, success);
777     });
778 }
779
780 void CoreSession::kickClient(int peerId) {
781     auto peer = signalProxy()->peerById(peerId);
782     if (peer == nullptr) {
783         qWarning() << "Invalid peer Id: " << peerId;
784         return;
785     }
786     signalProxy()->restrictTargetPeers(peer, [&]{
787         emit disconnectFromCore();
788     });
789 }