Handle STATUSMSG messages
[quassel.git] / src / common / network.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2015 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
709 // There's potentially a lot of users and channels, so it makes sense to optimize the format of this.
710 // Rather than sending a thousand maps with identical keys, we convert this into one map containing lists
711 // where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times.
712 // Benchmarks have shown space savings of around 56%, resulting in saving several MBs worth of data on sync
713 // (without compression) with a decent amount of IrcUsers.
714 QVariantMap Network::initIrcUsersAndChannels() const
715 {
716     QVariantMap usersAndChannels;
717
718     if (_ircUsers.count()) {
719         QHash<QString, QVariantList> users;
720         QHash<QString, IrcUser *>::const_iterator it = _ircUsers.begin();
721         QHash<QString, IrcUser *>::const_iterator end = _ircUsers.end();
722         while (it != end) {
723             const QVariantMap &map = it.value()->toVariantMap();
724             QVariantMap::const_iterator mapiter = map.begin();
725             while (mapiter != map.end()) {
726                 users[mapiter.key()] << mapiter.value();
727                 ++mapiter;
728             }
729             ++it;
730         }
731         // Can't have a container with a value type != QVariant in a QVariant :(
732         // However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above.
733         QVariantMap userMap;
734         foreach(const QString &key, users.keys())
735             userMap[key] = users[key];
736         usersAndChannels["Users"] = userMap;
737     }
738
739     if (_ircChannels.count()) {
740         QHash<QString, QVariantList> channels;
741         QHash<QString, IrcChannel *>::const_iterator it = _ircChannels.begin();
742         QHash<QString, IrcChannel *>::const_iterator end = _ircChannels.end();
743         while (it != end) {
744             const QVariantMap &map = it.value()->toVariantMap();
745             QVariantMap::const_iterator mapiter = map.begin();
746             while (mapiter != map.end()) {
747                 channels[mapiter.key()] << mapiter.value();
748                 ++mapiter;
749             }
750             ++it;
751         }
752         QVariantMap channelMap;
753         foreach(const QString &key, channels.keys())
754             channelMap[key] = channels[key];
755         usersAndChannels["Channels"] = channelMap;
756     }
757
758     return usersAndChannels;
759 }
760
761
762 void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels)
763 {
764     Q_ASSERT(proxy());
765     if (isInitialized()) {
766         qWarning() << "Network" << networkId() << "received init data for users and channels although there already are known users or channels!";
767         return;
768     }
769
770     // toMap() and toList() are cheap, so we can avoid copying to lists...
771     // However, we really have to make sure to never accidentally detach from the shared data!
772
773     const QVariantMap &users = usersAndChannels["Users"].toMap();
774
775     // sanity check
776     int count = users["nick"].toList().count();
777     foreach(const QString &key, users.keys()) {
778         if (users[key].toList().count() != count) {
779             qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
780             return;
781         }
782     }
783
784     // now create the individual IrcUsers
785     for(int i = 0; i < count; i++) {
786         QVariantMap map;
787         foreach(const QString &key, users.keys())
788             map[key] = users[key].toList().at(i);
789         newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
790     }
791
792     // same thing for IrcChannels
793     const QVariantMap &channels = usersAndChannels["Channels"].toMap();
794
795     // sanity check
796     count = channels["name"].toList().count();
797     foreach(const QString &key, channels.keys()) {
798         if (channels[key].toList().count() != count) {
799             qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
800             return;
801         }
802     }
803     // now create the individual IrcChannels
804     for(int i = 0; i < count; i++) {
805         QVariantMap map;
806         foreach(const QString &key, channels.keys())
807             map[key] = channels[key].toList().at(i);
808         newIrcChannel(map["name"].toString(), map);
809     }
810 }
811
812
813 void Network::initSetSupports(const QVariantMap &supports)
814 {
815     QMapIterator<QString, QVariant> iter(supports);
816     while (iter.hasNext()) {
817         iter.next();
818         addSupport(iter.key(), iter.value().toString());
819     }
820 }
821
822
823 IrcUser *Network::updateNickFromMask(const QString &mask)
824 {
825     QString nick(nickFromMask(mask).toLower());
826     IrcUser *ircuser;
827
828     if (_ircUsers.contains(nick)) {
829         ircuser = _ircUsers[nick];
830         ircuser->updateHostmask(mask);
831     }
832     else {
833         ircuser = newIrcUser(mask);
834     }
835     return ircuser;
836 }
837
838
839 void Network::ircUserNickChanged(QString newnick)
840 {
841     QString oldnick = _ircUsers.key(qobject_cast<IrcUser *>(sender()));
842
843     if (oldnick.isNull())
844         return;
845
846     if (newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
847
848     if (myNick().toLower() == oldnick)
849         setMyNick(newnick);
850 }
851
852
853 void Network::emitConnectionError(const QString &errorMsg)
854 {
855     emit connectionError(errorMsg);
856 }
857
858
859 // ====================
860 //  Private:
861 // ====================
862 void Network::determinePrefixes() const
863 {
864     // seems like we have to construct them first
865     QString prefix = support("PREFIX");
866
867     if (prefix.startsWith("(") && prefix.contains(")")) {
868         _prefixes = prefix.section(")", 1);
869         _prefixModes = prefix.mid(1).section(")", 0, 0);
870     }
871     else {
872         QString defaultPrefixes("~&@%+");
873         QString defaultPrefixModes("qaohv");
874
875         if (prefix.isEmpty()) {
876             _prefixes = defaultPrefixes;
877             _prefixModes = defaultPrefixModes;
878             return;
879         }
880         // clear the existing modes, just in case we're run multiple times
881         _prefixes = QString();
882         _prefixModes = QString();
883
884         // we just assume that in PREFIX are only prefix chars stored
885         for (int i = 0; i < defaultPrefixes.size(); i++) {
886             if (prefix.contains(defaultPrefixes[i])) {
887                 _prefixes += defaultPrefixes[i];
888                 _prefixModes += defaultPrefixModes[i];
889             }
890         }
891         // check for success
892         if (!_prefixes.isNull())
893             return;
894
895         // well... our assumption was obviously wrong...
896         // check if it's only prefix modes
897         for (int i = 0; i < defaultPrefixes.size(); i++) {
898             if (prefix.contains(defaultPrefixModes[i])) {
899                 _prefixes += defaultPrefixes[i];
900                 _prefixModes += defaultPrefixModes[i];
901             }
902         }
903         // now we've done all we've could...
904     }
905 }
906
907
908 /************************************************************************
909  * NetworkInfo
910  ************************************************************************/
911
912 NetworkInfo::NetworkInfo()
913     : networkId(0),
914     identity(1),
915     useRandomServer(false),
916     useAutoIdentify(false),
917     autoIdentifyService("NickServ"),
918     useSasl(false),
919     useAutoReconnect(true),
920     autoReconnectInterval(60),
921     autoReconnectRetries(20),
922     unlimitedReconnectRetries(false),
923     rejoinChannels(true)
924 {
925 }
926
927
928 bool NetworkInfo::operator==(const NetworkInfo &other) const
929 {
930     if (networkId != other.networkId) return false;
931     if (networkName != other.networkName) return false;
932     if (identity != other.identity) return false;
933     if (codecForServer != other.codecForServer) return false;
934     if (codecForEncoding != other.codecForEncoding) return false;
935     if (codecForDecoding != other.codecForDecoding) return false;
936     if (serverList != other.serverList) return false;
937     if (useRandomServer != other.useRandomServer) return false;
938     if (perform != other.perform) return false;
939     if (useAutoIdentify != other.useAutoIdentify) return false;
940     if (autoIdentifyService != other.autoIdentifyService) return false;
941     if (autoIdentifyPassword != other.autoIdentifyPassword) return false;
942     if (useSasl != other.useSasl) return false;
943     if (saslAccount != other.saslAccount) return false;
944     if (saslPassword != other.saslPassword) return false;
945     if (useAutoReconnect != other.useAutoReconnect) return false;
946     if (autoReconnectInterval != other.autoReconnectInterval) return false;
947     if (autoReconnectRetries != other.autoReconnectRetries) return false;
948     if (unlimitedReconnectRetries != other.unlimitedReconnectRetries) return false;
949     if (rejoinChannels != other.rejoinChannels) return false;
950     return true;
951 }
952
953
954 bool NetworkInfo::operator!=(const NetworkInfo &other) const
955 {
956     return !(*this == other);
957 }
958
959
960 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info)
961 {
962     QVariantMap i;
963     i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
964     i["NetworkName"] = info.networkName;
965     i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
966     i["CodecForServer"] = info.codecForServer;
967     i["CodecForEncoding"] = info.codecForEncoding;
968     i["CodecForDecoding"] = info.codecForDecoding;
969     i["ServerList"] = toVariantList(info.serverList);
970     i["UseRandomServer"] = info.useRandomServer;
971     i["Perform"] = info.perform;
972     i["UseAutoIdentify"] = info.useAutoIdentify;
973     i["AutoIdentifyService"] = info.autoIdentifyService;
974     i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
975     i["UseSasl"] = info.useSasl;
976     i["SaslAccount"] = info.saslAccount;
977     i["SaslPassword"] = info.saslPassword;
978     i["UseAutoReconnect"] = info.useAutoReconnect;
979     i["AutoReconnectInterval"] = info.autoReconnectInterval;
980     i["AutoReconnectRetries"] = info.autoReconnectRetries;
981     i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
982     i["RejoinChannels"] = info.rejoinChannels;
983     out << i;
984     return out;
985 }
986
987
988 QDataStream &operator>>(QDataStream &in, NetworkInfo &info)
989 {
990     QVariantMap i;
991     in >> i;
992     info.networkId = i["NetworkId"].value<NetworkId>();
993     info.networkName = i["NetworkName"].toString();
994     info.identity = i["Identity"].value<IdentityId>();
995     info.codecForServer = i["CodecForServer"].toByteArray();
996     info.codecForEncoding = i["CodecForEncoding"].toByteArray();
997     info.codecForDecoding = i["CodecForDecoding"].toByteArray();
998     info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
999     info.useRandomServer = i["UseRandomServer"].toBool();
1000     info.perform = i["Perform"].toStringList();
1001     info.useAutoIdentify = i["UseAutoIdentify"].toBool();
1002     info.autoIdentifyService = i["AutoIdentifyService"].toString();
1003     info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
1004     info.useSasl = i["UseSasl"].toBool();
1005     info.saslAccount = i["SaslAccount"].toString();
1006     info.saslPassword = i["SaslPassword"].toString();
1007     info.useAutoReconnect = i["UseAutoReconnect"].toBool();
1008     info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
1009     info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
1010     info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
1011     info.rejoinChannels = i["RejoinChannels"].toBool();
1012     return in;
1013 }
1014
1015
1016 QDebug operator<<(QDebug dbg, const NetworkInfo &i)
1017 {
1018     dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
1019     << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
1020     << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
1021     << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
1022     << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
1023     << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
1024     << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
1025     << " rejoinChannels = " << i.rejoinChannels << ")";
1026     return dbg.space();
1027 }
1028
1029
1030 QDataStream &operator<<(QDataStream &out, const Network::Server &server)
1031 {
1032     QVariantMap serverMap;
1033     serverMap["Host"] = server.host;
1034     serverMap["Port"] = server.port;
1035     serverMap["Password"] = server.password;
1036     serverMap["UseSSL"] = server.useSsl;
1037     serverMap["sslVersion"] = server.sslVersion;
1038     serverMap["UseProxy"] = server.useProxy;
1039     serverMap["ProxyType"] = server.proxyType;
1040     serverMap["ProxyHost"] = server.proxyHost;
1041     serverMap["ProxyPort"] = server.proxyPort;
1042     serverMap["ProxyUser"] = server.proxyUser;
1043     serverMap["ProxyPass"] = server.proxyPass;
1044     out << serverMap;
1045     return out;
1046 }
1047
1048
1049 QDataStream &operator>>(QDataStream &in, Network::Server &server)
1050 {
1051     QVariantMap serverMap;
1052     in >> serverMap;
1053     server.host = serverMap["Host"].toString();
1054     server.port = serverMap["Port"].toUInt();
1055     server.password = serverMap["Password"].toString();
1056     server.useSsl = serverMap["UseSSL"].toBool();
1057     server.sslVersion = serverMap["sslVersion"].toInt();
1058     server.useProxy = serverMap["UseProxy"].toBool();
1059     server.proxyType = serverMap["ProxyType"].toInt();
1060     server.proxyHost = serverMap["ProxyHost"].toString();
1061     server.proxyPort = serverMap["ProxyPort"].toUInt();
1062     server.proxyUser = serverMap["ProxyUser"].toString();
1063     server.proxyPass = serverMap["ProxyPass"].toString();
1064     return in;
1065 }
1066
1067
1068 bool Network::Server::operator==(const Server &other) const
1069 {
1070     if (host != other.host) return false;
1071     if (port != other.port) return false;
1072     if (password != other.password) return false;
1073     if (useSsl != other.useSsl) return false;
1074     if (sslVersion != other.sslVersion) return false;
1075     if (useProxy != other.useProxy) return false;
1076     if (proxyType != other.proxyType) return false;
1077     if (proxyHost != other.proxyHost) return false;
1078     if (proxyPort != other.proxyPort) return false;
1079     if (proxyUser != other.proxyUser) return false;
1080     if (proxyPass != other.proxyPass) return false;
1081     return true;
1082 }
1083
1084
1085 bool Network::Server::operator!=(const Server &other) const
1086 {
1087     return !(*this == other);
1088 }
1089
1090
1091 QDebug operator<<(QDebug dbg, const Network::Server &server)
1092 {
1093     dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << server.useSsl << ")";
1094     return dbg.space();
1095 }