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