Add codec blacklist for UTF-8 detection
[quassel.git] / src / common / network.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2013 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         SYNC_OTHER(addIrcUser, ARG(hostmask))
238         // emit ircUserAdded(hostmask);
239         emit ircUserAdded(ircuser);
240     }
241
242     return _ircUsers[nick];
243 }
244
245
246 IrcUser *Network::ircUser(QString nickname) const
247 {
248     nickname = nickname.toLower();
249     if (_ircUsers.contains(nickname))
250         return _ircUsers[nickname];
251     else
252         return 0;
253 }
254
255
256 void Network::removeIrcUser(IrcUser *ircuser)
257 {
258     QString nick = _ircUsers.key(ircuser);
259     if (nick.isNull())
260         return;
261
262     _ircUsers.remove(nick);
263     disconnect(ircuser, 0, this, 0);
264     ircuser->deleteLater();
265 }
266
267
268 void Network::removeIrcChannel(IrcChannel *channel)
269 {
270     QString chanName = _ircChannels.key(channel);
271     if (chanName.isNull())
272         return;
273
274     _ircChannels.remove(chanName);
275     disconnect(channel, 0, this, 0);
276     channel->deleteLater();
277 }
278
279
280 void Network::removeChansAndUsers()
281 {
282     QList<IrcUser *> users = ircUsers();
283     _ircUsers.clear();
284     QList<IrcChannel *> channels = ircChannels();
285     _ircChannels.clear();
286
287     foreach(IrcChannel *channel, channels) {
288         proxy()->detachObject(channel);
289         disconnect(channel, 0, this, 0);
290     }
291     foreach(IrcUser *user, users) {
292         proxy()->detachObject(user);
293         disconnect(user, 0, this, 0);
294     }
295
296     // the second loop is needed because quit can have sideffects
297     foreach(IrcUser *user, users) {
298         user->quit();
299     }
300
301     qDeleteAll(users);
302     qDeleteAll(channels);
303 }
304
305
306 IrcChannel *Network::newIrcChannel(const QString &channelname, const QVariantMap &initData)
307 {
308     if (!_ircChannels.contains(channelname.toLower())) {
309         IrcChannel *channel = ircChannelFactory(channelname);
310         if (!initData.isEmpty()) {
311             channel->fromVariantMap(initData);
312             channel->setInitialized();
313         }
314
315         if (proxy())
316             proxy()->synchronize(channel);
317         else
318             qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
319
320         _ircChannels[channelname.toLower()] = channel;
321
322         SYNC_OTHER(addIrcChannel, ARG(channelname))
323         // emit ircChannelAdded(channelname);
324         emit ircChannelAdded(channel);
325     }
326     return _ircChannels[channelname.toLower()];
327 }
328
329
330 IrcChannel *Network::ircChannel(QString channelname) const
331 {
332     channelname = channelname.toLower();
333     if (_ircChannels.contains(channelname))
334         return _ircChannels[channelname];
335     else
336         return 0;
337 }
338
339
340 QByteArray Network::defaultCodecForServer()
341 {
342     if (_defaultCodecForServer)
343         return _defaultCodecForServer->name();
344     return QByteArray();
345 }
346
347
348 void Network::setDefaultCodecForServer(const QByteArray &name)
349 {
350     _defaultCodecForServer = QTextCodec::codecForName(name);
351 }
352
353
354 QByteArray Network::defaultCodecForEncoding()
355 {
356     if (_defaultCodecForEncoding)
357         return _defaultCodecForEncoding->name();
358     return QByteArray();
359 }
360
361
362 void Network::setDefaultCodecForEncoding(const QByteArray &name)
363 {
364     _defaultCodecForEncoding = QTextCodec::codecForName(name);
365 }
366
367
368 QByteArray Network::defaultCodecForDecoding()
369 {
370     if (_defaultCodecForDecoding)
371         return _defaultCodecForDecoding->name();
372     return QByteArray();
373 }
374
375
376 void Network::setDefaultCodecForDecoding(const QByteArray &name)
377 {
378     _defaultCodecForDecoding = QTextCodec::codecForName(name);
379 }
380
381
382 QByteArray Network::codecForServer() const
383 {
384     if (_codecForServer)
385         return _codecForServer->name();
386     return QByteArray();
387 }
388
389
390 void Network::setCodecForServer(const QByteArray &name)
391 {
392     setCodecForServer(QTextCodec::codecForName(name));
393 }
394
395
396 void Network::setCodecForServer(QTextCodec *codec)
397 {
398     _codecForServer = codec;
399     QByteArray codecName = codecForServer();
400     SYNC_OTHER(setCodecForServer, ARG(codecName))
401     emit configChanged();
402 }
403
404
405 QByteArray Network::codecForEncoding() const
406 {
407     if (_codecForEncoding)
408         return _codecForEncoding->name();
409     return QByteArray();
410 }
411
412
413 void Network::setCodecForEncoding(const QByteArray &name)
414 {
415     setCodecForEncoding(QTextCodec::codecForName(name));
416 }
417
418
419 void Network::setCodecForEncoding(QTextCodec *codec)
420 {
421     _codecForEncoding = codec;
422     QByteArray codecName = codecForEncoding();
423     SYNC_OTHER(setCodecForEncoding, ARG(codecName))
424     emit configChanged();
425 }
426
427
428 QByteArray Network::codecForDecoding() const
429 {
430     if (_codecForDecoding)
431         return _codecForDecoding->name();
432     else return QByteArray();
433 }
434
435
436 void Network::setCodecForDecoding(const QByteArray &name)
437 {
438     setCodecForDecoding(QTextCodec::codecForName(name));
439 }
440
441
442 void Network::setCodecForDecoding(QTextCodec *codec)
443 {
444     _codecForDecoding = codec;
445     QByteArray codecName = codecForDecoding();
446     SYNC_OTHER(setCodecForDecoding, ARG(codecName))
447     emit configChanged();
448 }
449
450
451 // FIXME use server encoding if appropriate
452 QString Network::decodeString(const QByteArray &text) const
453 {
454     if (_codecForDecoding)
455         return ::decodeString(text, _codecForDecoding);
456     else return ::decodeString(text, _defaultCodecForDecoding);
457 }
458
459
460 QByteArray Network::encodeString(const QString &string) const
461 {
462     if (_codecForEncoding) {
463         return _codecForEncoding->fromUnicode(string);
464     }
465     if (_defaultCodecForEncoding) {
466         return _defaultCodecForEncoding->fromUnicode(string);
467     }
468     return string.toAscii();
469 }
470
471
472 QString Network::decodeServerString(const QByteArray &text) const
473 {
474     if (_codecForServer)
475         return ::decodeString(text, _codecForServer);
476     else
477         return ::decodeString(text, _defaultCodecForServer);
478 }
479
480
481 QByteArray Network::encodeServerString(const QString &string) const
482 {
483     if (_codecForServer) {
484         return _codecForServer->fromUnicode(string);
485     }
486     if (_defaultCodecForServer) {
487         return _defaultCodecForServer->fromUnicode(string);
488     }
489     return string.toAscii();
490 }
491
492
493 /*** Handle networks.ini ***/
494
495 QStringList Network::presetNetworks(bool onlyDefault)
496 {
497     // lazily find the file, make sure to not call one of the other preset functions first (they'll fail else)
498     if (_networksIniPath.isNull()) {
499         _networksIniPath = Quassel::findDataFilePath("networks.ini");
500         if (_networksIniPath.isNull()) {
501             _networksIniPath = ""; // now we won't check again, as it's not null anymore
502             return QStringList();
503         }
504     }
505     if (!_networksIniPath.isEmpty()) {
506         QSettings s(_networksIniPath, QSettings::IniFormat);
507         QStringList networks = s.childGroups();
508         if (!networks.isEmpty()) {
509             // we sort the list case-insensitive
510             QMap<QString, QString> sorted;
511             foreach(QString net, networks) {
512                 if (onlyDefault && !s.value(QString("%1/Default").arg(net)).toBool())
513                     continue;
514                 sorted[net.toLower()] = net;
515             }
516             return sorted.values();
517         }
518     }
519     return QStringList();
520 }
521
522
523 QStringList Network::presetDefaultChannels(const QString &networkName)
524 {
525     if (_networksIniPath.isEmpty()) // be sure to have called presetNetworks() first, else this always fails
526         return QStringList();
527     QSettings s(_networksIniPath, QSettings::IniFormat);
528     return s.value(QString("%1/DefaultChannels").arg(networkName)).toStringList();
529 }
530
531
532 NetworkInfo Network::networkInfoFromPreset(const QString &networkName)
533 {
534     NetworkInfo info;
535     if (!_networksIniPath.isEmpty()) {
536         info.networkName = networkName;
537         QSettings s(_networksIniPath, QSettings::IniFormat);
538         s.beginGroup(info.networkName);
539         foreach(QString server, s.value("Servers").toStringList()) {
540             bool ssl = false;
541             QStringList splitserver = server.split(':', QString::SkipEmptyParts);
542             if (splitserver.count() != 2) {
543                 qWarning() << "Invalid server entry in networks.conf:" << server;
544                 continue;
545             }
546             if (splitserver[1].at(0) == '+')
547                 ssl = true;
548             uint port = splitserver[1].toUInt();
549             if (!port) {
550                 qWarning() << "Invalid port entry in networks.conf:" << server;
551                 continue;
552             }
553             info.serverList << Network::Server(splitserver[0].trimmed(), port, QString(), ssl);
554         }
555     }
556     return info;
557 }
558
559
560 // ====================
561 //  Public Slots:
562 // ====================
563 void Network::setNetworkName(const QString &networkName)
564 {
565     _networkName = networkName;
566     SYNC(ARG(networkName))
567     emit networkNameSet(networkName);
568     emit configChanged();
569 }
570
571
572 void Network::setCurrentServer(const QString &currentServer)
573 {
574     _currentServer = currentServer;
575     SYNC(ARG(currentServer))
576     emit currentServerSet(currentServer);
577 }
578
579
580 void Network::setConnected(bool connected)
581 {
582     if (_connected == connected)
583         return;
584
585     _connected = connected;
586     if (!connected) {
587         setMyNick(QString());
588         setCurrentServer(QString());
589         removeChansAndUsers();
590     }
591     SYNC(ARG(connected))
592     emit connectedSet(connected);
593 }
594
595
596 //void Network::setConnectionState(ConnectionState state) {
597 void Network::setConnectionState(int state)
598 {
599     _connectionState = (ConnectionState)state;
600     //qDebug() << "netstate" << networkId() << networkName() << state;
601     SYNC(ARG(state))
602     emit connectionStateSet(_connectionState);
603 }
604
605
606 void Network::setMyNick(const QString &nickname)
607 {
608     _myNick = nickname;
609     if (!_myNick.isEmpty() && !ircUser(myNick())) {
610         newIrcUser(myNick());
611     }
612     SYNC(ARG(nickname))
613     emit myNickSet(nickname);
614 }
615
616
617 void Network::setLatency(int latency)
618 {
619     if (_latency == latency)
620         return;
621     _latency = latency;
622     SYNC(ARG(latency))
623 }
624
625
626 void Network::setIdentity(IdentityId id)
627 {
628     _identity = id;
629     SYNC(ARG(id))
630     emit identitySet(id);
631     emit configChanged();
632 }
633
634
635 void Network::setServerList(const QVariantList &serverList)
636 {
637     _serverList = fromVariantList<Server>(serverList);
638     SYNC(ARG(serverList))
639     emit configChanged();
640 }
641
642
643 void Network::setUseRandomServer(bool use)
644 {
645     _useRandomServer = use;
646     SYNC(ARG(use))
647     emit configChanged();
648 }
649
650
651 void Network::setPerform(const QStringList &perform)
652 {
653     _perform = perform;
654     SYNC(ARG(perform))
655     emit configChanged();
656 }
657
658
659 void Network::setUseAutoIdentify(bool use)
660 {
661     _useAutoIdentify = use;
662     SYNC(ARG(use))
663     emit configChanged();
664 }
665
666
667 void Network::setAutoIdentifyService(const QString &service)
668 {
669     _autoIdentifyService = service;
670     SYNC(ARG(service))
671     emit configChanged();
672 }
673
674
675 void Network::setAutoIdentifyPassword(const QString &password)
676 {
677     _autoIdentifyPassword = password;
678     SYNC(ARG(password))
679     emit configChanged();
680 }
681
682
683 void Network::setUseSasl(bool use)
684 {
685     _useSasl = use;
686     SYNC(ARG(use))
687     emit configChanged();
688 }
689
690
691 void Network::setSaslAccount(const QString &account)
692 {
693     _saslAccount = account;
694     SYNC(ARG(account))
695     emit configChanged();
696 }
697
698
699 void Network::setSaslPassword(const QString &password)
700 {
701     _saslPassword = password;
702     SYNC(ARG(password))
703     emit configChanged();
704 }
705
706
707 void Network::setUseAutoReconnect(bool use)
708 {
709     _useAutoReconnect = use;
710     SYNC(ARG(use))
711     emit configChanged();
712 }
713
714
715 void Network::setAutoReconnectInterval(quint32 interval)
716 {
717     _autoReconnectInterval = interval;
718     SYNC(ARG(interval))
719     emit configChanged();
720 }
721
722
723 void Network::setAutoReconnectRetries(quint16 retries)
724 {
725     _autoReconnectRetries = retries;
726     SYNC(ARG(retries))
727     emit configChanged();
728 }
729
730
731 void Network::setUnlimitedReconnectRetries(bool unlimited)
732 {
733     _unlimitedReconnectRetries = unlimited;
734     SYNC(ARG(unlimited))
735     emit configChanged();
736 }
737
738
739 void Network::setRejoinChannels(bool rejoin)
740 {
741     _rejoinChannels = rejoin;
742     SYNC(ARG(rejoin))
743     emit configChanged();
744 }
745
746
747 void Network::addSupport(const QString &param, const QString &value)
748 {
749     if (!_supports.contains(param)) {
750         _supports[param] = value;
751         SYNC(ARG(param), ARG(value))
752     }
753 }
754
755
756 void Network::removeSupport(const QString &param)
757 {
758     if (_supports.contains(param)) {
759         _supports.remove(param);
760         SYNC(ARG(param))
761     }
762 }
763
764
765 QVariantMap Network::initSupports() const
766 {
767     QVariantMap supports;
768     QHashIterator<QString, QString> iter(_supports);
769     while (iter.hasNext()) {
770         iter.next();
771         supports[iter.key()] = iter.value();
772     }
773     return supports;
774 }
775
776
777 QVariantMap Network::initIrcUsersAndChannels() const
778 {
779     QVariantMap usersAndChannels;
780     QVariantMap users;
781     QVariantMap channels;
782
783     QHash<QString, IrcUser *>::const_iterator userIter = _ircUsers.constBegin();
784     QHash<QString, IrcUser *>::const_iterator userIterEnd = _ircUsers.constEnd();
785     while (userIter != userIterEnd) {
786         users[userIter.value()->hostmask()] = userIter.value()->toVariantMap();
787         userIter++;
788     }
789     usersAndChannels["users"] = users;
790
791     QHash<QString, IrcChannel *>::const_iterator channelIter = _ircChannels.constBegin();
792     QHash<QString, IrcChannel *>::const_iterator channelIterEnd = _ircChannels.constEnd();
793     while (channelIter != channelIterEnd) {
794         channels[channelIter.value()->name()] = channelIter.value()->toVariantMap();
795         channelIter++;
796     }
797     usersAndChannels["channels"] = channels;
798
799     return usersAndChannels;
800 }
801
802
803 void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels)
804 {
805     Q_ASSERT(proxy());
806     if (isInitialized()) {
807         qWarning() << "Network" << networkId() << "received init data for users and channels allthough there allready are known users or channels!";
808         return;
809     }
810
811     QVariantMap users = usersAndChannels.value("users").toMap();
812     QVariantMap::const_iterator userIter = users.constBegin();
813     QVariantMap::const_iterator userIterEnd = users.constEnd();
814     while (userIter != userIterEnd) {
815         newIrcUser(userIter.key(), userIter.value().toMap());
816         userIter++;
817     }
818
819     QVariantMap channels = usersAndChannels.value("channels").toMap();
820     QVariantMap::const_iterator channelIter = channels.constBegin();
821     QVariantMap::const_iterator channelIterEnd = channels.constEnd();
822     while (channelIter != channelIterEnd) {
823         newIrcChannel(channelIter.key(), channelIter.value().toMap());
824         channelIter++;
825     }
826 }
827
828
829 void Network::initSetSupports(const QVariantMap &supports)
830 {
831     QMapIterator<QString, QVariant> iter(supports);
832     while (iter.hasNext()) {
833         iter.next();
834         addSupport(iter.key(), iter.value().toString());
835     }
836 }
837
838
839 IrcUser *Network::updateNickFromMask(const QString &mask)
840 {
841     QString nick(nickFromMask(mask).toLower());
842     IrcUser *ircuser;
843
844     if (_ircUsers.contains(nick)) {
845         ircuser = _ircUsers[nick];
846         ircuser->updateHostmask(mask);
847     }
848     else {
849         ircuser = newIrcUser(mask);
850     }
851     return ircuser;
852 }
853
854
855 void Network::ircUserNickChanged(QString newnick)
856 {
857     QString oldnick = _ircUsers.key(qobject_cast<IrcUser *>(sender()));
858
859     if (oldnick.isNull())
860         return;
861
862     if (newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
863
864     if (myNick().toLower() == oldnick)
865         setMyNick(newnick);
866 }
867
868
869 void Network::emitConnectionError(const QString &errorMsg)
870 {
871     emit connectionError(errorMsg);
872 }
873
874
875 // ====================
876 //  Private:
877 // ====================
878 void Network::determinePrefixes() const
879 {
880     // seems like we have to construct them first
881     QString prefix = support("PREFIX");
882
883     if (prefix.startsWith("(") && prefix.contains(")")) {
884         _prefixes = prefix.section(")", 1);
885         _prefixModes = prefix.mid(1).section(")", 0, 0);
886     }
887     else {
888         QString defaultPrefixes("~&@%+");
889         QString defaultPrefixModes("qaohv");
890
891         if (prefix.isEmpty()) {
892             _prefixes = defaultPrefixes;
893             _prefixModes = defaultPrefixModes;
894             return;
895         }
896         // clear the existing modes, just in case we're run multiple times
897         _prefixes = QString();
898         _prefixModes = QString();
899
900         // we just assume that in PREFIX are only prefix chars stored
901         for (int i = 0; i < defaultPrefixes.size(); i++) {
902             if (prefix.contains(defaultPrefixes[i])) {
903                 _prefixes += defaultPrefixes[i];
904                 _prefixModes += defaultPrefixModes[i];
905             }
906         }
907         // check for success
908         if (!_prefixes.isNull())
909             return;
910
911         // well... our assumption was obviously wrong...
912         // check if it's only prefix modes
913         for (int i = 0; i < defaultPrefixes.size(); i++) {
914             if (prefix.contains(defaultPrefixModes[i])) {
915                 _prefixes += defaultPrefixes[i];
916                 _prefixModes += defaultPrefixModes[i];
917             }
918         }
919         // now we've done all we've could...
920     }
921 }
922
923
924 /************************************************************************
925  * NetworkInfo
926  ************************************************************************/
927
928 NetworkInfo::NetworkInfo()
929     : networkId(0),
930     identity(1),
931     useRandomServer(false),
932     useAutoIdentify(false),
933     autoIdentifyService("NickServ"),
934     useSasl(false),
935     useAutoReconnect(true),
936     autoReconnectInterval(60),
937     autoReconnectRetries(20),
938     unlimitedReconnectRetries(false),
939     rejoinChannels(true)
940 {
941 }
942
943
944 bool NetworkInfo::operator==(const NetworkInfo &other) const
945 {
946     if (networkId != other.networkId) return false;
947     if (networkName != other.networkName) return false;
948     if (identity != other.identity) return false;
949     if (codecForServer != other.codecForServer) return false;
950     if (codecForEncoding != other.codecForEncoding) return false;
951     if (codecForDecoding != other.codecForDecoding) return false;
952     if (serverList != other.serverList) return false;
953     if (useRandomServer != other.useRandomServer) return false;
954     if (perform != other.perform) return false;
955     if (useAutoIdentify != other.useAutoIdentify) return false;
956     if (autoIdentifyService != other.autoIdentifyService) return false;
957     if (autoIdentifyPassword != other.autoIdentifyPassword) return false;
958     if (useSasl != other.useSasl) return false;
959     if (saslAccount != other.saslAccount) return false;
960     if (saslPassword != other.saslPassword) return false;
961     if (useAutoReconnect != other.useAutoReconnect) return false;
962     if (autoReconnectInterval != other.autoReconnectInterval) return false;
963     if (autoReconnectRetries != other.autoReconnectRetries) return false;
964     if (unlimitedReconnectRetries != other.unlimitedReconnectRetries) return false;
965     if (rejoinChannels != other.rejoinChannels) return false;
966     return true;
967 }
968
969
970 bool NetworkInfo::operator!=(const NetworkInfo &other) const
971 {
972     return !(*this == other);
973 }
974
975
976 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info)
977 {
978     QVariantMap i;
979     i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
980     i["NetworkName"] = info.networkName;
981     i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
982     i["CodecForServer"] = info.codecForServer;
983     i["CodecForEncoding"] = info.codecForEncoding;
984     i["CodecForDecoding"] = info.codecForDecoding;
985     i["ServerList"] = toVariantList(info.serverList);
986     i["UseRandomServer"] = info.useRandomServer;
987     i["Perform"] = info.perform;
988     i["UseAutoIdentify"] = info.useAutoIdentify;
989     i["AutoIdentifyService"] = info.autoIdentifyService;
990     i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
991     i["UseSasl"] = info.useSasl;
992     i["SaslAccount"] = info.saslAccount;
993     i["SaslPassword"] = info.saslPassword;
994     i["UseAutoReconnect"] = info.useAutoReconnect;
995     i["AutoReconnectInterval"] = info.autoReconnectInterval;
996     i["AutoReconnectRetries"] = info.autoReconnectRetries;
997     i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
998     i["RejoinChannels"] = info.rejoinChannels;
999     out << i;
1000     return out;
1001 }
1002
1003
1004 QDataStream &operator>>(QDataStream &in, NetworkInfo &info)
1005 {
1006     QVariantMap i;
1007     in >> i;
1008     info.networkId = i["NetworkId"].value<NetworkId>();
1009     info.networkName = i["NetworkName"].toString();
1010     info.identity = i["Identity"].value<IdentityId>();
1011     info.codecForServer = i["CodecForServer"].toByteArray();
1012     info.codecForEncoding = i["CodecForEncoding"].toByteArray();
1013     info.codecForDecoding = i["CodecForDecoding"].toByteArray();
1014     info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
1015     info.useRandomServer = i["UseRandomServer"].toBool();
1016     info.perform = i["Perform"].toStringList();
1017     info.useAutoIdentify = i["UseAutoIdentify"].toBool();
1018     info.autoIdentifyService = i["AutoIdentifyService"].toString();
1019     info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
1020     info.useSasl = i["UseSasl"].toBool();
1021     info.saslAccount = i["SaslAccount"].toString();
1022     info.saslPassword = i["SaslPassword"].toString();
1023     info.useAutoReconnect = i["UseAutoReconnect"].toBool();
1024     info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
1025     info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
1026     info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
1027     info.rejoinChannels = i["RejoinChannels"].toBool();
1028     return in;
1029 }
1030
1031
1032 QDebug operator<<(QDebug dbg, const NetworkInfo &i)
1033 {
1034     dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
1035     << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
1036     << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
1037     << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
1038     << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
1039     << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
1040     << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
1041     << " rejoinChannels = " << i.rejoinChannels << ")";
1042     return dbg.space();
1043 }
1044
1045
1046 QDataStream &operator<<(QDataStream &out, const Network::Server &server)
1047 {
1048     QVariantMap serverMap;
1049     serverMap["Host"] = server.host;
1050     serverMap["Port"] = server.port;
1051     serverMap["Password"] = server.password;
1052     serverMap["UseSSL"] = server.useSsl;
1053     serverMap["sslVersion"] = server.sslVersion;
1054     serverMap["UseProxy"] = server.useProxy;
1055     serverMap["ProxyType"] = server.proxyType;
1056     serverMap["ProxyHost"] = server.proxyHost;
1057     serverMap["ProxyPort"] = server.proxyPort;
1058     serverMap["ProxyUser"] = server.proxyUser;
1059     serverMap["ProxyPass"] = server.proxyPass;
1060     out << serverMap;
1061     return out;
1062 }
1063
1064
1065 QDataStream &operator>>(QDataStream &in, Network::Server &server)
1066 {
1067     QVariantMap serverMap;
1068     in >> serverMap;
1069     server.host = serverMap["Host"].toString();
1070     server.port = serverMap["Port"].toUInt();
1071     server.password = serverMap["Password"].toString();
1072     server.useSsl = serverMap["UseSSL"].toBool();
1073     server.sslVersion = serverMap["sslVersion"].toInt();
1074     server.useProxy = serverMap["UseProxy"].toBool();
1075     server.proxyType = serverMap["ProxyType"].toInt();
1076     server.proxyHost = serverMap["ProxyHost"].toString();
1077     server.proxyPort = serverMap["ProxyPort"].toUInt();
1078     server.proxyUser = serverMap["ProxyUser"].toString();
1079     server.proxyPass = serverMap["ProxyPass"].toString();
1080     return in;
1081 }
1082
1083
1084 bool Network::Server::operator==(const Server &other) const
1085 {
1086     if (host != other.host) return false;
1087     if (port != other.port) return false;
1088     if (password != other.password) return false;
1089     if (useSsl != other.useSsl) return false;
1090     if (sslVersion != other.sslVersion) return false;
1091     if (useProxy != other.useProxy) return false;
1092     if (proxyType != other.proxyType) return false;
1093     if (proxyHost != other.proxyHost) return false;
1094     if (proxyPort != other.proxyPort) return false;
1095     if (proxyUser != other.proxyUser) return false;
1096     if (proxyPass != other.proxyPass) return false;
1097     return true;
1098 }
1099
1100
1101 bool Network::Server::operator!=(const Server &other) const
1102 {
1103     return !(*this == other);
1104 }
1105
1106
1107 QDebug operator<<(QDebug dbg, const Network::Server &server)
1108 {
1109     dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << server.useSsl << ")";
1110     return dbg.space();
1111 }