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