1 /***************************************************************************
2 * Copyright (C) 2005-2018 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 ***************************************************************************/
28 QTextCodec *Network::_defaultCodecForServer = 0;
29 QTextCodec *Network::_defaultCodecForEncoding = 0;
30 QTextCodec *Network::_defaultCodecForDecoding = 0;
32 // ====================
34 // ====================
35 INIT_SYNCABLE_OBJECT(Network)
36 Network::Network(const NetworkId &networkid, QObject *parent)
37 : SyncableObject(parent),
39 _networkId(networkid),
43 _networkName(QString("<not initialized>")),
44 _currentServer(QString()),
46 _connectionState(Disconnected),
48 _prefixModes(QString()),
49 _useRandomServer(false),
50 _useAutoIdentify(false),
52 _useAutoReconnect(false),
53 _autoReconnectInterval(60),
54 _autoReconnectRetries(10),
55 _unlimitedReconnectRetries(false),
56 _useCustomMessageRate(false),
57 _messageRateBurstSize(5),
58 _messageRateDelay(2200),
59 _unlimitedMessageRate(false),
63 _autoAwayActive(false)
65 setObjectName(QString::number(networkid.toInt()));
71 emit aboutToBeDestroyed();
75 bool Network::isChannelName(const QString &channelname) const
77 if (channelname.isEmpty())
80 if (supports("CHANTYPES"))
81 return support("CHANTYPES").contains(channelname[0]);
83 return QString("#&!+").contains(channelname[0]);
87 bool Network::isStatusMsg(const QString &target) const
92 if (supports("STATUSMSG"))
93 return support("STATUSMSG").contains(target[0]);
95 return QString("@+").contains(target[0]);
99 NetworkInfo Network::networkInfo() const
102 info.networkName = networkName();
103 info.networkId = networkId();
104 info.identity = identity();
105 info.codecForServer = codecForServer();
106 info.codecForEncoding = codecForEncoding();
107 info.codecForDecoding = codecForDecoding();
108 info.serverList = serverList();
109 info.useRandomServer = useRandomServer();
110 info.perform = perform();
111 info.useAutoIdentify = useAutoIdentify();
112 info.autoIdentifyService = autoIdentifyService();
113 info.autoIdentifyPassword = autoIdentifyPassword();
114 info.useSasl = useSasl();
115 info.saslAccount = saslAccount();
116 info.saslPassword = saslPassword();
117 info.useAutoReconnect = useAutoReconnect();
118 info.autoReconnectInterval = autoReconnectInterval();
119 info.autoReconnectRetries = autoReconnectRetries();
120 info.unlimitedReconnectRetries = unlimitedReconnectRetries();
121 info.rejoinChannels = rejoinChannels();
122 info.useCustomMessageRate = useCustomMessageRate();
123 info.messageRateBurstSize = messageRateBurstSize();
124 info.messageRateDelay = messageRateDelay();
125 info.unlimitedMessageRate = unlimitedMessageRate();
130 void Network::setNetworkInfo(const NetworkInfo &info)
132 // we don't set our ID!
133 if (!info.networkName.isEmpty() && info.networkName != networkName()) setNetworkName(info.networkName);
134 if (info.identity > 0 && info.identity != identity()) setIdentity(info.identity);
135 if (info.codecForServer != codecForServer()) setCodecForServer(QTextCodec::codecForName(info.codecForServer));
136 if (info.codecForEncoding != codecForEncoding()) setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
137 if (info.codecForDecoding != codecForDecoding()) setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
138 if (info.serverList.count()) setServerList(toVariantList(info.serverList)); // FIXME compare components
139 if (info.useRandomServer != useRandomServer()) setUseRandomServer(info.useRandomServer);
140 if (info.perform != perform()) setPerform(info.perform);
141 if (info.useAutoIdentify != useAutoIdentify()) setUseAutoIdentify(info.useAutoIdentify);
142 if (info.autoIdentifyService != autoIdentifyService()) setAutoIdentifyService(info.autoIdentifyService);
143 if (info.autoIdentifyPassword != autoIdentifyPassword()) setAutoIdentifyPassword(info.autoIdentifyPassword);
144 if (info.useSasl != useSasl()) setUseSasl(info.useSasl);
145 if (info.saslAccount != saslAccount()) setSaslAccount(info.saslAccount);
146 if (info.saslPassword != saslPassword()) setSaslPassword(info.saslPassword);
147 if (info.useAutoReconnect != useAutoReconnect()) setUseAutoReconnect(info.useAutoReconnect);
148 if (info.autoReconnectInterval != autoReconnectInterval()) setAutoReconnectInterval(info.autoReconnectInterval);
149 if (info.autoReconnectRetries != autoReconnectRetries()) setAutoReconnectRetries(info.autoReconnectRetries);
150 if (info.unlimitedReconnectRetries != unlimitedReconnectRetries()) setUnlimitedReconnectRetries(info.unlimitedReconnectRetries);
151 if (info.rejoinChannels != rejoinChannels()) setRejoinChannels(info.rejoinChannels);
152 // Custom rate limiting
153 if (info.useCustomMessageRate != useCustomMessageRate())
154 setUseCustomMessageRate(info.useCustomMessageRate);
155 if (info.messageRateBurstSize != messageRateBurstSize())
156 setMessageRateBurstSize(info.messageRateBurstSize);
157 if (info.messageRateDelay != messageRateDelay())
158 setMessageRateDelay(info.messageRateDelay);
159 if (info.unlimitedMessageRate != unlimitedMessageRate())
160 setUnlimitedMessageRate(info.unlimitedMessageRate);
164 QString Network::prefixToMode(const QString &prefix) const
166 if (prefixes().contains(prefix))
167 return QString(prefixModes()[prefixes().indexOf(prefix)]);
173 QString Network::modeToPrefix(const QString &mode) const
175 if (prefixModes().contains(mode))
176 return QString(prefixes()[prefixModes().indexOf(mode)]);
182 QString Network::sortPrefixModes(const QString &modes) const
184 // If modes is empty or we don't have any modes, nothing can be sorted, bail out early
185 if (modes.isEmpty() || prefixModes().isEmpty()) {
189 // Store a copy of the modes for modification
190 // QString should be efficient and not copy memory if nothing changes, but if mistaken,
191 // std::is_sorted could be called first.
192 QString sortedModes = QString(modes);
194 // Sort modes as if a QChar array
195 // See https://en.cppreference.com/w/cpp/algorithm/sort
196 // Defining lambda with [&] implicitly captures variables by reference
197 std::sort(sortedModes.begin(), sortedModes.end(), [&](const QChar &lmode, const QChar &rmode) {
198 // Compare characters according to prefix modes
199 // Return true if lmode comes before rmode (is "less than")
201 // Check for unknown modes...
202 if (!prefixModes().contains(lmode)) {
203 // Left mode not in prefix list, send to end
205 } else if (!prefixModes().contains(rmode)) {
206 // Right mode not in prefix list, send to end
209 // Both characters known, sort according to index in prefixModes()
210 return (prefixModes().indexOf(lmode) < prefixModes().indexOf(rmode));
218 QStringList Network::nicks() const
220 // we don't use _ircUsers.keys() since the keys may be
221 // not up to date after a nick change
223 foreach(IrcUser *ircuser, _ircUsers.values()) {
224 nicks << ircuser->nick();
230 QString Network::prefixes() const
232 if (_prefixes.isNull())
239 QString Network::prefixModes() const
241 if (_prefixModes.isNull())
248 // example Unreal IRCD: CHANMODES=beI,kfL,lj,psmntirRcOAQKVCuzNSMTG
249 Network::ChannelModeType Network::channelModeType(const QString &mode)
252 return NOT_A_CHANMODE;
254 QString chanmodes = support("CHANMODES");
255 if (chanmodes.isEmpty())
256 return NOT_A_CHANMODE;
258 ChannelModeType modeType = A_CHANMODE;
259 for (int i = 0; i < chanmodes.count(); i++) {
260 if (chanmodes[i] == mode[0])
262 else if (chanmodes[i] == ',')
263 modeType = (ChannelModeType)(modeType << 1);
265 if (modeType > D_CHANMODE) {
266 qWarning() << "Network" << networkId() << "supplied invalid CHANMODES:" << chanmodes;
267 modeType = NOT_A_CHANMODE;
273 QString Network::support(const QString ¶m) const
275 QString support_ = param.toUpper();
276 if (_supports.contains(support_))
277 return _supports[support_];
283 bool Network::saslMaybeSupports(const QString &saslMechanism) const
285 if (!capAvailable(IrcCap::SASL)) {
286 // If SASL's not advertised at all, it's likely the mechanism isn't supported, as per specs.
287 // Unfortunately, we don't know for sure, but Quassel won't request SASL without it being
288 // advertised, anyways.
289 // This may also occur if the network's disconnected or negotiation hasn't yet happened.
293 // Get the SASL capability value
294 QString saslCapValue = capValue(IrcCap::SASL);
295 // SASL mechanisms are only specified in capability values as part of SASL 3.2. In SASL 3.1,
296 // it's handled differently. If we don't know via capability value, assume it's supported to
297 // reduce the risk of breaking existing setups.
298 // See: http://ircv3.net/specs/extensions/sasl-3.1.html
299 // And: http://ircv3.net/specs/extensions/sasl-3.2.html
300 return (saslCapValue.length() == 0)
301 || (saslCapValue.contains(saslMechanism, Qt::CaseInsensitive));
305 IrcUser *Network::newIrcUser(const QString &hostmask, const QVariantMap &initData)
307 QString nick(nickFromMask(hostmask).toLower());
308 if (!_ircUsers.contains(nick)) {
309 IrcUser *ircuser = ircUserFactory(hostmask);
310 if (!initData.isEmpty()) {
311 ircuser->fromVariantMap(initData);
312 ircuser->setInitialized();
316 proxy()->synchronize(ircuser);
318 qWarning() << "unable to synchronize new IrcUser" << hostmask << "forgot to call Network::setProxy(SignalProxy *)?";
320 connect(ircuser, SIGNAL(nickSet(QString)), this, SLOT(ircUserNickChanged(QString)));
322 _ircUsers[nick] = ircuser;
324 // This method will be called with a nick instead of hostmask by setInitIrcUsersAndChannels().
325 // Not a problem because initData contains all we need; however, making sure here to get the real
326 // hostmask out of the IrcUser afterwards.
327 QString mask = ircuser->hostmask();
328 SYNC_OTHER(addIrcUser, ARG(mask));
329 // emit ircUserAdded(mask);
330 emit ircUserAdded(ircuser);
333 return _ircUsers[nick];
337 IrcUser *Network::ircUser(QString nickname) const
339 nickname = nickname.toLower();
340 if (_ircUsers.contains(nickname))
341 return _ircUsers[nickname];
347 void Network::removeIrcUser(IrcUser *ircuser)
349 QString nick = _ircUsers.key(ircuser);
353 _ircUsers.remove(nick);
354 disconnect(ircuser, 0, this, 0);
355 ircuser->deleteLater();
359 void Network::removeIrcChannel(IrcChannel *channel)
361 QString chanName = _ircChannels.key(channel);
362 if (chanName.isNull())
365 _ircChannels.remove(chanName);
366 disconnect(channel, 0, this, 0);
367 channel->deleteLater();
371 void Network::removeChansAndUsers()
373 QList<IrcUser *> users = ircUsers();
375 QList<IrcChannel *> channels = ircChannels();
376 _ircChannels.clear();
379 qDeleteAll(channels);
383 IrcChannel *Network::newIrcChannel(const QString &channelname, const QVariantMap &initData)
385 if (!_ircChannels.contains(channelname.toLower())) {
386 IrcChannel *channel = ircChannelFactory(channelname);
387 if (!initData.isEmpty()) {
388 channel->fromVariantMap(initData);
389 channel->setInitialized();
393 proxy()->synchronize(channel);
395 qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
397 _ircChannels[channelname.toLower()] = channel;
399 SYNC_OTHER(addIrcChannel, ARG(channelname))
400 // emit ircChannelAdded(channelname);
401 emit ircChannelAdded(channel);
403 return _ircChannels[channelname.toLower()];
407 IrcChannel *Network::ircChannel(QString channelname) const
409 channelname = channelname.toLower();
410 if (_ircChannels.contains(channelname))
411 return _ircChannels[channelname];
417 QByteArray Network::defaultCodecForServer()
419 if (_defaultCodecForServer)
420 return _defaultCodecForServer->name();
425 void Network::setDefaultCodecForServer(const QByteArray &name)
427 _defaultCodecForServer = QTextCodec::codecForName(name);
431 QByteArray Network::defaultCodecForEncoding()
433 if (_defaultCodecForEncoding)
434 return _defaultCodecForEncoding->name();
439 void Network::setDefaultCodecForEncoding(const QByteArray &name)
441 _defaultCodecForEncoding = QTextCodec::codecForName(name);
445 QByteArray Network::defaultCodecForDecoding()
447 if (_defaultCodecForDecoding)
448 return _defaultCodecForDecoding->name();
453 void Network::setDefaultCodecForDecoding(const QByteArray &name)
455 _defaultCodecForDecoding = QTextCodec::codecForName(name);
459 QByteArray Network::codecForServer() const
462 return _codecForServer->name();
467 void Network::setCodecForServer(const QByteArray &name)
469 setCodecForServer(QTextCodec::codecForName(name));
473 void Network::setCodecForServer(QTextCodec *codec)
475 _codecForServer = codec;
476 QByteArray codecName = codecForServer();
477 SYNC_OTHER(setCodecForServer, ARG(codecName))
478 emit configChanged();
482 QByteArray Network::codecForEncoding() const
484 if (_codecForEncoding)
485 return _codecForEncoding->name();
490 void Network::setCodecForEncoding(const QByteArray &name)
492 setCodecForEncoding(QTextCodec::codecForName(name));
496 void Network::setCodecForEncoding(QTextCodec *codec)
498 _codecForEncoding = codec;
499 QByteArray codecName = codecForEncoding();
500 SYNC_OTHER(setCodecForEncoding, ARG(codecName))
501 emit configChanged();
505 QByteArray Network::codecForDecoding() const
507 if (_codecForDecoding)
508 return _codecForDecoding->name();
509 else return QByteArray();
513 void Network::setCodecForDecoding(const QByteArray &name)
515 setCodecForDecoding(QTextCodec::codecForName(name));
519 void Network::setCodecForDecoding(QTextCodec *codec)
521 _codecForDecoding = codec;
522 QByteArray codecName = codecForDecoding();
523 SYNC_OTHER(setCodecForDecoding, ARG(codecName))
524 emit configChanged();
528 // FIXME use server encoding if appropriate
529 QString Network::decodeString(const QByteArray &text) const
531 if (_codecForDecoding)
532 return ::decodeString(text, _codecForDecoding);
533 else return ::decodeString(text, _defaultCodecForDecoding);
537 QByteArray Network::encodeString(const QString &string) const
539 if (_codecForEncoding) {
540 return _codecForEncoding->fromUnicode(string);
542 if (_defaultCodecForEncoding) {
543 return _defaultCodecForEncoding->fromUnicode(string);
545 return string.toLatin1();
549 QString Network::decodeServerString(const QByteArray &text) const
552 return ::decodeString(text, _codecForServer);
554 return ::decodeString(text, _defaultCodecForServer);
558 QByteArray Network::encodeServerString(const QString &string) const
560 if (_codecForServer) {
561 return _codecForServer->fromUnicode(string);
563 if (_defaultCodecForServer) {
564 return _defaultCodecForServer->fromUnicode(string);
566 return string.toLatin1();
570 // ====================
572 // ====================
573 void Network::setNetworkName(const QString &networkName)
575 _networkName = networkName;
576 SYNC(ARG(networkName))
577 emit networkNameSet(networkName);
578 emit configChanged();
582 void Network::setCurrentServer(const QString ¤tServer)
584 _currentServer = currentServer;
585 SYNC(ARG(currentServer))
586 emit currentServerSet(currentServer);
590 void Network::setConnected(bool connected)
592 if (_connected == connected)
595 _connected = connected;
597 setMyNick(QString());
598 setCurrentServer(QString());
599 removeChansAndUsers();
602 emit connectedSet(connected);
606 //void Network::setConnectionState(ConnectionState state) {
607 void Network::setConnectionState(int state)
609 _connectionState = (ConnectionState)state;
610 //qDebug() << "netstate" << networkId() << networkName() << state;
612 emit connectionStateSet(_connectionState);
616 void Network::setMyNick(const QString &nickname)
619 if (!_myNick.isEmpty() && !ircUser(myNick())) {
620 newIrcUser(myNick());
623 emit myNickSet(nickname);
627 void Network::setLatency(int latency)
629 if (_latency == latency)
636 void Network::setIdentity(IdentityId id)
640 emit identitySet(id);
641 emit configChanged();
645 void Network::setServerList(const QVariantList &serverList)
647 _serverList = fromVariantList<Server>(serverList);
648 SYNC(ARG(serverList))
649 emit configChanged();
653 void Network::setUseRandomServer(bool use)
655 _useRandomServer = use;
657 emit configChanged();
661 void Network::setPerform(const QStringList &perform)
665 emit configChanged();
669 void Network::setUseAutoIdentify(bool use)
671 _useAutoIdentify = use;
673 emit configChanged();
677 void Network::setAutoIdentifyService(const QString &service)
679 _autoIdentifyService = service;
681 emit configChanged();
685 void Network::setAutoIdentifyPassword(const QString &password)
687 _autoIdentifyPassword = password;
689 emit configChanged();
693 void Network::setUseSasl(bool use)
697 emit configChanged();
701 void Network::setSaslAccount(const QString &account)
703 _saslAccount = account;
705 emit configChanged();
709 void Network::setSaslPassword(const QString &password)
711 _saslPassword = password;
713 emit configChanged();
717 void Network::setUseAutoReconnect(bool use)
719 _useAutoReconnect = use;
721 emit configChanged();
725 void Network::setAutoReconnectInterval(quint32 interval)
727 _autoReconnectInterval = interval;
729 emit configChanged();
733 void Network::setAutoReconnectRetries(quint16 retries)
735 _autoReconnectRetries = retries;
737 emit configChanged();
741 void Network::setUnlimitedReconnectRetries(bool unlimited)
743 _unlimitedReconnectRetries = unlimited;
745 emit configChanged();
749 void Network::setRejoinChannels(bool rejoin)
751 _rejoinChannels = rejoin;
753 emit configChanged();
757 void Network::setUseCustomMessageRate(bool useCustomRate)
759 if (_useCustomMessageRate != useCustomRate) {
760 _useCustomMessageRate = useCustomRate;
761 SYNC(ARG(useCustomRate))
762 emit configChanged();
763 emit useCustomMessageRateSet(_useCustomMessageRate);
768 void Network::setMessageRateBurstSize(quint32 burstSize)
771 // Can't go slower than one message at a time. Also blocks old clients from trying to set
773 qDebug() << "Received invalid setMessageRateBurstSize data - message burst size must be "
774 "non-zero positive, given" << burstSize;
777 if (_messageRateBurstSize != burstSize) {
778 _messageRateBurstSize = burstSize;
780 emit configChanged();
781 emit messageRateBurstSizeSet(_messageRateBurstSize);
786 void Network::setMessageRateDelay(quint32 messageDelay)
788 if (messageDelay == 0) {
789 // Nonsensical to have no delay - just check the Unlimited box instead. Also blocks old
790 // clients from trying to set this to 0.
791 qDebug() << "Received invalid setMessageRateDelay data - message delay must be non-zero "
792 "positive, given" << messageDelay;
795 if (_messageRateDelay != messageDelay) {
796 _messageRateDelay = messageDelay;
797 SYNC(ARG(messageDelay))
798 emit configChanged();
799 emit messageRateDelaySet(_messageRateDelay);
804 void Network::setUnlimitedMessageRate(bool unlimitedRate)
806 if (_unlimitedMessageRate != unlimitedRate) {
807 _unlimitedMessageRate = unlimitedRate;
808 SYNC(ARG(unlimitedRate))
809 emit configChanged();
810 emit unlimitedMessageRateSet(_unlimitedMessageRate);
815 void Network::addSupport(const QString ¶m, const QString &value)
817 if (!_supports.contains(param)) {
818 _supports[param] = value;
819 SYNC(ARG(param), ARG(value))
824 void Network::removeSupport(const QString ¶m)
826 if (_supports.contains(param)) {
827 _supports.remove(param);
833 QVariantMap Network::initSupports() const
835 QVariantMap supports;
836 QHashIterator<QString, QString> iter(_supports);
837 while (iter.hasNext()) {
839 supports[iter.key()] = iter.value();
844 void Network::addCap(const QString &capability, const QString &value)
846 // IRCv3 specs all use lowercase capability names
847 QString _capLowercase = capability.toLower();
848 if (!_caps.contains(_capLowercase)) {
849 _caps[_capLowercase] = value;
850 SYNC(ARG(capability), ARG(value))
851 emit capAdded(_capLowercase);
855 void Network::acknowledgeCap(const QString &capability)
857 // IRCv3 specs all use lowercase capability names
858 QString _capLowercase = capability.toLower();
859 if (!_capsEnabled.contains(_capLowercase)) {
860 _capsEnabled.append(_capLowercase);
861 SYNC(ARG(capability))
862 emit capAcknowledged(_capLowercase);
866 void Network::removeCap(const QString &capability)
868 // IRCv3 specs all use lowercase capability names
869 QString _capLowercase = capability.toLower();
870 if (_caps.contains(_capLowercase)) {
871 // Remove from the list of available capabilities.
872 _caps.remove(_capLowercase);
873 // Remove it from the acknowledged list if it was previously acknowledged. The SYNC call
874 // ensures this propogates to the other side.
875 // Use removeOne() for speed; no more than one due to contains() check in acknowledgeCap().
876 _capsEnabled.removeOne(_capLowercase);
877 SYNC(ARG(capability))
878 emit capRemoved(_capLowercase);
882 void Network::clearCaps()
884 // IRCv3 specs all use lowercase capability names
885 if (_caps.empty() && _capsEnabled.empty()) {
886 // Avoid the sync call if there's nothing to clear (e.g. failed reconnects)
889 // To ease core-side configuration, loop through the list and emit capRemoved for each entry.
890 // If performance issues arise, this can be converted to a more-efficient setup without breaking
891 // protocol (in theory).
892 QString _capLowercase;
893 foreach (const QString &capability, _caps) {
894 _capLowercase = capability.toLower();
895 emit capRemoved(_capLowercase);
897 // Clear capabilities from the stored list
899 _capsEnabled.clear();
904 QVariantMap Network::initCaps() const
907 QHashIterator<QString, QString> iter(_caps);
908 while (iter.hasNext()) {
910 caps[iter.key()] = iter.value();
916 // There's potentially a lot of users and channels, so it makes sense to optimize the format of this.
917 // Rather than sending a thousand maps with identical keys, we convert this into one map containing lists
918 // where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times.
919 // Benchmarks have shown space savings of around 56%, resulting in saving several MBs worth of data on sync
920 // (without compression) with a decent amount of IrcUsers.
921 QVariantMap Network::initIrcUsersAndChannels() const
924 Q_ASSERT(proxy()->targetPeer());
925 QVariantMap usersAndChannels;
927 if (_ircUsers.count()) {
928 QHash<QString, QVariantList> users;
929 QHash<QString, IrcUser *>::const_iterator it = _ircUsers.begin();
930 QHash<QString, IrcUser *>::const_iterator end = _ircUsers.end();
932 QVariantMap map = it.value()->toVariantMap();
933 // If the peer doesn't support LongTime, replace the lastAwayMessageTime field
934 // with the 32-bit numerical seconds value (lastAwayMessage) used in older versions
935 if (!proxy()->targetPeer()->hasFeature(Quassel::Feature::LongTime)) {
936 #if QT_VERSION >= 0x050800
937 int lastAwayMessage = it.value()->lastAwayMessageTime().toSecsSinceEpoch();
939 // toSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now.
940 // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
941 int lastAwayMessage = it.value()->lastAwayMessageTime().toMSecsSinceEpoch() / 1000;
943 map.remove("lastAwayMessageTime");
944 map["lastAwayMessage"] = lastAwayMessage;
947 QVariantMap::const_iterator mapiter = map.begin();
948 while (mapiter != map.end()) {
949 users[mapiter.key()] << mapiter.value();
954 // Can't have a container with a value type != QVariant in a QVariant :(
955 // However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above.
957 foreach(const QString &key, users.keys())
958 userMap[key] = users[key];
959 usersAndChannels["Users"] = userMap;
962 if (_ircChannels.count()) {
963 QHash<QString, QVariantList> channels;
964 QHash<QString, IrcChannel *>::const_iterator it = _ircChannels.begin();
965 QHash<QString, IrcChannel *>::const_iterator end = _ircChannels.end();
967 const QVariantMap &map = it.value()->toVariantMap();
968 QVariantMap::const_iterator mapiter = map.begin();
969 while (mapiter != map.end()) {
970 channels[mapiter.key()] << mapiter.value();
975 QVariantMap channelMap;
976 foreach(const QString &key, channels.keys())
977 channelMap[key] = channels[key];
978 usersAndChannels["Channels"] = channelMap;
981 return usersAndChannels;
985 void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels)
988 Q_ASSERT(proxy()->sourcePeer());
989 if (isInitialized()) {
990 qWarning() << "Network" << networkId() << "received init data for users and channels although there already are known users or channels!";
994 // toMap() and toList() are cheap, so we can avoid copying to lists...
995 // However, we really have to make sure to never accidentally detach from the shared data!
997 const QVariantMap &users = usersAndChannels["Users"].toMap();
1000 int count = users["nick"].toList().count();
1001 foreach(const QString &key, users.keys()) {
1002 if (users[key].toList().count() != count) {
1003 qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
1008 // now create the individual IrcUsers
1009 for(int i = 0; i < count; i++) {
1011 foreach(const QString &key, users.keys())
1012 map[key] = users[key].toList().at(i);
1014 // If the peer doesn't support LongTime, upconvert the lastAwayMessageTime field
1015 // from the 32-bit numerical seconds value used in older versions to QDateTime
1016 if (!proxy()->sourcePeer()->hasFeature(Quassel::Feature::LongTime)) {
1017 QDateTime lastAwayMessageTime = QDateTime();
1018 lastAwayMessageTime.setTimeSpec(Qt::UTC);
1019 #if QT_VERSION >= 0x050800
1020 lastAwayMessageTime.fromSecsSinceEpoch(map.take("lastAwayMessage").toInt());
1022 // toSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now.
1023 // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
1024 lastAwayMessageTime.fromMSecsSinceEpoch(map.take("lastAwayMessage").toInt() * 1000);
1026 map["lastAwayMessageTime"] = lastAwayMessageTime;
1029 newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
1032 // same thing for IrcChannels
1033 const QVariantMap &channels = usersAndChannels["Channels"].toMap();
1036 count = channels["name"].toList().count();
1037 foreach(const QString &key, channels.keys()) {
1038 if (channels[key].toList().count() != count) {
1039 qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
1043 // now create the individual IrcChannels
1044 for(int i = 0; i < count; i++) {
1046 foreach(const QString &key, channels.keys())
1047 map[key] = channels[key].toList().at(i);
1048 newIrcChannel(map["name"].toString(), map);
1053 void Network::initSetSupports(const QVariantMap &supports)
1055 QMapIterator<QString, QVariant> iter(supports);
1056 while (iter.hasNext()) {
1058 addSupport(iter.key(), iter.value().toString());
1063 void Network::initSetCaps(const QVariantMap &caps)
1065 QMapIterator<QString, QVariant> iter(caps);
1066 while (iter.hasNext()) {
1068 addCap(iter.key(), iter.value().toString());
1073 IrcUser *Network::updateNickFromMask(const QString &mask)
1075 QString nick(nickFromMask(mask).toLower());
1078 if (_ircUsers.contains(nick)) {
1079 ircuser = _ircUsers[nick];
1080 ircuser->updateHostmask(mask);
1083 ircuser = newIrcUser(mask);
1089 void Network::ircUserNickChanged(QString newnick)
1091 QString oldnick = _ircUsers.key(qobject_cast<IrcUser *>(sender()));
1093 if (oldnick.isNull())
1096 if (newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
1098 if (myNick().toLower() == oldnick)
1103 void Network::emitConnectionError(const QString &errorMsg)
1105 emit connectionError(errorMsg);
1109 // ====================
1111 // ====================
1112 void Network::determinePrefixes() const
1114 // seems like we have to construct them first
1115 QString prefix = support("PREFIX");
1117 if (prefix.startsWith("(") && prefix.contains(")")) {
1118 _prefixes = prefix.section(")", 1);
1119 _prefixModes = prefix.mid(1).section(")", 0, 0);
1122 QString defaultPrefixes("~&@%+");
1123 QString defaultPrefixModes("qaohv");
1125 if (prefix.isEmpty()) {
1126 _prefixes = defaultPrefixes;
1127 _prefixModes = defaultPrefixModes;
1130 // clear the existing modes, just in case we're run multiple times
1131 _prefixes = QString();
1132 _prefixModes = QString();
1134 // we just assume that in PREFIX are only prefix chars stored
1135 for (int i = 0; i < defaultPrefixes.size(); i++) {
1136 if (prefix.contains(defaultPrefixes[i])) {
1137 _prefixes += defaultPrefixes[i];
1138 _prefixModes += defaultPrefixModes[i];
1141 // check for success
1142 if (!_prefixes.isNull())
1145 // well... our assumption was obviously wrong...
1146 // check if it's only prefix modes
1147 for (int i = 0; i < defaultPrefixes.size(); i++) {
1148 if (prefix.contains(defaultPrefixModes[i])) {
1149 _prefixes += defaultPrefixes[i];
1150 _prefixModes += defaultPrefixModes[i];
1153 // now we've done all we've could...
1158 /************************************************************************
1160 ************************************************************************/
1162 NetworkInfo::NetworkInfo()
1165 useRandomServer(false),
1166 useAutoIdentify(false),
1167 autoIdentifyService("NickServ"),
1169 useAutoReconnect(true),
1170 autoReconnectInterval(60),
1171 autoReconnectRetries(20),
1172 unlimitedReconnectRetries(false),
1173 rejoinChannels(true),
1174 useCustomMessageRate(false),
1175 messageRateBurstSize(5),
1176 messageRateDelay(2200),
1177 unlimitedMessageRate(false)
1182 bool NetworkInfo::operator==(const NetworkInfo &other) const
1184 if (networkId != other.networkId) return false;
1185 if (networkName != other.networkName) return false;
1186 if (identity != other.identity) return false;
1187 if (codecForServer != other.codecForServer) return false;
1188 if (codecForEncoding != other.codecForEncoding) return false;
1189 if (codecForDecoding != other.codecForDecoding) return false;
1190 if (serverList != other.serverList) return false;
1191 if (useRandomServer != other.useRandomServer) return false;
1192 if (perform != other.perform) return false;
1193 if (useAutoIdentify != other.useAutoIdentify) return false;
1194 if (autoIdentifyService != other.autoIdentifyService) return false;
1195 if (autoIdentifyPassword != other.autoIdentifyPassword) return false;
1196 if (useSasl != other.useSasl) return false;
1197 if (saslAccount != other.saslAccount) return false;
1198 if (saslPassword != other.saslPassword) return false;
1199 if (useAutoReconnect != other.useAutoReconnect) return false;
1200 if (autoReconnectInterval != other.autoReconnectInterval) return false;
1201 if (autoReconnectRetries != other.autoReconnectRetries) return false;
1202 if (unlimitedReconnectRetries != other.unlimitedReconnectRetries) return false;
1203 if (rejoinChannels != other.rejoinChannels) return false;
1204 // Custom rate limiting
1205 if (useCustomMessageRate != other.useCustomMessageRate) return false;
1206 if (messageRateBurstSize != other.messageRateBurstSize) return false;
1207 if (messageRateDelay != other.messageRateDelay) return false;
1208 if (unlimitedMessageRate != other.unlimitedMessageRate) return false;
1213 bool NetworkInfo::operator!=(const NetworkInfo &other) const
1215 return !(*this == other);
1219 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info)
1222 i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
1223 i["NetworkName"] = info.networkName;
1224 i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
1225 i["CodecForServer"] = info.codecForServer;
1226 i["CodecForEncoding"] = info.codecForEncoding;
1227 i["CodecForDecoding"] = info.codecForDecoding;
1228 i["ServerList"] = toVariantList(info.serverList);
1229 i["UseRandomServer"] = info.useRandomServer;
1230 i["Perform"] = info.perform;
1231 i["UseAutoIdentify"] = info.useAutoIdentify;
1232 i["AutoIdentifyService"] = info.autoIdentifyService;
1233 i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
1234 i["UseSasl"] = info.useSasl;
1235 i["SaslAccount"] = info.saslAccount;
1236 i["SaslPassword"] = info.saslPassword;
1237 i["UseAutoReconnect"] = info.useAutoReconnect;
1238 i["AutoReconnectInterval"] = info.autoReconnectInterval;
1239 i["AutoReconnectRetries"] = info.autoReconnectRetries;
1240 i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
1241 i["RejoinChannels"] = info.rejoinChannels;
1242 // Custom rate limiting
1243 i["UseCustomMessageRate"] = info.useCustomMessageRate;
1244 i["MessageRateBurstSize"] = info.messageRateBurstSize;
1245 i["MessageRateDelay"] = info.messageRateDelay;
1246 i["UnlimitedMessageRate"] = info.unlimitedMessageRate;
1252 QDataStream &operator>>(QDataStream &in, NetworkInfo &info)
1256 info.networkId = i["NetworkId"].value<NetworkId>();
1257 info.networkName = i["NetworkName"].toString();
1258 info.identity = i["Identity"].value<IdentityId>();
1259 info.codecForServer = i["CodecForServer"].toByteArray();
1260 info.codecForEncoding = i["CodecForEncoding"].toByteArray();
1261 info.codecForDecoding = i["CodecForDecoding"].toByteArray();
1262 info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
1263 info.useRandomServer = i["UseRandomServer"].toBool();
1264 info.perform = i["Perform"].toStringList();
1265 info.useAutoIdentify = i["UseAutoIdentify"].toBool();
1266 info.autoIdentifyService = i["AutoIdentifyService"].toString();
1267 info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
1268 info.useSasl = i["UseSasl"].toBool();
1269 info.saslAccount = i["SaslAccount"].toString();
1270 info.saslPassword = i["SaslPassword"].toString();
1271 info.useAutoReconnect = i["UseAutoReconnect"].toBool();
1272 info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
1273 info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
1274 info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
1275 info.rejoinChannels = i["RejoinChannels"].toBool();
1276 // Custom rate limiting
1277 info.useCustomMessageRate = i["UseCustomMessageRate"].toBool();
1278 info.messageRateBurstSize = i["MessageRateBurstSize"].toUInt();
1279 info.messageRateDelay = i["MessageRateDelay"].toUInt();
1280 info.unlimitedMessageRate = i["UnlimitedMessageRate"].toBool();
1285 QDebug operator<<(QDebug dbg, const NetworkInfo &i)
1287 dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
1288 << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
1289 << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
1290 << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
1291 << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
1292 << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
1293 << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
1294 << " rejoinChannels = " << i.rejoinChannels
1295 << " useCustomMessageRate = " << i.useCustomMessageRate
1296 << " messageRateBurstSize = " << i.messageRateBurstSize
1297 << " messageRateDelay = " << i.messageRateDelay
1298 << " unlimitedMessageRate = " << i.unlimitedMessageRate
1304 QDataStream &operator<<(QDataStream &out, const Network::Server &server)
1306 QVariantMap serverMap;
1307 serverMap["Host"] = server.host;
1308 serverMap["Port"] = server.port;
1309 serverMap["Password"] = server.password;
1310 serverMap["UseSSL"] = server.useSsl;
1311 serverMap["sslVerify"] = server.sslVerify;
1312 serverMap["sslVersion"] = server.sslVersion;
1313 serverMap["UseProxy"] = server.useProxy;
1314 serverMap["ProxyType"] = server.proxyType;
1315 serverMap["ProxyHost"] = server.proxyHost;
1316 serverMap["ProxyPort"] = server.proxyPort;
1317 serverMap["ProxyUser"] = server.proxyUser;
1318 serverMap["ProxyPass"] = server.proxyPass;
1324 QDataStream &operator>>(QDataStream &in, Network::Server &server)
1326 QVariantMap serverMap;
1328 server.host = serverMap["Host"].toString();
1329 server.port = serverMap["Port"].toUInt();
1330 server.password = serverMap["Password"].toString();
1331 server.useSsl = serverMap["UseSSL"].toBool();
1332 server.sslVerify = serverMap["sslVerify"].toBool();
1333 server.sslVersion = serverMap["sslVersion"].toInt();
1334 server.useProxy = serverMap["UseProxy"].toBool();
1335 server.proxyType = serverMap["ProxyType"].toInt();
1336 server.proxyHost = serverMap["ProxyHost"].toString();
1337 server.proxyPort = serverMap["ProxyPort"].toUInt();
1338 server.proxyUser = serverMap["ProxyUser"].toString();
1339 server.proxyPass = serverMap["ProxyPass"].toString();
1344 bool Network::Server::operator==(const Server &other) const
1346 if (host != other.host) return false;
1347 if (port != other.port) return false;
1348 if (password != other.password) return false;
1349 if (useSsl != other.useSsl) return false;
1350 if (sslVerify != other.sslVerify) return false;
1351 if (sslVersion != other.sslVersion) return false;
1352 if (useProxy != other.useProxy) return false;
1353 if (proxyType != other.proxyType) return false;
1354 if (proxyHost != other.proxyHost) return false;
1355 if (proxyPort != other.proxyPort) return false;
1356 if (proxyUser != other.proxyUser) return false;
1357 if (proxyPass != other.proxyPass) return false;
1362 bool Network::Server::operator!=(const Server &other) const
1364 return !(*this == other);
1368 QDebug operator<<(QDebug dbg, const Network::Server &server)
1370 dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " <<
1371 server.useSsl << ", sslVerify = " << server.sslVerify << ")";