1 /***************************************************************************
2 * Copyright (C) 2005-2019 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
29 QTextCodec* Network::_defaultCodecForServer = nullptr;
30 QTextCodec* Network::_defaultCodecForEncoding = nullptr;
31 QTextCodec* Network::_defaultCodecForDecoding = nullptr;
33 // ====================
35 // ====================
37 Network::Network(const NetworkId& networkid, QObject* parent)
38 : SyncableObject(parent)
40 , _networkId(networkid)
44 , _networkName(QString("<not initialized>"))
45 , _currentServer(QString())
47 , _connectionState(Disconnected)
48 , _prefixes(QString())
49 , _prefixModes(QString())
50 , _useRandomServer(false)
51 , _useAutoIdentify(false)
53 , _useAutoReconnect(false)
54 , _autoReconnectInterval(60)
55 , _autoReconnectRetries(10)
56 , _unlimitedReconnectRetries(false)
57 , _useCustomMessageRate(false)
58 , _messageRateBurstSize(5)
59 , _messageRateDelay(2200)
60 , _unlimitedMessageRate(false)
61 , _codecForServer(nullptr)
62 , _codecForEncoding(nullptr)
63 , _codecForDecoding(nullptr)
64 , _autoAwayActive(false)
66 setObjectName(QString::number(networkid.toInt()));
71 emit aboutToBeDestroyed();
74 bool Network::isChannelName(const QString& channelname) const
76 if (channelname.isEmpty())
79 if (supports("CHANTYPES"))
80 return support("CHANTYPES").contains(channelname[0]);
82 return QString("#&!+").contains(channelname[0]);
85 bool Network::isStatusMsg(const QString& target) const
90 if (supports("STATUSMSG"))
91 return support("STATUSMSG").contains(target[0]);
93 return QString("@+").contains(target[0]);
96 NetworkInfo Network::networkInfo() const
99 info.networkName = networkName();
100 info.networkId = networkId();
101 info.identity = identity();
102 info.codecForServer = codecForServer();
103 info.codecForEncoding = codecForEncoding();
104 info.codecForDecoding = codecForDecoding();
105 info.serverList = serverList();
106 info.useRandomServer = useRandomServer();
107 info.perform = perform();
108 info.useAutoIdentify = useAutoIdentify();
109 info.autoIdentifyService = autoIdentifyService();
110 info.autoIdentifyPassword = autoIdentifyPassword();
111 info.useSasl = useSasl();
112 info.saslAccount = saslAccount();
113 info.saslPassword = saslPassword();
114 info.useAutoReconnect = useAutoReconnect();
115 info.autoReconnectInterval = autoReconnectInterval();
116 info.autoReconnectRetries = autoReconnectRetries();
117 info.unlimitedReconnectRetries = unlimitedReconnectRetries();
118 info.rejoinChannels = rejoinChannels();
119 info.useCustomMessageRate = useCustomMessageRate();
120 info.messageRateBurstSize = messageRateBurstSize();
121 info.messageRateDelay = messageRateDelay();
122 info.unlimitedMessageRate = unlimitedMessageRate();
126 void Network::setNetworkInfo(const NetworkInfo& info)
128 // we don't set our ID!
129 if (!info.networkName.isEmpty() && info.networkName != networkName())
130 setNetworkName(info.networkName);
131 if (info.identity > 0 && info.identity != identity())
132 setIdentity(info.identity);
133 if (info.codecForServer != codecForServer())
134 setCodecForServer(QTextCodec::codecForName(info.codecForServer));
135 if (info.codecForEncoding != codecForEncoding())
136 setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
137 if (info.codecForDecoding != codecForDecoding())
138 setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
139 if (info.serverList.count())
140 setServerList(toVariantList(info.serverList)); // FIXME compare components
141 if (info.useRandomServer != useRandomServer())
142 setUseRandomServer(info.useRandomServer);
143 if (info.perform != perform())
144 setPerform(info.perform);
145 if (info.useAutoIdentify != useAutoIdentify())
146 setUseAutoIdentify(info.useAutoIdentify);
147 if (info.autoIdentifyService != autoIdentifyService())
148 setAutoIdentifyService(info.autoIdentifyService);
149 if (info.autoIdentifyPassword != autoIdentifyPassword())
150 setAutoIdentifyPassword(info.autoIdentifyPassword);
151 if (info.useSasl != useSasl())
152 setUseSasl(info.useSasl);
153 if (info.saslAccount != saslAccount())
154 setSaslAccount(info.saslAccount);
155 if (info.saslPassword != saslPassword())
156 setSaslPassword(info.saslPassword);
157 if (info.useAutoReconnect != useAutoReconnect())
158 setUseAutoReconnect(info.useAutoReconnect);
159 if (info.autoReconnectInterval != autoReconnectInterval())
160 setAutoReconnectInterval(info.autoReconnectInterval);
161 if (info.autoReconnectRetries != autoReconnectRetries())
162 setAutoReconnectRetries(info.autoReconnectRetries);
163 if (info.unlimitedReconnectRetries != unlimitedReconnectRetries())
164 setUnlimitedReconnectRetries(info.unlimitedReconnectRetries);
165 if (info.rejoinChannels != rejoinChannels())
166 setRejoinChannels(info.rejoinChannels);
167 // Custom rate limiting
168 if (info.useCustomMessageRate != useCustomMessageRate())
169 setUseCustomMessageRate(info.useCustomMessageRate);
170 if (info.messageRateBurstSize != messageRateBurstSize())
171 setMessageRateBurstSize(info.messageRateBurstSize);
172 if (info.messageRateDelay != messageRateDelay())
173 setMessageRateDelay(info.messageRateDelay);
174 if (info.unlimitedMessageRate != unlimitedMessageRate())
175 setUnlimitedMessageRate(info.unlimitedMessageRate);
178 QString Network::prefixToMode(const QString& prefix) const
180 if (prefixes().contains(prefix))
181 return QString(prefixModes()[prefixes().indexOf(prefix)]);
186 QString Network::modeToPrefix(const QString& mode) const
188 if (prefixModes().contains(mode))
189 return QString(prefixes()[prefixModes().indexOf(mode)]);
194 QString Network::sortPrefixModes(const QString& modes) const
196 // If modes is empty or we don't have any modes, nothing can be sorted, bail out early
197 if (modes.isEmpty() || prefixModes().isEmpty()) {
201 // Store a copy of the modes for modification
202 // QString should be efficient and not copy memory if nothing changes, but if mistaken,
203 // std::is_sorted could be called first.
204 QString sortedModes = QString(modes);
206 // Sort modes as if a QChar array
207 // See https://en.cppreference.com/w/cpp/algorithm/sort
208 // Defining lambda with [&] implicitly captures variables by reference
209 std::sort(sortedModes.begin(), sortedModes.end(), [&](const QChar& lmode, const QChar& rmode) {
210 // Compare characters according to prefix modes
211 // Return true if lmode comes before rmode (is "less than")
213 // Check for unknown modes...
214 if (!prefixModes().contains(lmode)) {
215 // Left mode not in prefix list, send to end
218 else if (!prefixModes().contains(rmode)) {
219 // Right mode not in prefix list, send to end
223 // Both characters known, sort according to index in prefixModes()
224 return (prefixModes().indexOf(lmode) < prefixModes().indexOf(rmode));
231 QStringList Network::nicks() const
233 // we don't use _ircUsers.keys() since the keys may be
234 // not up to date after a nick change
236 foreach (IrcUser* ircuser, _ircUsers.values()) {
237 nicks << ircuser->nick();
242 QString Network::prefixes() const
244 if (_prefixes.isNull())
250 QString Network::prefixModes() const
252 if (_prefixModes.isNull())
258 // example Unreal IRCD: CHANMODES=beI,kfL,lj,psmntirRcOAQKVCuzNSMTG
259 Network::ChannelModeType Network::channelModeType(const QString& mode)
262 return NOT_A_CHANMODE;
264 QString chanmodes = support("CHANMODES");
265 if (chanmodes.isEmpty())
266 return NOT_A_CHANMODE;
268 ChannelModeType modeType = A_CHANMODE;
269 for (int i = 0; i < chanmodes.count(); i++) {
270 if (chanmodes[i] == mode[0])
272 else if (chanmodes[i] == ',')
273 modeType = (ChannelModeType)(modeType << 1);
275 if (modeType > D_CHANMODE) {
276 qWarning() << "Network" << networkId() << "supplied invalid CHANMODES:" << chanmodes;
277 modeType = NOT_A_CHANMODE;
282 QString Network::support(const QString& param) const
284 QString support_ = param.toUpper();
285 if (_supports.contains(support_))
286 return _supports[support_];
291 bool Network::saslMaybeSupports(const QString& saslMechanism) const
293 if (!capAvailable(IrcCap::SASL)) {
294 // If SASL's not advertised at all, it's likely the mechanism isn't supported, as per specs.
295 // Unfortunately, we don't know for sure, but Quassel won't request SASL without it being
296 // advertised, anyways.
297 // This may also occur if the network's disconnected or negotiation hasn't yet happened.
301 // Get the SASL capability value
302 QString saslCapValue = capValue(IrcCap::SASL);
303 // SASL mechanisms are only specified in capability values as part of SASL 3.2. In SASL 3.1,
304 // it's handled differently. If we don't know via capability value, assume it's supported to
305 // reduce the risk of breaking existing setups.
306 // See: http://ircv3.net/specs/extensions/sasl-3.1.html
307 // And: http://ircv3.net/specs/extensions/sasl-3.2.html
308 return (saslCapValue.length() == 0) || (saslCapValue.contains(saslMechanism, Qt::CaseInsensitive));
311 IrcUser* Network::newIrcUser(const QString& hostmask, const QVariantMap& initData)
313 QString nick(nickFromMask(hostmask).toLower());
314 if (!_ircUsers.contains(nick)) {
315 IrcUser* ircuser = ircUserFactory(hostmask);
316 if (!initData.isEmpty()) {
317 ircuser->fromVariantMap(initData);
318 ircuser->setInitialized();
322 proxy()->synchronize(ircuser);
324 qWarning() << "unable to synchronize new IrcUser" << hostmask << "forgot to call Network::setProxy(SignalProxy *)?";
326 connect(ircuser, &IrcUser::nickSet, this, &Network::ircUserNickChanged);
328 _ircUsers[nick] = ircuser;
330 // This method will be called with a nick instead of hostmask by setInitIrcUsersAndChannels().
331 // Not a problem because initData contains all we need; however, making sure here to get the real
332 // hostmask out of the IrcUser afterwards.
333 QString mask = ircuser->hostmask();
334 SYNC_OTHER(addIrcUser, ARG(mask));
335 // emit ircUserAdded(mask);
336 emit ircUserAdded(ircuser);
339 return _ircUsers[nick];
342 IrcUser* Network::ircUser(QString nickname) const
344 nickname = nickname.toLower();
345 if (_ircUsers.contains(nickname))
346 return _ircUsers[nickname];
351 void Network::removeIrcUser(IrcUser* ircuser)
353 QString nick = _ircUsers.key(ircuser);
357 _ircUsers.remove(nick);
358 disconnect(ircuser, nullptr, this, nullptr);
359 ircuser->deleteLater();
362 void Network::removeIrcChannel(IrcChannel* channel)
364 QString chanName = _ircChannels.key(channel);
365 if (chanName.isNull())
368 _ircChannels.remove(chanName);
369 disconnect(channel, nullptr, this, nullptr);
370 channel->deleteLater();
373 void Network::removeChansAndUsers()
375 QList<IrcUser*> users = ircUsers();
377 QList<IrcChannel*> channels = ircChannels();
378 _ircChannels.clear();
381 qDeleteAll(channels);
384 IrcChannel* Network::newIrcChannel(const QString& channelname, const QVariantMap& initData)
386 if (!_ircChannels.contains(channelname.toLower())) {
387 IrcChannel* channel = ircChannelFactory(channelname);
388 if (!initData.isEmpty()) {
389 channel->fromVariantMap(initData);
390 channel->setInitialized();
394 proxy()->synchronize(channel);
396 qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
398 _ircChannels[channelname.toLower()] = channel;
400 SYNC_OTHER(addIrcChannel, ARG(channelname))
401 // emit ircChannelAdded(channelname);
402 emit ircChannelAdded(channel);
404 return _ircChannels[channelname.toLower()];
407 IrcChannel* Network::ircChannel(QString channelname) const
409 channelname = channelname.toLower();
410 if (_ircChannels.contains(channelname))
411 return _ircChannels[channelname];
416 QByteArray Network::defaultCodecForServer()
418 if (_defaultCodecForServer)
419 return _defaultCodecForServer->name();
423 void Network::setDefaultCodecForServer(const QByteArray& name)
425 _defaultCodecForServer = QTextCodec::codecForName(name);
428 QByteArray Network::defaultCodecForEncoding()
430 if (_defaultCodecForEncoding)
431 return _defaultCodecForEncoding->name();
435 void Network::setDefaultCodecForEncoding(const QByteArray& name)
437 _defaultCodecForEncoding = QTextCodec::codecForName(name);
440 QByteArray Network::defaultCodecForDecoding()
442 if (_defaultCodecForDecoding)
443 return _defaultCodecForDecoding->name();
447 void Network::setDefaultCodecForDecoding(const QByteArray& name)
449 _defaultCodecForDecoding = QTextCodec::codecForName(name);
452 QByteArray Network::codecForServer() const
455 return _codecForServer->name();
459 void Network::setCodecForServer(const QByteArray& name)
461 setCodecForServer(QTextCodec::codecForName(name));
464 void Network::setCodecForServer(QTextCodec* codec)
466 _codecForServer = codec;
467 QByteArray codecName = codecForServer();
468 SYNC_OTHER(setCodecForServer, ARG(codecName))
469 emit configChanged();
472 QByteArray Network::codecForEncoding() const
474 if (_codecForEncoding)
475 return _codecForEncoding->name();
479 void Network::setCodecForEncoding(const QByteArray& name)
481 setCodecForEncoding(QTextCodec::codecForName(name));
484 void Network::setCodecForEncoding(QTextCodec* codec)
486 _codecForEncoding = codec;
487 QByteArray codecName = codecForEncoding();
488 SYNC_OTHER(setCodecForEncoding, ARG(codecName))
489 emit configChanged();
492 QByteArray Network::codecForDecoding() const
494 if (_codecForDecoding)
495 return _codecForDecoding->name();
500 void Network::setCodecForDecoding(const QByteArray& name)
502 setCodecForDecoding(QTextCodec::codecForName(name));
505 void Network::setCodecForDecoding(QTextCodec* codec)
507 _codecForDecoding = codec;
508 QByteArray codecName = codecForDecoding();
509 SYNC_OTHER(setCodecForDecoding, ARG(codecName))
510 emit configChanged();
513 // FIXME use server encoding if appropriate
514 QString Network::decodeString(const QByteArray& text) const
516 if (_codecForDecoding)
517 return ::decodeString(text, _codecForDecoding);
519 return ::decodeString(text, _defaultCodecForDecoding);
522 QByteArray Network::encodeString(const QString& string) const
524 if (_codecForEncoding) {
525 return _codecForEncoding->fromUnicode(string);
527 if (_defaultCodecForEncoding) {
528 return _defaultCodecForEncoding->fromUnicode(string);
530 return string.toLatin1();
533 QString Network::decodeServerString(const QByteArray& text) const
536 return ::decodeString(text, _codecForServer);
538 return ::decodeString(text, _defaultCodecForServer);
541 QByteArray Network::encodeServerString(const QString& string) const
543 if (_codecForServer) {
544 return _codecForServer->fromUnicode(string);
546 if (_defaultCodecForServer) {
547 return _defaultCodecForServer->fromUnicode(string);
549 return string.toLatin1();
552 // ====================
554 // ====================
555 void Network::setNetworkName(const QString& networkName)
557 _networkName = networkName;
558 SYNC(ARG(networkName))
559 emit networkNameSet(networkName);
560 emit configChanged();
563 void Network::setCurrentServer(const QString& currentServer)
565 _currentServer = currentServer;
566 SYNC(ARG(currentServer))
567 emit currentServerSet(currentServer);
570 void Network::setConnected(bool connected)
572 if (_connected == connected)
575 _connected = connected;
577 setMyNick(QString());
578 setCurrentServer(QString());
579 removeChansAndUsers();
582 emit connectedSet(connected);
585 // void Network::setConnectionState(ConnectionState state) {
586 void Network::setConnectionState(int state)
588 _connectionState = (ConnectionState)state;
589 // qDebug() << "netstate" << networkId() << networkName() << state;
591 emit connectionStateSet(_connectionState);
594 void Network::setMyNick(const QString& nickname)
597 if (!_myNick.isEmpty() && !ircUser(myNick())) {
598 newIrcUser(myNick());
601 emit myNickSet(nickname);
604 void Network::setLatency(int latency)
606 if (_latency == latency)
612 void Network::setIdentity(IdentityId id)
616 emit identitySet(id);
617 emit configChanged();
620 void Network::setServerList(const QVariantList& serverList)
622 _serverList = fromVariantList<Server>(serverList);
623 SYNC(ARG(serverList))
624 emit configChanged();
627 void Network::setUseRandomServer(bool use)
629 _useRandomServer = use;
631 emit configChanged();
634 void Network::setPerform(const QStringList& perform)
638 emit configChanged();
641 void Network::setUseAutoIdentify(bool use)
643 _useAutoIdentify = use;
645 emit configChanged();
648 void Network::setAutoIdentifyService(const QString& service)
650 _autoIdentifyService = service;
652 emit configChanged();
655 void Network::setAutoIdentifyPassword(const QString& password)
657 _autoIdentifyPassword = password;
659 emit configChanged();
662 void Network::setUseSasl(bool use)
666 emit configChanged();
669 void Network::setSaslAccount(const QString& account)
671 _saslAccount = account;
673 emit configChanged();
676 void Network::setSaslPassword(const QString& password)
678 _saslPassword = password;
680 emit configChanged();
683 void Network::setUseAutoReconnect(bool use)
685 _useAutoReconnect = use;
687 emit configChanged();
690 void Network::setAutoReconnectInterval(quint32 interval)
692 _autoReconnectInterval = interval;
694 emit configChanged();
697 void Network::setAutoReconnectRetries(quint16 retries)
699 _autoReconnectRetries = retries;
701 emit configChanged();
704 void Network::setUnlimitedReconnectRetries(bool unlimited)
706 _unlimitedReconnectRetries = unlimited;
708 emit configChanged();
711 void Network::setRejoinChannels(bool rejoin)
713 _rejoinChannels = rejoin;
715 emit configChanged();
718 void Network::setUseCustomMessageRate(bool useCustomRate)
720 if (_useCustomMessageRate != useCustomRate) {
721 _useCustomMessageRate = useCustomRate;
722 SYNC(ARG(useCustomRate))
723 emit configChanged();
724 emit useCustomMessageRateSet(_useCustomMessageRate);
728 void Network::setMessageRateBurstSize(quint32 burstSize)
731 // Can't go slower than one message at a time. Also blocks old clients from trying to set
733 qDebug() << "Received invalid setMessageRateBurstSize data - message burst size must be "
734 "non-zero positive, given"
738 if (_messageRateBurstSize != burstSize) {
739 _messageRateBurstSize = burstSize;
741 emit configChanged();
742 emit messageRateBurstSizeSet(_messageRateBurstSize);
746 void Network::setMessageRateDelay(quint32 messageDelay)
748 if (messageDelay == 0) {
749 // Nonsensical to have no delay - just check the Unlimited box instead. Also blocks old
750 // clients from trying to set this to 0.
751 qDebug() << "Received invalid setMessageRateDelay data - message delay must be non-zero "
756 if (_messageRateDelay != messageDelay) {
757 _messageRateDelay = messageDelay;
758 SYNC(ARG(messageDelay))
759 emit configChanged();
760 emit messageRateDelaySet(_messageRateDelay);
764 void Network::setUnlimitedMessageRate(bool unlimitedRate)
766 if (_unlimitedMessageRate != unlimitedRate) {
767 _unlimitedMessageRate = unlimitedRate;
768 SYNC(ARG(unlimitedRate))
769 emit configChanged();
770 emit unlimitedMessageRateSet(_unlimitedMessageRate);
774 void Network::addSupport(const QString& param, const QString& value)
776 if (!_supports.contains(param)) {
777 _supports[param] = value;
778 SYNC(ARG(param), ARG(value))
782 void Network::removeSupport(const QString& param)
784 if (_supports.contains(param)) {
785 _supports.remove(param);
790 QVariantMap Network::initSupports() const
792 QVariantMap supports;
793 QHashIterator<QString, QString> iter(_supports);
794 while (iter.hasNext()) {
796 supports[iter.key()] = iter.value();
801 void Network::addCap(const QString& capability, const QString& value)
803 // IRCv3 specs all use lowercase capability names
804 QString _capLowercase = capability.toLower();
805 if (!_caps.contains(_capLowercase)) {
806 _caps[_capLowercase] = value;
807 SYNC(ARG(capability), ARG(value))
808 emit capAdded(_capLowercase);
812 void Network::acknowledgeCap(const QString& capability)
814 // IRCv3 specs all use lowercase capability names
815 QString _capLowercase = capability.toLower();
816 if (!_capsEnabled.contains(_capLowercase)) {
817 _capsEnabled.append(_capLowercase);
818 SYNC(ARG(capability))
819 emit capAcknowledged(_capLowercase);
823 void Network::removeCap(const QString& capability)
825 // IRCv3 specs all use lowercase capability names
826 QString _capLowercase = capability.toLower();
827 if (_caps.contains(_capLowercase)) {
828 // Remove from the list of available capabilities.
829 _caps.remove(_capLowercase);
830 // Remove it from the acknowledged list if it was previously acknowledged. The SYNC call
831 // ensures this propogates to the other side.
832 // Use removeOne() for speed; no more than one due to contains() check in acknowledgeCap().
833 _capsEnabled.removeOne(_capLowercase);
834 SYNC(ARG(capability))
835 emit capRemoved(_capLowercase);
839 void Network::clearCaps()
841 // IRCv3 specs all use lowercase capability names
842 if (_caps.empty() && _capsEnabled.empty()) {
843 // Avoid the sync call if there's nothing to clear (e.g. failed reconnects)
846 // To ease core-side configuration, loop through the list and emit capRemoved for each entry.
847 // If performance issues arise, this can be converted to a more-efficient setup without breaking
848 // protocol (in theory).
849 QString _capLowercase;
850 foreach (const QString& capability, _caps) {
851 _capLowercase = capability.toLower();
852 emit capRemoved(_capLowercase);
854 // Clear capabilities from the stored list
856 _capsEnabled.clear();
861 QVariantMap Network::initCaps() const
864 QHashIterator<QString, QString> iter(_caps);
865 while (iter.hasNext()) {
867 caps[iter.key()] = iter.value();
872 // There's potentially a lot of users and channels, so it makes sense to optimize the format of this.
873 // Rather than sending a thousand maps with identical keys, we convert this into one map containing lists
874 // where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times.
875 // Benchmarks have shown space savings of around 56%, resulting in saving several MBs worth of data on sync
876 // (without compression) with a decent amount of IrcUsers.
877 QVariantMap Network::initIrcUsersAndChannels() const
880 Q_ASSERT(proxy()->targetPeer());
881 QVariantMap usersAndChannels;
883 if (_ircUsers.count()) {
884 QHash<QString, QVariantList> users;
885 QHash<QString, IrcUser*>::const_iterator it = _ircUsers.begin();
886 QHash<QString, IrcUser*>::const_iterator end = _ircUsers.end();
888 QVariantMap map = it.value()->toVariantMap();
889 // If the peer doesn't support LongTime, replace the lastAwayMessageTime field
890 // with the 32-bit numerical seconds value (lastAwayMessage) used in older versions
891 if (!proxy()->targetPeer()->hasFeature(Quassel::Feature::LongTime)) {
892 #if QT_VERSION >= 0x050800
893 int lastAwayMessage = it.value()->lastAwayMessageTime().toSecsSinceEpoch();
895 // toSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now.
896 // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
897 int lastAwayMessage = it.value()->lastAwayMessageTime().toMSecsSinceEpoch() / 1000;
899 map.remove("lastAwayMessageTime");
900 map["lastAwayMessage"] = lastAwayMessage;
903 QVariantMap::const_iterator mapiter = map.begin();
904 while (mapiter != map.end()) {
905 users[mapiter.key()] << mapiter.value();
910 // Can't have a container with a value type != QVariant in a QVariant :(
911 // However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above.
913 foreach (const QString& key, users.keys())
914 userMap[key] = users[key];
915 usersAndChannels["Users"] = userMap;
918 if (_ircChannels.count()) {
919 QHash<QString, QVariantList> channels;
920 QHash<QString, IrcChannel*>::const_iterator it = _ircChannels.begin();
921 QHash<QString, IrcChannel*>::const_iterator end = _ircChannels.end();
923 const QVariantMap& map = it.value()->toVariantMap();
924 QVariantMap::const_iterator mapiter = map.begin();
925 while (mapiter != map.end()) {
926 channels[mapiter.key()] << mapiter.value();
931 QVariantMap channelMap;
932 foreach (const QString& key, channels.keys())
933 channelMap[key] = channels[key];
934 usersAndChannels["Channels"] = channelMap;
937 return usersAndChannels;
940 void Network::initSetIrcUsersAndChannels(const QVariantMap& usersAndChannels)
943 Q_ASSERT(proxy()->sourcePeer());
944 if (isInitialized()) {
945 qWarning() << "Network" << networkId()
946 << "received init data for users and channels although there already are known users or channels!";
950 // toMap() and toList() are cheap, so we can avoid copying to lists...
951 // However, we really have to make sure to never accidentally detach from the shared data!
953 const QVariantMap& users = usersAndChannels["Users"].toMap();
956 int count = users["nick"].toList().count();
957 foreach (const QString& key, users.keys()) {
958 if (users[key].toList().count() != count) {
959 qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
964 // now create the individual IrcUsers
965 for (int i = 0; i < count; i++) {
967 foreach (const QString& key, users.keys())
968 map[key] = users[key].toList().at(i);
970 // If the peer doesn't support LongTime, upconvert the lastAwayMessageTime field
971 // from the 32-bit numerical seconds value used in older versions to QDateTime
972 if (!proxy()->sourcePeer()->hasFeature(Quassel::Feature::LongTime)) {
973 QDateTime lastAwayMessageTime = QDateTime();
974 lastAwayMessageTime.setTimeSpec(Qt::UTC);
975 #if QT_VERSION >= 0x050800
976 lastAwayMessageTime.fromSecsSinceEpoch(map.take("lastAwayMessage").toInt());
978 // toSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now.
979 // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
980 lastAwayMessageTime.fromMSecsSinceEpoch(map.take("lastAwayMessage").toInt() * 1000);
982 map["lastAwayMessageTime"] = lastAwayMessageTime;
985 newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
988 // same thing for IrcChannels
989 const QVariantMap& channels = usersAndChannels["Channels"].toMap();
992 count = channels["name"].toList().count();
993 foreach (const QString& key, channels.keys()) {
994 if (channels[key].toList().count() != count) {
995 qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
999 // now create the individual IrcChannels
1000 for (int i = 0; i < count; i++) {
1002 foreach (const QString& key, channels.keys())
1003 map[key] = channels[key].toList().at(i);
1004 newIrcChannel(map["name"].toString(), map);
1008 void Network::initSetSupports(const QVariantMap& supports)
1010 QMapIterator<QString, QVariant> iter(supports);
1011 while (iter.hasNext()) {
1013 addSupport(iter.key(), iter.value().toString());
1017 void Network::initSetCaps(const QVariantMap& caps)
1019 QMapIterator<QString, QVariant> iter(caps);
1020 while (iter.hasNext()) {
1022 addCap(iter.key(), iter.value().toString());
1026 IrcUser* Network::updateNickFromMask(const QString& mask)
1028 QString nick(nickFromMask(mask).toLower());
1031 if (_ircUsers.contains(nick)) {
1032 ircuser = _ircUsers[nick];
1033 ircuser->updateHostmask(mask);
1036 ircuser = newIrcUser(mask);
1041 void Network::ircUserNickChanged(QString newnick)
1043 QString oldnick = _ircUsers.key(qobject_cast<IrcUser*>(sender()));
1045 if (oldnick.isNull())
1048 if (newnick.toLower() != oldnick)
1049 _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
1051 if (myNick().toLower() == oldnick)
1055 void Network::emitConnectionError(const QString& errorMsg)
1057 emit connectionError(errorMsg);
1060 // ====================
1062 // ====================
1063 void Network::determinePrefixes() const
1065 // seems like we have to construct them first
1066 QString prefix = support("PREFIX");
1068 if (prefix.startsWith("(") && prefix.contains(")")) {
1069 _prefixes = prefix.section(")", 1);
1070 _prefixModes = prefix.mid(1).section(")", 0, 0);
1073 QString defaultPrefixes("~&@%+");
1074 QString defaultPrefixModes("qaohv");
1076 if (prefix.isEmpty()) {
1077 _prefixes = defaultPrefixes;
1078 _prefixModes = defaultPrefixModes;
1081 // clear the existing modes, just in case we're run multiple times
1082 _prefixes = QString();
1083 _prefixModes = QString();
1085 // we just assume that in PREFIX are only prefix chars stored
1086 for (int i = 0; i < defaultPrefixes.size(); i++) {
1087 if (prefix.contains(defaultPrefixes[i])) {
1088 _prefixes += defaultPrefixes[i];
1089 _prefixModes += defaultPrefixModes[i];
1092 // check for success
1093 if (!_prefixes.isNull())
1096 // well... our assumption was obviously wrong...
1097 // check if it's only prefix modes
1098 for (int i = 0; i < defaultPrefixes.size(); i++) {
1099 if (prefix.contains(defaultPrefixModes[i])) {
1100 _prefixes += defaultPrefixes[i];
1101 _prefixModes += defaultPrefixModes[i];
1104 // now we've done all we've could...
1108 /************************************************************************
1110 ************************************************************************/
1112 bool NetworkInfo::operator==(const NetworkInfo& other) const
1114 return networkName == other.networkName
1115 && serverList == other.serverList
1116 && perform == other.perform
1117 && autoIdentifyService == other.autoIdentifyService
1118 && autoIdentifyPassword == other.autoIdentifyPassword
1119 && saslAccount == other.saslAccount
1120 && saslPassword == other.saslPassword
1121 && codecForServer == other.codecForServer
1122 && codecForEncoding == other.codecForEncoding
1123 && codecForDecoding == other.codecForDecoding
1124 && networkId == other.networkId
1125 && identity == other.identity
1126 && messageRateBurstSize == other.messageRateBurstSize
1127 && messageRateDelay == other.messageRateDelay
1128 && autoReconnectInterval == other.autoReconnectInterval
1129 && autoReconnectRetries == other.autoReconnectRetries
1130 && rejoinChannels == other.rejoinChannels
1131 && useRandomServer == other.useRandomServer
1132 && useAutoIdentify == other.useAutoIdentify
1133 && useSasl == other.useSasl
1134 && useAutoReconnect == other.useAutoReconnect
1135 && unlimitedReconnectRetries == other.unlimitedReconnectRetries
1136 && useCustomMessageRate == other.useCustomMessageRate
1137 && unlimitedMessageRate == other.unlimitedMessageRate
1141 bool NetworkInfo::operator!=(const NetworkInfo& other) const
1143 return !(*this == other);
1146 QDataStream& operator<<(QDataStream& out, const NetworkInfo& info)
1149 i["NetworkName"] = info.networkName;
1150 i["ServerList"] = toVariantList(info.serverList);
1151 i["Perform"] = info.perform;
1152 i["AutoIdentifyService"] = info.autoIdentifyService;
1153 i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
1154 i["SaslAccount"] = info.saslAccount;
1155 i["SaslPassword"] = info.saslPassword;
1156 i["CodecForServer"] = info.codecForServer;
1157 i["CodecForEncoding"] = info.codecForEncoding;
1158 i["CodecForDecoding"] = info.codecForDecoding;
1159 i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
1160 i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
1161 i["MessageRateBurstSize"] = info.messageRateBurstSize;
1162 i["MessageRateDelay"] = info.messageRateDelay;
1163 i["AutoReconnectInterval"] = info.autoReconnectInterval;
1164 i["AutoReconnectRetries"] = info.autoReconnectRetries;
1165 i["RejoinChannels"] = info.rejoinChannels;
1166 i["UseRandomServer"] = info.useRandomServer;
1167 i["UseAutoIdentify"] = info.useAutoIdentify;
1168 i["UseSasl"] = info.useSasl;
1169 i["UseAutoReconnect"] = info.useAutoReconnect;
1170 i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
1171 i["UseCustomMessageRate"] = info.useCustomMessageRate;
1172 i["UnlimitedMessageRate"] = info.unlimitedMessageRate;
1177 QDataStream& operator>>(QDataStream& in, NetworkInfo& info)
1181 info.networkName = i["NetworkName"].toString();
1182 info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
1183 info.perform = i["Perform"].toStringList();
1184 info.autoIdentifyService = i["AutoIdentifyService"].toString();
1185 info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
1186 info.saslAccount = i["SaslAccount"].toString();
1187 info.saslPassword = i["SaslPassword"].toString();
1188 info.codecForServer = i["CodecForServer"].toByteArray();
1189 info.codecForEncoding = i["CodecForEncoding"].toByteArray();
1190 info.codecForDecoding = i["CodecForDecoding"].toByteArray();
1191 info.networkId = i["NetworkId"].value<NetworkId>();
1192 info.identity = i["Identity"].value<IdentityId>();
1193 info.messageRateBurstSize = i["MessageRateBurstSize"].toUInt();
1194 info.messageRateDelay = i["MessageRateDelay"].toUInt();
1195 info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
1196 info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
1197 info.rejoinChannels = i["RejoinChannels"].toBool();
1198 info.useRandomServer = i["UseRandomServer"].toBool();
1199 info.useAutoIdentify = i["UseAutoIdentify"].toBool();
1200 info.useSasl = i["UseSasl"].toBool();
1201 info.useAutoReconnect = i["UseAutoReconnect"].toBool();
1202 info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
1203 info.useCustomMessageRate = i["UseCustomMessageRate"].toBool();
1204 info.unlimitedMessageRate = i["UnlimitedMessageRate"].toBool();
1208 QDebug operator<<(QDebug dbg, const NetworkInfo& i)
1210 dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
1211 << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding
1212 << " codecForDecoding = " << i.codecForDecoding << " serverList = " << i.serverList
1213 << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform << " useAutoIdentify = " << i.useAutoIdentify
1214 << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
1215 << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
1216 << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
1217 << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
1218 << " rejoinChannels = " << i.rejoinChannels << " useCustomMessageRate = " << i.useCustomMessageRate
1219 << " messageRateBurstSize = " << i.messageRateBurstSize << " messageRateDelay = " << i.messageRateDelay
1220 << " unlimitedMessageRate = " << i.unlimitedMessageRate << ")";
1224 QDataStream& operator<<(QDataStream& out, const Network::Server& server)
1226 QVariantMap serverMap;
1227 serverMap["Host"] = server.host;
1228 serverMap["Port"] = server.port;
1229 serverMap["Password"] = server.password;
1230 serverMap["UseSSL"] = server.useSsl;
1231 serverMap["sslVerify"] = server.sslVerify;
1232 serverMap["sslVersion"] = server.sslVersion;
1233 serverMap["UseProxy"] = server.useProxy;
1234 serverMap["ProxyType"] = server.proxyType;
1235 serverMap["ProxyHost"] = server.proxyHost;
1236 serverMap["ProxyPort"] = server.proxyPort;
1237 serverMap["ProxyUser"] = server.proxyUser;
1238 serverMap["ProxyPass"] = server.proxyPass;
1243 QDataStream& operator>>(QDataStream& in, Network::Server& server)
1245 QVariantMap serverMap;
1247 server.host = serverMap["Host"].toString();
1248 server.port = serverMap["Port"].toUInt();
1249 server.password = serverMap["Password"].toString();
1250 server.useSsl = serverMap["UseSSL"].toBool();
1251 server.sslVerify = serverMap["sslVerify"].toBool();
1252 server.sslVersion = serverMap["sslVersion"].toInt();
1253 server.useProxy = serverMap["UseProxy"].toBool();
1254 server.proxyType = serverMap["ProxyType"].toInt();
1255 server.proxyHost = serverMap["ProxyHost"].toString();
1256 server.proxyPort = serverMap["ProxyPort"].toUInt();
1257 server.proxyUser = serverMap["ProxyUser"].toString();
1258 server.proxyPass = serverMap["ProxyPass"].toString();
1262 bool Network::Server::operator==(const Server& other) const
1264 if (host != other.host)
1266 if (port != other.port)
1268 if (password != other.password)
1270 if (useSsl != other.useSsl)
1272 if (sslVerify != other.sslVerify)
1274 if (sslVersion != other.sslVersion)
1276 if (useProxy != other.useProxy)
1278 if (proxyType != other.proxyType)
1280 if (proxyHost != other.proxyHost)
1282 if (proxyPort != other.proxyPort)
1284 if (proxyUser != other.proxyUser)
1286 if (proxyPass != other.proxyPass)
1291 bool Network::Server::operator!=(const Server& other) const
1293 return !(*this == other);
1296 QDebug operator<<(QDebug dbg, const Network::Server& server)
1298 dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << server.useSsl
1299 << ", sslVerify = " << server.sslVerify << ")";