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