Network::clearCaps only sync when caps removed
[quassel.git] / src / common / network.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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 <QTextCodec>
22
23 #include "network.h"
24
25 QTextCodec *Network::_defaultCodecForServer = 0;
26 QTextCodec *Network::_defaultCodecForEncoding = 0;
27 QTextCodec *Network::_defaultCodecForDecoding = 0;
28
29 // ====================
30 //  Public:
31 // ====================
32 INIT_SYNCABLE_OBJECT(Network)
33 Network::Network(const NetworkId &networkid, QObject *parent)
34     : SyncableObject(parent),
35     _proxy(0),
36     _networkId(networkid),
37     _identity(0),
38     _myNick(QString()),
39     _latency(0),
40     _networkName(QString("<not initialized>")),
41     _currentServer(QString()),
42     _connected(false),
43     _connectionState(Disconnected),
44     _prefixes(QString()),
45     _prefixModes(QString()),
46     _useRandomServer(false),
47     _useAutoIdentify(false),
48     _useSasl(false),
49     _useAutoReconnect(false),
50     _autoReconnectInterval(60),
51     _autoReconnectRetries(10),
52     _unlimitedReconnectRetries(false),
53     _codecForServer(0),
54     _codecForEncoding(0),
55     _codecForDecoding(0),
56     _autoAwayActive(false)
57 {
58     setObjectName(QString::number(networkid.toInt()));
59 }
60
61
62 Network::~Network()
63 {
64     emit aboutToBeDestroyed();
65 }
66
67
68 bool Network::isChannelName(const QString &channelname) const
69 {
70     if (channelname.isEmpty())
71         return false;
72
73     if (supports("CHANTYPES"))
74         return support("CHANTYPES").contains(channelname[0]);
75     else
76         return QString("#&!+").contains(channelname[0]);
77 }
78
79
80 bool Network::isStatusMsg(const QString &target) const
81 {
82     if (target.isEmpty())
83         return false;
84
85     if (supports("STATUSMSG"))
86         return support("STATUSMSG").contains(target[0]);
87     else
88         return QString("@+").contains(target[0]);
89 }
90
91
92 NetworkInfo Network::networkInfo() const
93 {
94     NetworkInfo info;
95     info.networkName = networkName();
96     info.networkId = networkId();
97     info.identity = identity();
98     info.codecForServer = codecForServer();
99     info.codecForEncoding = codecForEncoding();
100     info.codecForDecoding = codecForDecoding();
101     info.serverList = serverList();
102     info.useRandomServer = useRandomServer();
103     info.perform = perform();
104     info.useAutoIdentify = useAutoIdentify();
105     info.autoIdentifyService = autoIdentifyService();
106     info.autoIdentifyPassword = autoIdentifyPassword();
107     info.useSasl = useSasl();
108     info.saslAccount = saslAccount();
109     info.saslPassword = saslPassword();
110     info.useAutoReconnect = useAutoReconnect();
111     info.autoReconnectInterval = autoReconnectInterval();
112     info.autoReconnectRetries = autoReconnectRetries();
113     info.unlimitedReconnectRetries = unlimitedReconnectRetries();
114     info.rejoinChannels = rejoinChannels();
115     return info;
116 }
117
118
119 void Network::setNetworkInfo(const NetworkInfo &info)
120 {
121     // we don't set our ID!
122     if (!info.networkName.isEmpty() && info.networkName != networkName()) setNetworkName(info.networkName);
123     if (info.identity > 0 && info.identity != identity()) setIdentity(info.identity);
124     if (info.codecForServer != codecForServer()) setCodecForServer(QTextCodec::codecForName(info.codecForServer));
125     if (info.codecForEncoding != codecForEncoding()) setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
126     if (info.codecForDecoding != codecForDecoding()) setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
127     if (info.serverList.count()) setServerList(toVariantList(info.serverList));  // FIXME compare components
128     if (info.useRandomServer != useRandomServer()) setUseRandomServer(info.useRandomServer);
129     if (info.perform != perform()) setPerform(info.perform);
130     if (info.useAutoIdentify != useAutoIdentify()) setUseAutoIdentify(info.useAutoIdentify);
131     if (info.autoIdentifyService != autoIdentifyService()) setAutoIdentifyService(info.autoIdentifyService);
132     if (info.autoIdentifyPassword != autoIdentifyPassword()) setAutoIdentifyPassword(info.autoIdentifyPassword);
133     if (info.useSasl != useSasl()) setUseSasl(info.useSasl);
134     if (info.saslAccount != saslAccount()) setSaslAccount(info.saslAccount);
135     if (info.saslPassword != saslPassword()) setSaslPassword(info.saslPassword);
136     if (info.useAutoReconnect != useAutoReconnect()) setUseAutoReconnect(info.useAutoReconnect);
137     if (info.autoReconnectInterval != autoReconnectInterval()) setAutoReconnectInterval(info.autoReconnectInterval);
138     if (info.autoReconnectRetries != autoReconnectRetries()) setAutoReconnectRetries(info.autoReconnectRetries);
139     if (info.unlimitedReconnectRetries != unlimitedReconnectRetries()) setUnlimitedReconnectRetries(info.unlimitedReconnectRetries);
140     if (info.rejoinChannels != rejoinChannels()) setRejoinChannels(info.rejoinChannels);
141 }
142
143
144 QString Network::prefixToMode(const QString &prefix) const
145 {
146     if (prefixes().contains(prefix))
147         return QString(prefixModes()[prefixes().indexOf(prefix)]);
148     else
149         return QString();
150 }
151
152
153 QString Network::modeToPrefix(const QString &mode) const
154 {
155     if (prefixModes().contains(mode))
156         return QString(prefixes()[prefixModes().indexOf(mode)]);
157     else
158         return QString();
159 }
160
161
162 QStringList Network::nicks() const
163 {
164     // we don't use _ircUsers.keys() since the keys may be
165     // not up to date after a nick change
166     QStringList nicks;
167     foreach(IrcUser *ircuser, _ircUsers.values()) {
168         nicks << ircuser->nick();
169     }
170     return nicks;
171 }
172
173
174 QString Network::prefixes() const
175 {
176     if (_prefixes.isNull())
177         determinePrefixes();
178
179     return _prefixes;
180 }
181
182
183 QString Network::prefixModes() const
184 {
185     if (_prefixModes.isNull())
186         determinePrefixes();
187
188     return _prefixModes;
189 }
190
191
192 // example Unreal IRCD: CHANMODES=beI,kfL,lj,psmntirRcOAQKVCuzNSMTG
193 Network::ChannelModeType Network::channelModeType(const QString &mode)
194 {
195     if (mode.isEmpty())
196         return NOT_A_CHANMODE;
197
198     QString chanmodes = support("CHANMODES");
199     if (chanmodes.isEmpty())
200         return NOT_A_CHANMODE;
201
202     ChannelModeType modeType = A_CHANMODE;
203     for (int i = 0; i < chanmodes.count(); i++) {
204         if (chanmodes[i] == mode[0])
205             break;
206         else if (chanmodes[i] == ',')
207             modeType = (ChannelModeType)(modeType << 1);
208     }
209     if (modeType > D_CHANMODE) {
210         qWarning() << "Network" << networkId() << "supplied invalid CHANMODES:" << chanmodes;
211         modeType = NOT_A_CHANMODE;
212     }
213     return modeType;
214 }
215
216
217 QString Network::support(const QString &param) const
218 {
219     QString support_ = param.toUpper();
220     if (_supports.contains(support_))
221         return _supports[support_];
222     else
223         return QString();
224 }
225
226
227 IrcUser *Network::newIrcUser(const QString &hostmask, const QVariantMap &initData)
228 {
229     QString nick(nickFromMask(hostmask).toLower());
230     if (!_ircUsers.contains(nick)) {
231         IrcUser *ircuser = ircUserFactory(hostmask);
232         if (!initData.isEmpty()) {
233             ircuser->fromVariantMap(initData);
234             ircuser->setInitialized();
235         }
236
237         if (proxy())
238             proxy()->synchronize(ircuser);
239         else
240             qWarning() << "unable to synchronize new IrcUser" << hostmask << "forgot to call Network::setProxy(SignalProxy *)?";
241
242         connect(ircuser, SIGNAL(nickSet(QString)), this, SLOT(ircUserNickChanged(QString)));
243
244         _ircUsers[nick] = ircuser;
245
246         // This method will be called with a nick instead of hostmask by setInitIrcUsersAndChannels().
247         // Not a problem because initData contains all we need; however, making sure here to get the real
248         // hostmask out of the IrcUser afterwards.
249         QString mask = ircuser->hostmask();
250         SYNC_OTHER(addIrcUser, ARG(mask));
251         // emit ircUserAdded(mask);
252         emit ircUserAdded(ircuser);
253     }
254
255     return _ircUsers[nick];
256 }
257
258
259 IrcUser *Network::ircUser(QString nickname) const
260 {
261     nickname = nickname.toLower();
262     if (_ircUsers.contains(nickname))
263         return _ircUsers[nickname];
264     else
265         return 0;
266 }
267
268
269 void Network::removeIrcUser(IrcUser *ircuser)
270 {
271     QString nick = _ircUsers.key(ircuser);
272     if (nick.isNull())
273         return;
274
275     _ircUsers.remove(nick);
276     disconnect(ircuser, 0, this, 0);
277     ircuser->deleteLater();
278 }
279
280
281 void Network::removeIrcChannel(IrcChannel *channel)
282 {
283     QString chanName = _ircChannels.key(channel);
284     if (chanName.isNull())
285         return;
286
287     _ircChannels.remove(chanName);
288     disconnect(channel, 0, this, 0);
289     channel->deleteLater();
290 }
291
292
293 void Network::removeChansAndUsers()
294 {
295     QList<IrcUser *> users = ircUsers();
296     _ircUsers.clear();
297     QList<IrcChannel *> channels = ircChannels();
298     _ircChannels.clear();
299
300     qDeleteAll(users);
301     qDeleteAll(channels);
302 }
303
304
305 IrcChannel *Network::newIrcChannel(const QString &channelname, const QVariantMap &initData)
306 {
307     if (!_ircChannels.contains(channelname.toLower())) {
308         IrcChannel *channel = ircChannelFactory(channelname);
309         if (!initData.isEmpty()) {
310             channel->fromVariantMap(initData);
311             channel->setInitialized();
312         }
313
314         if (proxy())
315             proxy()->synchronize(channel);
316         else
317             qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
318
319         _ircChannels[channelname.toLower()] = channel;
320
321         SYNC_OTHER(addIrcChannel, ARG(channelname))
322         // emit ircChannelAdded(channelname);
323         emit ircChannelAdded(channel);
324     }
325     return _ircChannels[channelname.toLower()];
326 }
327
328
329 IrcChannel *Network::ircChannel(QString channelname) const
330 {
331     channelname = channelname.toLower();
332     if (_ircChannels.contains(channelname))
333         return _ircChannels[channelname];
334     else
335         return 0;
336 }
337
338
339 QByteArray Network::defaultCodecForServer()
340 {
341     if (_defaultCodecForServer)
342         return _defaultCodecForServer->name();
343     return QByteArray();
344 }
345
346
347 void Network::setDefaultCodecForServer(const QByteArray &name)
348 {
349     _defaultCodecForServer = QTextCodec::codecForName(name);
350 }
351
352
353 QByteArray Network::defaultCodecForEncoding()
354 {
355     if (_defaultCodecForEncoding)
356         return _defaultCodecForEncoding->name();
357     return QByteArray();
358 }
359
360
361 void Network::setDefaultCodecForEncoding(const QByteArray &name)
362 {
363     _defaultCodecForEncoding = QTextCodec::codecForName(name);
364 }
365
366
367 QByteArray Network::defaultCodecForDecoding()
368 {
369     if (_defaultCodecForDecoding)
370         return _defaultCodecForDecoding->name();
371     return QByteArray();
372 }
373
374
375 void Network::setDefaultCodecForDecoding(const QByteArray &name)
376 {
377     _defaultCodecForDecoding = QTextCodec::codecForName(name);
378 }
379
380
381 QByteArray Network::codecForServer() const
382 {
383     if (_codecForServer)
384         return _codecForServer->name();
385     return QByteArray();
386 }
387
388
389 void Network::setCodecForServer(const QByteArray &name)
390 {
391     setCodecForServer(QTextCodec::codecForName(name));
392 }
393
394
395 void Network::setCodecForServer(QTextCodec *codec)
396 {
397     _codecForServer = codec;
398     QByteArray codecName = codecForServer();
399     SYNC_OTHER(setCodecForServer, ARG(codecName))
400     emit configChanged();
401 }
402
403
404 QByteArray Network::codecForEncoding() const
405 {
406     if (_codecForEncoding)
407         return _codecForEncoding->name();
408     return QByteArray();
409 }
410
411
412 void Network::setCodecForEncoding(const QByteArray &name)
413 {
414     setCodecForEncoding(QTextCodec::codecForName(name));
415 }
416
417
418 void Network::setCodecForEncoding(QTextCodec *codec)
419 {
420     _codecForEncoding = codec;
421     QByteArray codecName = codecForEncoding();
422     SYNC_OTHER(setCodecForEncoding, ARG(codecName))
423     emit configChanged();
424 }
425
426
427 QByteArray Network::codecForDecoding() const
428 {
429     if (_codecForDecoding)
430         return _codecForDecoding->name();
431     else return QByteArray();
432 }
433
434
435 void Network::setCodecForDecoding(const QByteArray &name)
436 {
437     setCodecForDecoding(QTextCodec::codecForName(name));
438 }
439
440
441 void Network::setCodecForDecoding(QTextCodec *codec)
442 {
443     _codecForDecoding = codec;
444     QByteArray codecName = codecForDecoding();
445     SYNC_OTHER(setCodecForDecoding, ARG(codecName))
446     emit configChanged();
447 }
448
449
450 // FIXME use server encoding if appropriate
451 QString Network::decodeString(const QByteArray &text) const
452 {
453     if (_codecForDecoding)
454         return ::decodeString(text, _codecForDecoding);
455     else return ::decodeString(text, _defaultCodecForDecoding);
456 }
457
458
459 QByteArray Network::encodeString(const QString &string) const
460 {
461     if (_codecForEncoding) {
462         return _codecForEncoding->fromUnicode(string);
463     }
464     if (_defaultCodecForEncoding) {
465         return _defaultCodecForEncoding->fromUnicode(string);
466     }
467     return string.toLatin1();
468 }
469
470
471 QString Network::decodeServerString(const QByteArray &text) const
472 {
473     if (_codecForServer)
474         return ::decodeString(text, _codecForServer);
475     else
476         return ::decodeString(text, _defaultCodecForServer);
477 }
478
479
480 QByteArray Network::encodeServerString(const QString &string) const
481 {
482     if (_codecForServer) {
483         return _codecForServer->fromUnicode(string);
484     }
485     if (_defaultCodecForServer) {
486         return _defaultCodecForServer->fromUnicode(string);
487     }
488     return string.toLatin1();
489 }
490
491
492 // ====================
493 //  Public Slots:
494 // ====================
495 void Network::setNetworkName(const QString &networkName)
496 {
497     _networkName = networkName;
498     SYNC(ARG(networkName))
499     emit networkNameSet(networkName);
500     emit configChanged();
501 }
502
503
504 void Network::setCurrentServer(const QString &currentServer)
505 {
506     _currentServer = currentServer;
507     SYNC(ARG(currentServer))
508     emit currentServerSet(currentServer);
509 }
510
511
512 void Network::setConnected(bool connected)
513 {
514     if (_connected == connected)
515         return;
516
517     _connected = connected;
518     if (!connected) {
519         setMyNick(QString());
520         setCurrentServer(QString());
521         removeChansAndUsers();
522     }
523     SYNC(ARG(connected))
524     emit connectedSet(connected);
525 }
526
527
528 //void Network::setConnectionState(ConnectionState state) {
529 void Network::setConnectionState(int state)
530 {
531     _connectionState = (ConnectionState)state;
532     //qDebug() << "netstate" << networkId() << networkName() << state;
533     SYNC(ARG(state))
534     emit connectionStateSet(_connectionState);
535 }
536
537
538 void Network::setMyNick(const QString &nickname)
539 {
540     _myNick = nickname;
541     if (!_myNick.isEmpty() && !ircUser(myNick())) {
542         newIrcUser(myNick());
543     }
544     SYNC(ARG(nickname))
545     emit myNickSet(nickname);
546 }
547
548
549 void Network::setLatency(int latency)
550 {
551     if (_latency == latency)
552         return;
553     _latency = latency;
554     SYNC(ARG(latency))
555 }
556
557
558 void Network::setIdentity(IdentityId id)
559 {
560     _identity = id;
561     SYNC(ARG(id))
562     emit identitySet(id);
563     emit configChanged();
564 }
565
566
567 void Network::setServerList(const QVariantList &serverList)
568 {
569     _serverList = fromVariantList<Server>(serverList);
570     SYNC(ARG(serverList))
571     emit configChanged();
572 }
573
574
575 void Network::setUseRandomServer(bool use)
576 {
577     _useRandomServer = use;
578     SYNC(ARG(use))
579     emit configChanged();
580 }
581
582
583 void Network::setPerform(const QStringList &perform)
584 {
585     _perform = perform;
586     SYNC(ARG(perform))
587     emit configChanged();
588 }
589
590
591 void Network::setUseAutoIdentify(bool use)
592 {
593     _useAutoIdentify = use;
594     SYNC(ARG(use))
595     emit configChanged();
596 }
597
598
599 void Network::setAutoIdentifyService(const QString &service)
600 {
601     _autoIdentifyService = service;
602     SYNC(ARG(service))
603     emit configChanged();
604 }
605
606
607 void Network::setAutoIdentifyPassword(const QString &password)
608 {
609     _autoIdentifyPassword = password;
610     SYNC(ARG(password))
611     emit configChanged();
612 }
613
614
615 void Network::setUseSasl(bool use)
616 {
617     _useSasl = use;
618     SYNC(ARG(use))
619     emit configChanged();
620 }
621
622
623 void Network::setSaslAccount(const QString &account)
624 {
625     _saslAccount = account;
626     SYNC(ARG(account))
627     emit configChanged();
628 }
629
630
631 void Network::setSaslPassword(const QString &password)
632 {
633     _saslPassword = password;
634     SYNC(ARG(password))
635     emit configChanged();
636 }
637
638
639 void Network::setUseAutoReconnect(bool use)
640 {
641     _useAutoReconnect = use;
642     SYNC(ARG(use))
643     emit configChanged();
644 }
645
646
647 void Network::setAutoReconnectInterval(quint32 interval)
648 {
649     _autoReconnectInterval = interval;
650     SYNC(ARG(interval))
651     emit configChanged();
652 }
653
654
655 void Network::setAutoReconnectRetries(quint16 retries)
656 {
657     _autoReconnectRetries = retries;
658     SYNC(ARG(retries))
659     emit configChanged();
660 }
661
662
663 void Network::setUnlimitedReconnectRetries(bool unlimited)
664 {
665     _unlimitedReconnectRetries = unlimited;
666     SYNC(ARG(unlimited))
667     emit configChanged();
668 }
669
670
671 void Network::setRejoinChannels(bool rejoin)
672 {
673     _rejoinChannels = rejoin;
674     SYNC(ARG(rejoin))
675     emit configChanged();
676 }
677
678
679 void Network::addSupport(const QString &param, const QString &value)
680 {
681     if (!_supports.contains(param)) {
682         _supports[param] = value;
683         SYNC(ARG(param), ARG(value))
684     }
685 }
686
687
688 void Network::removeSupport(const QString &param)
689 {
690     if (_supports.contains(param)) {
691         _supports.remove(param);
692         SYNC(ARG(param))
693     }
694 }
695
696
697 QVariantMap Network::initSupports() const
698 {
699     QVariantMap supports;
700     QHashIterator<QString, QString> iter(_supports);
701     while (iter.hasNext()) {
702         iter.next();
703         supports[iter.key()] = iter.value();
704     }
705     return supports;
706 }
707
708 void Network::addCap(const QString &capability, const QString &value)
709 {
710     // IRCv3 specs all use lowercase capability names
711     QString _capLowercase = capability.toLower();
712     if (!_caps.contains(_capLowercase)) {
713         _caps[_capLowercase] = value;
714         SYNC(ARG(capability), ARG(value))
715         emit capAdded(_capLowercase);
716     }
717 }
718
719 void Network::acknowledgeCap(const QString &capability)
720 {
721     // IRCv3 specs all use lowercase capability names
722     QString _capLowercase = capability.toLower();
723     if (!_capsEnabled.contains(_capLowercase)) {
724         _capsEnabled.append(_capLowercase);
725         SYNC(ARG(capability))
726         emit capAcknowledged(_capLowercase);
727     }
728 }
729
730 void Network::removeCap(const QString &capability)
731 {
732     // IRCv3 specs all use lowercase capability names
733     QString _capLowercase = capability.toLower();
734     if (_caps.contains(_capLowercase)) {
735         // Remove from the list of available capabilities.
736         _caps.remove(_capLowercase);
737         // Remove it from the acknowledged list if it was previously acknowledged.  The SYNC call
738         // ensures this propogates to the other side.
739         // Use removeOne() for speed; no more than one due to contains() check in acknowledgeCap().
740         _capsEnabled.removeOne(_capLowercase);
741         SYNC(ARG(capability))
742         emit capRemoved(_capLowercase);
743     }
744 }
745
746 void Network::clearCaps()
747 {
748     // IRCv3 specs all use lowercase capability names
749     if (_caps.empty() && _capsEnabled.empty()) {
750         // Avoid the sync call if there's nothing to clear (e.g. failed reconnects)
751         return;
752     }
753     // To ease core-side configuration, loop through the list and emit capRemoved for each entry.
754     // If performance issues arise, this can be converted to a more-efficient setup without breaking
755     // protocol (in theory).
756     QString _capLowercase;
757     foreach (const QString &capability, _caps) {
758         _capLowercase = capability.toLower();
759         emit capRemoved(_capLowercase);
760     }
761     // Clear capabilities from the stored list
762     _caps.clear();
763     _capsEnabled.clear();
764
765     SYNC(NO_ARG)
766 }
767
768 QVariantMap Network::initCaps() const
769 {
770     QVariantMap caps;
771     QHashIterator<QString, QString> iter(_caps);
772     while (iter.hasNext()) {
773         iter.next();
774         caps[iter.key()] = iter.value();
775     }
776     return caps;
777 }
778
779
780 // There's potentially a lot of users and channels, so it makes sense to optimize the format of this.
781 // Rather than sending a thousand maps with identical keys, we convert this into one map containing lists
782 // where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times.
783 // Benchmarks have shown space savings of around 56%, resulting in saving several MBs worth of data on sync
784 // (without compression) with a decent amount of IrcUsers.
785 QVariantMap Network::initIrcUsersAndChannels() const
786 {
787     QVariantMap usersAndChannels;
788
789     if (_ircUsers.count()) {
790         QHash<QString, QVariantList> users;
791         QHash<QString, IrcUser *>::const_iterator it = _ircUsers.begin();
792         QHash<QString, IrcUser *>::const_iterator end = _ircUsers.end();
793         while (it != end) {
794             const QVariantMap &map = it.value()->toVariantMap();
795             QVariantMap::const_iterator mapiter = map.begin();
796             while (mapiter != map.end()) {
797                 users[mapiter.key()] << mapiter.value();
798                 ++mapiter;
799             }
800             ++it;
801         }
802         // Can't have a container with a value type != QVariant in a QVariant :(
803         // However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above.
804         QVariantMap userMap;
805         foreach(const QString &key, users.keys())
806             userMap[key] = users[key];
807         usersAndChannels["Users"] = userMap;
808     }
809
810     if (_ircChannels.count()) {
811         QHash<QString, QVariantList> channels;
812         QHash<QString, IrcChannel *>::const_iterator it = _ircChannels.begin();
813         QHash<QString, IrcChannel *>::const_iterator end = _ircChannels.end();
814         while (it != end) {
815             const QVariantMap &map = it.value()->toVariantMap();
816             QVariantMap::const_iterator mapiter = map.begin();
817             while (mapiter != map.end()) {
818                 channels[mapiter.key()] << mapiter.value();
819                 ++mapiter;
820             }
821             ++it;
822         }
823         QVariantMap channelMap;
824         foreach(const QString &key, channels.keys())
825             channelMap[key] = channels[key];
826         usersAndChannels["Channels"] = channelMap;
827     }
828
829     return usersAndChannels;
830 }
831
832
833 void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels)
834 {
835     Q_ASSERT(proxy());
836     if (isInitialized()) {
837         qWarning() << "Network" << networkId() << "received init data for users and channels although there already are known users or channels!";
838         return;
839     }
840
841     // toMap() and toList() are cheap, so we can avoid copying to lists...
842     // However, we really have to make sure to never accidentally detach from the shared data!
843
844     const QVariantMap &users = usersAndChannels["Users"].toMap();
845
846     // sanity check
847     int count = users["nick"].toList().count();
848     foreach(const QString &key, users.keys()) {
849         if (users[key].toList().count() != count) {
850             qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
851             return;
852         }
853     }
854
855     // now create the individual IrcUsers
856     for(int i = 0; i < count; i++) {
857         QVariantMap map;
858         foreach(const QString &key, users.keys())
859             map[key] = users[key].toList().at(i);
860         newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
861     }
862
863     // same thing for IrcChannels
864     const QVariantMap &channels = usersAndChannels["Channels"].toMap();
865
866     // sanity check
867     count = channels["name"].toList().count();
868     foreach(const QString &key, channels.keys()) {
869         if (channels[key].toList().count() != count) {
870             qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
871             return;
872         }
873     }
874     // now create the individual IrcChannels
875     for(int i = 0; i < count; i++) {
876         QVariantMap map;
877         foreach(const QString &key, channels.keys())
878             map[key] = channels[key].toList().at(i);
879         newIrcChannel(map["name"].toString(), map);
880     }
881 }
882
883
884 void Network::initSetSupports(const QVariantMap &supports)
885 {
886     QMapIterator<QString, QVariant> iter(supports);
887     while (iter.hasNext()) {
888         iter.next();
889         addSupport(iter.key(), iter.value().toString());
890     }
891 }
892
893
894 void Network::initSetCaps(const QVariantMap &caps)
895 {
896     QMapIterator<QString, QVariant> iter(caps);
897     while (iter.hasNext()) {
898         iter.next();
899         addCap(iter.key(), iter.value().toString());
900     }
901 }
902
903
904 IrcUser *Network::updateNickFromMask(const QString &mask)
905 {
906     QString nick(nickFromMask(mask).toLower());
907     IrcUser *ircuser;
908
909     if (_ircUsers.contains(nick)) {
910         ircuser = _ircUsers[nick];
911         ircuser->updateHostmask(mask);
912     }
913     else {
914         ircuser = newIrcUser(mask);
915     }
916     return ircuser;
917 }
918
919
920 void Network::ircUserNickChanged(QString newnick)
921 {
922     QString oldnick = _ircUsers.key(qobject_cast<IrcUser *>(sender()));
923
924     if (oldnick.isNull())
925         return;
926
927     if (newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
928
929     if (myNick().toLower() == oldnick)
930         setMyNick(newnick);
931 }
932
933
934 void Network::emitConnectionError(const QString &errorMsg)
935 {
936     emit connectionError(errorMsg);
937 }
938
939
940 // ====================
941 //  Private:
942 // ====================
943 void Network::determinePrefixes() const
944 {
945     // seems like we have to construct them first
946     QString prefix = support("PREFIX");
947
948     if (prefix.startsWith("(") && prefix.contains(")")) {
949         _prefixes = prefix.section(")", 1);
950         _prefixModes = prefix.mid(1).section(")", 0, 0);
951     }
952     else {
953         QString defaultPrefixes("~&@%+");
954         QString defaultPrefixModes("qaohv");
955
956         if (prefix.isEmpty()) {
957             _prefixes = defaultPrefixes;
958             _prefixModes = defaultPrefixModes;
959             return;
960         }
961         // clear the existing modes, just in case we're run multiple times
962         _prefixes = QString();
963         _prefixModes = QString();
964
965         // we just assume that in PREFIX are only prefix chars stored
966         for (int i = 0; i < defaultPrefixes.size(); i++) {
967             if (prefix.contains(defaultPrefixes[i])) {
968                 _prefixes += defaultPrefixes[i];
969                 _prefixModes += defaultPrefixModes[i];
970             }
971         }
972         // check for success
973         if (!_prefixes.isNull())
974             return;
975
976         // well... our assumption was obviously wrong...
977         // check if it's only prefix modes
978         for (int i = 0; i < defaultPrefixes.size(); i++) {
979             if (prefix.contains(defaultPrefixModes[i])) {
980                 _prefixes += defaultPrefixes[i];
981                 _prefixModes += defaultPrefixModes[i];
982             }
983         }
984         // now we've done all we've could...
985     }
986 }
987
988
989 /************************************************************************
990  * NetworkInfo
991  ************************************************************************/
992
993 NetworkInfo::NetworkInfo()
994     : networkId(0),
995     identity(1),
996     useRandomServer(false),
997     useAutoIdentify(false),
998     autoIdentifyService("NickServ"),
999     useSasl(false),
1000     useAutoReconnect(true),
1001     autoReconnectInterval(60),
1002     autoReconnectRetries(20),
1003     unlimitedReconnectRetries(false),
1004     rejoinChannels(true)
1005 {
1006 }
1007
1008
1009 bool NetworkInfo::operator==(const NetworkInfo &other) const
1010 {
1011     if (networkId != other.networkId) return false;
1012     if (networkName != other.networkName) return false;
1013     if (identity != other.identity) return false;
1014     if (codecForServer != other.codecForServer) return false;
1015     if (codecForEncoding != other.codecForEncoding) return false;
1016     if (codecForDecoding != other.codecForDecoding) return false;
1017     if (serverList != other.serverList) return false;
1018     if (useRandomServer != other.useRandomServer) return false;
1019     if (perform != other.perform) return false;
1020     if (useAutoIdentify != other.useAutoIdentify) return false;
1021     if (autoIdentifyService != other.autoIdentifyService) return false;
1022     if (autoIdentifyPassword != other.autoIdentifyPassword) return false;
1023     if (useSasl != other.useSasl) return false;
1024     if (saslAccount != other.saslAccount) return false;
1025     if (saslPassword != other.saslPassword) return false;
1026     if (useAutoReconnect != other.useAutoReconnect) return false;
1027     if (autoReconnectInterval != other.autoReconnectInterval) return false;
1028     if (autoReconnectRetries != other.autoReconnectRetries) return false;
1029     if (unlimitedReconnectRetries != other.unlimitedReconnectRetries) return false;
1030     if (rejoinChannels != other.rejoinChannels) return false;
1031     return true;
1032 }
1033
1034
1035 bool NetworkInfo::operator!=(const NetworkInfo &other) const
1036 {
1037     return !(*this == other);
1038 }
1039
1040
1041 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info)
1042 {
1043     QVariantMap i;
1044     i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
1045     i["NetworkName"] = info.networkName;
1046     i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
1047     i["CodecForServer"] = info.codecForServer;
1048     i["CodecForEncoding"] = info.codecForEncoding;
1049     i["CodecForDecoding"] = info.codecForDecoding;
1050     i["ServerList"] = toVariantList(info.serverList);
1051     i["UseRandomServer"] = info.useRandomServer;
1052     i["Perform"] = info.perform;
1053     i["UseAutoIdentify"] = info.useAutoIdentify;
1054     i["AutoIdentifyService"] = info.autoIdentifyService;
1055     i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
1056     i["UseSasl"] = info.useSasl;
1057     i["SaslAccount"] = info.saslAccount;
1058     i["SaslPassword"] = info.saslPassword;
1059     i["UseAutoReconnect"] = info.useAutoReconnect;
1060     i["AutoReconnectInterval"] = info.autoReconnectInterval;
1061     i["AutoReconnectRetries"] = info.autoReconnectRetries;
1062     i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
1063     i["RejoinChannels"] = info.rejoinChannels;
1064     out << i;
1065     return out;
1066 }
1067
1068
1069 QDataStream &operator>>(QDataStream &in, NetworkInfo &info)
1070 {
1071     QVariantMap i;
1072     in >> i;
1073     info.networkId = i["NetworkId"].value<NetworkId>();
1074     info.networkName = i["NetworkName"].toString();
1075     info.identity = i["Identity"].value<IdentityId>();
1076     info.codecForServer = i["CodecForServer"].toByteArray();
1077     info.codecForEncoding = i["CodecForEncoding"].toByteArray();
1078     info.codecForDecoding = i["CodecForDecoding"].toByteArray();
1079     info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
1080     info.useRandomServer = i["UseRandomServer"].toBool();
1081     info.perform = i["Perform"].toStringList();
1082     info.useAutoIdentify = i["UseAutoIdentify"].toBool();
1083     info.autoIdentifyService = i["AutoIdentifyService"].toString();
1084     info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
1085     info.useSasl = i["UseSasl"].toBool();
1086     info.saslAccount = i["SaslAccount"].toString();
1087     info.saslPassword = i["SaslPassword"].toString();
1088     info.useAutoReconnect = i["UseAutoReconnect"].toBool();
1089     info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
1090     info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
1091     info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
1092     info.rejoinChannels = i["RejoinChannels"].toBool();
1093     return in;
1094 }
1095
1096
1097 QDebug operator<<(QDebug dbg, const NetworkInfo &i)
1098 {
1099     dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
1100     << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
1101     << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
1102     << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
1103     << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
1104     << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
1105     << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
1106     << " rejoinChannels = " << i.rejoinChannels << ")";
1107     return dbg.space();
1108 }
1109
1110
1111 QDataStream &operator<<(QDataStream &out, const Network::Server &server)
1112 {
1113     QVariantMap serverMap;
1114     serverMap["Host"] = server.host;
1115     serverMap["Port"] = server.port;
1116     serverMap["Password"] = server.password;
1117     serverMap["UseSSL"] = server.useSsl;
1118     serverMap["sslVerify"] = server.sslVerify;
1119     serverMap["sslVersion"] = server.sslVersion;
1120     serverMap["UseProxy"] = server.useProxy;
1121     serverMap["ProxyType"] = server.proxyType;
1122     serverMap["ProxyHost"] = server.proxyHost;
1123     serverMap["ProxyPort"] = server.proxyPort;
1124     serverMap["ProxyUser"] = server.proxyUser;
1125     serverMap["ProxyPass"] = server.proxyPass;
1126     out << serverMap;
1127     return out;
1128 }
1129
1130
1131 QDataStream &operator>>(QDataStream &in, Network::Server &server)
1132 {
1133     QVariantMap serverMap;
1134     in >> serverMap;
1135     server.host = serverMap["Host"].toString();
1136     server.port = serverMap["Port"].toUInt();
1137     server.password = serverMap["Password"].toString();
1138     server.useSsl = serverMap["UseSSL"].toBool();
1139     server.sslVerify = serverMap["sslVerify"].toBool();
1140     server.sslVersion = serverMap["sslVersion"].toInt();
1141     server.useProxy = serverMap["UseProxy"].toBool();
1142     server.proxyType = serverMap["ProxyType"].toInt();
1143     server.proxyHost = serverMap["ProxyHost"].toString();
1144     server.proxyPort = serverMap["ProxyPort"].toUInt();
1145     server.proxyUser = serverMap["ProxyUser"].toString();
1146     server.proxyPass = serverMap["ProxyPass"].toString();
1147     return in;
1148 }
1149
1150
1151 bool Network::Server::operator==(const Server &other) const
1152 {
1153     if (host != other.host) return false;
1154     if (port != other.port) return false;
1155     if (password != other.password) return false;
1156     if (useSsl != other.useSsl) return false;
1157     if (sslVerify != other.sslVerify) return false;
1158     if (sslVersion != other.sslVersion) return false;
1159     if (useProxy != other.useProxy) return false;
1160     if (proxyType != other.proxyType) return false;
1161     if (proxyHost != other.proxyHost) return false;
1162     if (proxyPort != other.proxyPort) return false;
1163     if (proxyUser != other.proxyUser) return false;
1164     if (proxyPass != other.proxyPass) return false;
1165     return true;
1166 }
1167
1168
1169 bool Network::Server::operator!=(const Server &other) const
1170 {
1171     return !(*this == other);
1172 }
1173
1174
1175 QDebug operator<<(QDebug dbg, const Network::Server &server)
1176 {
1177     dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " <<
1178                      server.useSsl << ", sslVerify = " << server.sslVerify << ")";
1179     return dbg.space();
1180 }