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