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