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