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