Force parsing of PREFIX in RPL_ISUPPORT. Fixes #936
[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
479 // ====================
480 //  Public Slots:
481 // ====================
482 void Network::setNetworkName(const QString &networkName) {
483   _networkName = networkName;
484   SYNC(ARG(networkName))
485   emit networkNameSet(networkName);
486   emit configChanged();
487 }
488
489 void Network::setCurrentServer(const QString &currentServer) {
490   _currentServer = currentServer;
491   SYNC(ARG(currentServer))
492   emit currentServerSet(currentServer);
493 }
494
495 void Network::setConnected(bool connected) {
496   if(_connected == connected)
497     return;
498
499   _connected = connected;
500   if(!connected) {
501     setMyNick(QString());
502     setCurrentServer(QString());
503     removeChansAndUsers();
504   }
505   SYNC(ARG(connected))
506   emit connectedSet(connected);
507 }
508
509 //void Network::setConnectionState(ConnectionState state) {
510 void Network::setConnectionState(int state) {
511   _connectionState = (ConnectionState)state;
512   //qDebug() << "netstate" << networkId() << networkName() << state;
513   SYNC(ARG(state))
514   emit connectionStateSet(_connectionState);
515 }
516
517 void Network::setMyNick(const QString &nickname) {
518   _myNick = nickname;
519   if(!_myNick.isEmpty() && !ircUser(myNick())) {
520     newIrcUser(myNick());
521   }
522   SYNC(ARG(nickname))
523   emit myNickSet(nickname);
524 }
525
526 void Network::setLatency(int latency) {
527   if(_latency == latency)
528     return;
529   _latency = latency;
530   SYNC(ARG(latency))
531 }
532
533 void Network::setIdentity(IdentityId id) {
534   _identity = id;
535   SYNC(ARG(id))
536   emit identitySet(id);
537   emit configChanged();
538 }
539
540 void Network::setServerList(const QVariantList &serverList) {
541   _serverList = fromVariantList<Server>(serverList);
542   SYNC(ARG(serverList))
543   emit configChanged();
544 }
545
546 void Network::setUseRandomServer(bool use) {
547   _useRandomServer = use;
548   SYNC(ARG(use))
549   emit configChanged();
550 }
551
552 void Network::setPerform(const QStringList &perform) {
553   _perform = perform;
554   SYNC(ARG(perform))
555   emit configChanged();
556 }
557
558 void Network::setUseAutoIdentify(bool use) {
559   _useAutoIdentify = use;
560   SYNC(ARG(use))
561   emit configChanged();
562 }
563
564 void Network::setAutoIdentifyService(const QString &service) {
565   _autoIdentifyService = service;
566   SYNC(ARG(service))
567   emit configChanged();
568 }
569
570 void Network::setAutoIdentifyPassword(const QString &password) {
571   _autoIdentifyPassword = password;
572   SYNC(ARG(password))
573   emit configChanged();
574 }
575
576 void Network::setUseSasl(bool use) {
577   _useSasl = use;
578   SYNC(ARG(use))
579   emit configChanged();
580 }
581
582 void Network::setSaslAccount(const QString &account) {
583   _saslAccount = account;
584   SYNC(ARG(account))
585   emit configChanged();
586 }
587
588 void Network::setSaslPassword(const QString &password) {
589   _saslPassword = password;
590   SYNC(ARG(password))
591   emit configChanged();
592 }
593
594 void Network::setUseAutoReconnect(bool use) {
595   _useAutoReconnect = use;
596   SYNC(ARG(use))
597   emit configChanged();
598 }
599
600 void Network::setAutoReconnectInterval(quint32 interval) {
601   _autoReconnectInterval = interval;
602   SYNC(ARG(interval))
603   emit configChanged();
604 }
605
606 void Network::setAutoReconnectRetries(quint16 retries) {
607   _autoReconnectRetries = retries;
608   SYNC(ARG(retries))
609   emit configChanged();
610 }
611
612 void Network::setUnlimitedReconnectRetries(bool unlimited) {
613   _unlimitedReconnectRetries = unlimited;
614   SYNC(ARG(unlimited))
615   emit configChanged();
616 }
617
618 void Network::setRejoinChannels(bool rejoin) {
619   _rejoinChannels = rejoin;
620   SYNC(ARG(rejoin))
621   emit configChanged();
622 }
623
624 void Network::addSupport(const QString &param, const QString &value) {
625   if(!_supports.contains(param)) {
626     _supports[param] = value;
627     SYNC(ARG(param), ARG(value))
628   }
629 }
630
631 void Network::removeSupport(const QString &param) {
632   if(_supports.contains(param)) {
633     _supports.remove(param);
634     SYNC(ARG(param))
635   }
636 }
637
638 QVariantMap Network::initSupports() const {
639   QVariantMap supports;
640   QHashIterator<QString, QString> iter(_supports);
641   while(iter.hasNext()) {
642     iter.next();
643     supports[iter.key()] = iter.value();
644   }
645   return supports;
646 }
647
648 QVariantMap Network::initIrcUsersAndChannels() const {
649   QVariantMap usersAndChannels;
650   QVariantMap users;
651   QVariantMap channels;
652
653   QHash<QString, IrcUser *>::const_iterator userIter = _ircUsers.constBegin();
654   QHash<QString, IrcUser *>::const_iterator userIterEnd = _ircUsers.constEnd();
655   while(userIter != userIterEnd) {
656     users[userIter.value()->hostmask()] = userIter.value()->toVariantMap();
657     userIter++;
658   }
659   usersAndChannels["users"] = users;
660
661   QHash<QString, IrcChannel *>::const_iterator channelIter = _ircChannels.constBegin();
662   QHash<QString, IrcChannel *>::const_iterator channelIterEnd = _ircChannels.constEnd();
663   while(channelIter != channelIterEnd) {
664     channels[channelIter.value()->name()] = channelIter.value()->toVariantMap();
665     channelIter++;
666   }
667   usersAndChannels["channels"] = channels;
668
669   return usersAndChannels;
670 }
671
672 void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels) {
673   Q_ASSERT(proxy());
674   if(isInitialized()) {
675     qWarning() << "Network" << networkId() << "received init data for users and channels allthough there allready are known users or channels!";
676     return;
677   }
678
679   QVariantMap users = usersAndChannels.value("users").toMap();
680   QVariantMap::const_iterator userIter = users.constBegin();
681   QVariantMap::const_iterator userIterEnd = users.constEnd();
682   while(userIter != userIterEnd) {
683     newIrcUser(userIter.key(), userIter.value().toMap());
684     userIter++;
685   }
686
687   QVariantMap channels = usersAndChannels.value("channels").toMap();
688   QVariantMap::const_iterator channelIter = channels.constBegin();
689   QVariantMap::const_iterator channelIterEnd = channels.constEnd();
690   while(channelIter != channelIterEnd) {
691     newIrcChannel(channelIter.key(), channelIter.value().toMap());
692     channelIter++;
693   }
694 }
695
696 void Network::initSetSupports(const QVariantMap &supports) {
697   QMapIterator<QString, QVariant> iter(supports);
698   while(iter.hasNext()) {
699     iter.next();
700     addSupport(iter.key(), iter.value().toString());
701   }
702 }
703
704 IrcUser *Network::updateNickFromMask(const QString &mask) {
705   QString nick(nickFromMask(mask).toLower());
706   IrcUser *ircuser;
707
708   if(_ircUsers.contains(nick)) {
709     ircuser = _ircUsers[nick];
710     ircuser->updateHostmask(mask);
711   } else {
712     ircuser = newIrcUser(mask);
713   }
714   return ircuser;
715 }
716
717 void Network::ircUserNickChanged(QString newnick) {
718   QString oldnick = _ircUsers.key(qobject_cast<IrcUser*>(sender()));
719
720   if(oldnick.isNull())
721     return;
722
723   if(newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
724
725   if(myNick().toLower() == oldnick)
726     setMyNick(newnick);
727 }
728
729 void Network::emitConnectionError(const QString &errorMsg) {
730   emit connectionError(errorMsg);
731 }
732
733 // ====================
734 //  Private:
735 // ====================
736 void Network::determinePrefixes() {
737   // seems like we have to construct them first
738   QString prefix = support("PREFIX");
739
740   if(prefix.startsWith("(") && prefix.contains(")")) {
741     _prefixes = prefix.section(")", 1);
742     _prefixModes = prefix.mid(1).section(")", 0, 0);
743   } else {
744     QString defaultPrefixes("~&@%+");
745     QString defaultPrefixModes("qaohv");
746
747     if(prefix.isEmpty()) {
748       _prefixes = defaultPrefixes;
749       _prefixModes = defaultPrefixModes;
750       return;
751     }
752     // clear the existing modes, just in case we're run multiple times
753     _prefixes = QString();
754     _prefixModes = QString();
755
756     // we just assume that in PREFIX are only prefix chars stored
757     for(int i = 0; i < defaultPrefixes.size(); i++) {
758       if(prefix.contains(defaultPrefixes[i])) {
759         _prefixes += defaultPrefixes[i];
760         _prefixModes += defaultPrefixModes[i];
761       }
762     }
763     // check for success
764     if(!_prefixes.isNull())
765       return;
766
767     // well... our assumption was obviously wrong...
768     // check if it's only prefix modes
769     for(int i = 0; i < defaultPrefixes.size(); i++) {
770       if(prefix.contains(defaultPrefixModes[i])) {
771         _prefixes += defaultPrefixes[i];
772         _prefixModes += defaultPrefixModes[i];
773       }
774     }
775     // now we've done all we've could...
776   }
777 }
778
779 /************************************************************************
780  * NetworkInfo
781  ************************************************************************/
782
783 NetworkInfo::NetworkInfo()
784 : networkId(0),
785   identity(1),
786   useRandomServer(false),
787   useAutoIdentify(false),
788   autoIdentifyService("NickServ"),
789   useSasl(false),
790   useAutoReconnect(true),
791   autoReconnectInterval(60),
792   autoReconnectRetries(20),
793   unlimitedReconnectRetries(false),
794   rejoinChannels(true)
795 {
796
797 }
798
799 bool NetworkInfo::operator==(const NetworkInfo &other) const {
800   if(networkId != other.networkId) return false;
801   if(networkName != other.networkName) return false;
802   if(identity != other.identity) return false;
803   if(codecForServer != other.codecForServer) return false;
804   if(codecForEncoding != other.codecForEncoding) return false;
805   if(codecForDecoding != other.codecForDecoding) return false;
806   if(serverList != other.serverList) return false;
807   if(useRandomServer != other.useRandomServer) return false;
808   if(perform != other.perform) return false;
809   if(useAutoIdentify != other.useAutoIdentify) return false;
810   if(autoIdentifyService != other.autoIdentifyService) return false;
811   if(autoIdentifyPassword != other.autoIdentifyPassword) return false;
812   if(useSasl != other.useSasl) return false;
813   if(saslAccount != other.saslAccount) return false;
814   if(saslPassword != other.saslPassword) return false;
815   if(useAutoReconnect != other.useAutoReconnect) return false;
816   if(autoReconnectInterval != other.autoReconnectInterval) return false;
817   if(autoReconnectRetries != other.autoReconnectRetries) return false;
818   if(unlimitedReconnectRetries != other.unlimitedReconnectRetries) return false;
819   if(rejoinChannels != other.rejoinChannels) return false;
820   return true;
821 }
822
823 bool NetworkInfo::operator!=(const NetworkInfo &other) const {
824   return !(*this == other);
825 }
826
827 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info) {
828   QVariantMap i;
829   i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
830   i["NetworkName"] = info.networkName;
831   i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
832   i["CodecForServer"] = info.codecForServer;
833   i["CodecForEncoding"] = info.codecForEncoding;
834   i["CodecForDecoding"] = info.codecForDecoding;
835   i["ServerList"] = toVariantList(info.serverList);
836   i["UseRandomServer"] = info.useRandomServer;
837   i["Perform"] = info.perform;
838   i["UseAutoIdentify"] = info.useAutoIdentify;
839   i["AutoIdentifyService"] = info.autoIdentifyService;
840   i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
841   i["UseSasl"] = info.useSasl;
842   i["SaslAccount"] = info.saslAccount;
843   i["SaslPassword"] = info.saslPassword;
844   i["UseAutoReconnect"] = info.useAutoReconnect;
845   i["AutoReconnectInterval"] = info.autoReconnectInterval;
846   i["AutoReconnectRetries"] = info.autoReconnectRetries;
847   i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
848   i["RejoinChannels"] = info.rejoinChannels;
849   out << i;
850   return out;
851 }
852
853 QDataStream &operator>>(QDataStream &in, NetworkInfo &info) {
854   QVariantMap i;
855   in >> i;
856   info.networkId = i["NetworkId"].value<NetworkId>();
857   info.networkName = i["NetworkName"].toString();
858   info.identity = i["Identity"].value<IdentityId>();
859   info.codecForServer = i["CodecForServer"].toByteArray();
860   info.codecForEncoding = i["CodecForEncoding"].toByteArray();
861   info.codecForDecoding = i["CodecForDecoding"].toByteArray();
862   info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
863   info.useRandomServer = i["UseRandomServer"].toBool();
864   info.perform = i["Perform"].toStringList();
865   info.useAutoIdentify = i["UseAutoIdentify"].toBool();
866   info.autoIdentifyService = i["AutoIdentifyService"].toString();
867   info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
868   info.useSasl = i["UseSasl"].toBool();
869   info.saslAccount = i["SaslAccount"].toString();
870   info.saslPassword = i["SaslPassword"].toString();
871   info.useAutoReconnect = i["UseAutoReconnect"].toBool();
872   info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
873   info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
874   info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
875   info.rejoinChannels = i["RejoinChannels"].toBool();
876   return in;
877 }
878
879 QDebug operator<<(QDebug dbg, const NetworkInfo &i) {
880   dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
881                 << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
882                 << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
883                 << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
884                 << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
885                 << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
886                 << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
887                 << " rejoinChannels = " << i.rejoinChannels << ")";
888   return dbg.space();
889 }
890
891 QDataStream &operator<<(QDataStream &out, const Network::Server &server) {
892   QVariantMap serverMap;
893   serverMap["Host"] = server.host;
894   serverMap["Port"] = server.port;
895   serverMap["Password"] = server.password;
896   serverMap["UseSSL"] = server.useSsl;
897   serverMap["sslVersion"] = server.sslVersion;
898   serverMap["UseProxy"] = server.useProxy;
899   serverMap["ProxyType"] = server.proxyType;
900   serverMap["ProxyHost"] = server.proxyHost;
901   serverMap["ProxyPort"] = server.proxyPort;
902   serverMap["ProxyUser"] = server.proxyUser;
903   serverMap["ProxyPass"] = server.proxyPass;
904   out << serverMap;
905   return out;
906 }
907
908 QDataStream &operator>>(QDataStream &in, Network::Server &server) {
909   QVariantMap serverMap;
910   in >> serverMap;
911   server.host = serverMap["Host"].toString();
912   server.port = serverMap["Port"].toUInt();
913   server.password = serverMap["Password"].toString();
914   server.useSsl = serverMap["UseSSL"].toBool();
915   server.sslVersion = serverMap["sslVersion"].toInt();
916   server.useProxy = serverMap["UseProxy"].toBool();
917   server.proxyType = serverMap["ProxyType"].toInt();
918   server.proxyHost = serverMap["ProxyHost"].toString();
919   server.proxyPort = serverMap["ProxyPort"].toUInt();
920   server.proxyUser = serverMap["ProxyUser"].toString();
921   server.proxyPass = serverMap["ProxyPass"].toString();
922   return in;
923 }
924
925
926 bool Network::Server::operator==(const Server &other) const {
927   if(host != other.host) return false;
928   if(port != other.port) return false;
929   if(password != other.password) return false;
930   if(useSsl != other.useSsl) return false;
931   if(sslVersion != other.sslVersion) return false;
932   if(useProxy != other.useProxy) return false;
933   if(proxyType != other.proxyType) return false;
934   if(proxyHost != other.proxyHost) return false;
935   if(proxyPort != other.proxyPort) return false;
936   if(proxyUser != other.proxyUser) return false;
937   if(proxyPass != other.proxyPass) return false;
938   return true;
939 }
940
941 bool Network::Server::operator!=(const Server &other) const {
942   return !(*this == other);
943 }
944
945 QDebug operator<<(QDebug dbg, const Network::Server &server) {
946   dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << server.useSsl << ")";
947   return dbg.space();
948 }