fixed inconsistency issues. Upgrade and Distclean is strongly recommended
[quassel.git] / src / common / network.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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 "network.h"
21
22 #include "signalproxy.h"
23 #include "ircuser.h"
24 #include "ircchannel.h"
25
26 #include <QDebug>
27 #include <QTextCodec>
28
29 #include "util.h"
30
31 // ====================
32 //  Public:
33 // ====================
34 Network::Network(const NetworkId &networkid, QObject *parent) : SyncableObject(parent),
35     _networkId(networkid),
36     _identity(0),
37     _myNick(QString()),
38     _networkName(QString("<not initialized>")),
39     _currentServer(QString()),
40     _connected(false),
41     _connectionState(Disconnected),
42     _prefixes(QString()),
43     _prefixModes(QString()),
44     _proxy(0),
45     _codecForEncoding(0),
46     _codecForDecoding(0)
47 {
48   setObjectName(QString::number(networkid.toInt()));
49 }
50
51 // I think this is unnecessary since IrcUsers have us as their daddy :)
52
53 Network::~Network() {
54 //  QHashIterator<QString, IrcUser *> ircuser(_ircUsers);
55 //  while (ircuser.hasNext()) {
56 //    ircuser.next();
57 //    delete ircuser.value();
58 //  }
59 //  qDebug() << "Destroying net" << networkName() << networkId();
60 }
61
62
63 NetworkId Network::networkId() const {
64   return _networkId;
65 }
66
67 SignalProxy *Network::proxy() const {
68   return _proxy;
69 }
70
71 void Network::setProxy(SignalProxy *proxy) {
72   _proxy = proxy;
73   //proxy->synchronize(this);  // we should to this explicitly from the outside!
74 }
75
76 bool Network::isMyNick(const QString &nick) const {
77   return (myNick().toLower() == nick.toLower());
78 }
79
80 bool Network::isMe(IrcUser *ircuser) const {
81   return (ircuser->nick().toLower() == myNick().toLower());
82 }
83
84 bool Network::isChannelName(const QString &channelname) const {
85   if(channelname.isEmpty())
86     return false;
87   
88   if(supports("CHANTYPES"))
89     return support("CHANTYPES").contains(channelname[0]);
90   else
91     return QString("#&!+").contains(channelname[0]);
92 }
93
94 bool Network::isConnected() const {
95   return _connected;
96 }
97
98 //Network::ConnectionState Network::connectionState() const {
99 int Network::connectionState() const {
100   return _connectionState;
101 }
102
103 NetworkInfo Network::networkInfo() const {
104   NetworkInfo info;
105   info.networkName = networkName();
106   info.networkId = networkId();
107   info.identity = identity();
108   info.codecForEncoding = codecForEncoding();
109   info.codecForDecoding = codecForDecoding();
110   info.serverList = serverList();
111   return info;
112 }
113
114 void Network::setNetworkInfo(const NetworkInfo &info) {
115   // we don't set our ID!
116   if(!info.networkName.isEmpty() && info.networkName != networkName()) setNetworkName(info.networkName);
117   if(info.identity > 0 && info.identity != identity()) setIdentity(info.identity);
118   if(!info.codecForEncoding.isEmpty() && info.codecForEncoding != codecForEncoding())
119     setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
120   if(!info.codecForDecoding.isEmpty() && info.codecForDecoding != codecForDecoding())
121     setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
122   if(info.serverList.count()) setServerList(info.serverList); // FIXME compare components
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::prefixToMode(const QCharRef &prefix) {
133   return prefixToMode(QString(prefix));
134 }
135
136 QString Network::modeToPrefix(const QString &mode) {
137   if(prefixModes().contains(mode))
138     return QString(prefixes()[prefixModes().indexOf(mode)]);
139   else
140     return QString();
141 }
142
143 QString Network::modeToPrefix(const QCharRef &mode) {
144   return modeToPrefix(QString(mode));
145 }
146   
147 QString Network::networkName() const {
148   return _networkName;
149 }
150
151 QString Network::currentServer() const {
152   return _currentServer;
153 }
154
155 QString Network::myNick() const {
156   return _myNick;
157 }
158
159 IdentityId Network::identity() const {
160   return _identity;
161 }
162
163 QStringList Network::nicks() const {
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 QStringList Network::channels() const {
174   return _ircChannels.keys();
175 }
176
177 QVariantList Network::serverList() const {
178   return _serverList;
179 }
180
181 QString Network::prefixes() {
182   if(_prefixes.isNull())
183     determinePrefixes();
184   
185   return _prefixes;
186 }
187
188 QString Network::prefixModes() {
189   if(_prefixModes.isNull())
190     determinePrefixes();
191
192   return _prefixModes;
193 }
194
195 bool Network::supports(const QString &param) const {
196   return _supports.contains(param);
197 }
198
199 QString Network::support(const QString &param) const {
200   QString support_ = param.toUpper();
201   if(_supports.contains(support_))
202     return _supports[support_];
203   else
204     return QString();
205 }
206
207 IrcUser *Network::newIrcUser(const QString &hostmask) {
208   QString nick(nickFromMask(hostmask).toLower());
209   if(!_ircUsers.contains(nick)) {
210     IrcUser *ircuser = new IrcUser(hostmask, this);
211     // mark IrcUser as already initialized to keep the SignalProxy from requesting initData
212     //if(isInitialized())
213     //  ircuser->setInitialized();
214     if(proxy())
215       proxy()->synchronize(ircuser);
216     else
217       qWarning() << "unable to synchronize new IrcUser" << hostmask << "forgot to call Network::setProxy(SignalProxy *)?";
218     
219     connect(ircuser, SIGNAL(nickSet(QString)), this, SLOT(ircUserNickChanged(QString)));
220     connect(ircuser, SIGNAL(initDone()), this, SLOT(ircUserInitDone()));
221     _ircUsers[nick] = ircuser;
222     emit ircUserAdded(hostmask);
223     emit ircUserAdded(ircuser);
224   }
225   return _ircUsers[nick];
226 }
227
228 IrcUser *Network::newIrcUser(const QByteArray &hostmask) {
229   return newIrcUser(decodeString(hostmask));
230 }
231
232 void Network::removeIrcUser(IrcUser *ircuser) {
233   QString nick = _ircUsers.key(ircuser);
234   if(nick.isNull())
235     return;
236
237   _ircUsers.remove(nick);
238   disconnect(ircuser, 0, this, 0);
239   emit ircUserRemoved(nick);
240   emit ircUserRemoved(ircuser);
241   ircuser->deleteLater();
242 }
243
244 void Network::removeChansAndUsers() {
245   QList<IrcUser *> users = ircUsers();
246   foreach(IrcUser *user, users) {
247     removeIrcUser(user);
248   }
249   QList<IrcChannel *> channels = ircChannels();
250   foreach(IrcChannel *channel, channels) {
251     removeIrcChannel(channel);
252   }
253 }
254
255 void Network::removeIrcUser(const QString &nick) {
256   IrcUser *ircuser;
257   if((ircuser = ircUser(nick)) != 0)
258     removeIrcUser(ircuser);
259 }
260
261 IrcUser *Network::ircUser(QString nickname) const {
262   nickname = nickname.toLower();
263   if(_ircUsers.contains(nickname))
264     return _ircUsers[nickname];
265   else
266     return 0;
267 }
268
269 IrcUser *Network::ircUser(const QByteArray &nickname) const {
270   return ircUser(decodeString(nickname));
271 }
272
273 QList<IrcUser *> Network::ircUsers() const {
274   return _ircUsers.values();
275 }
276
277 quint32 Network::ircUserCount() const {
278   return _ircUsers.count();
279 }
280
281 IrcChannel *Network::newIrcChannel(const QString &channelname) {
282   if(!_ircChannels.contains(channelname.toLower())) {
283     IrcChannel *channel = new IrcChannel(channelname, this);
284     // mark IrcUser as already initialized to keep the SignalProxy from requesting initData
285     //if(isInitialized())
286     //  channel->setInitialized();
287
288     if(proxy())
289       proxy()->synchronize(channel);
290     else
291       qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
292
293     connect(channel, SIGNAL(initDone()), this, SLOT(ircChannelInitDone()));
294     connect(channel, SIGNAL(destroyed()), this, SLOT(channelDestroyed()));
295     _ircChannels[channelname.toLower()] = channel;
296     emit ircChannelAdded(channelname);
297     emit ircChannelAdded(channel);
298   }
299   return _ircChannels[channelname.toLower()];
300 }
301
302 IrcChannel *Network::newIrcChannel(const QByteArray &channelname) {
303   return newIrcChannel(decodeString(channelname));
304 }
305
306 IrcChannel *Network::ircChannel(QString channelname) const {
307   channelname = channelname.toLower();
308   if(_ircChannels.contains(channelname))
309     return _ircChannels[channelname];
310   else
311     return 0;
312 }
313
314 IrcChannel *Network::ircChannel(const QByteArray &channelname) const {
315   return ircChannel(decodeString(channelname));
316 }
317
318
319 QList<IrcChannel *> Network::ircChannels() const {
320   return _ircChannels.values();
321 }
322
323 quint32 Network::ircChannelCount() const {
324   return _ircChannels.count();
325 }
326
327 QByteArray Network::codecForEncoding() const {
328   if(_codecForEncoding) return _codecForEncoding->name();
329   return QByteArray();
330 }
331
332 void Network::setCodecForEncoding(const QByteArray &name) {
333   setCodecForEncoding(QTextCodec::codecForName(name));
334 }
335
336 void Network::setCodecForEncoding(QTextCodec *codec) {
337   _codecForEncoding = codec;
338   emit codecForEncodingSet(codecForEncoding());
339 }
340
341 QByteArray Network::codecForDecoding() const {
342   if(_codecForDecoding) return _codecForDecoding->name();
343   else return QByteArray();
344 }
345
346 void Network::setCodecForDecoding(const QByteArray &name) {
347   setCodecForDecoding(QTextCodec::codecForName(name));
348 }
349
350 void Network::setCodecForDecoding(QTextCodec *codec) {
351   _codecForDecoding = codec;
352   emit codecForDecodingSet(codecForDecoding());
353 }
354
355 QString Network::decodeString(const QByteArray &text) const {
356   return ::decodeString(text, _codecForDecoding);
357 }
358
359 QByteArray Network::encodeString(const QString string) const {
360   if(_codecForEncoding) {
361     return _codecForEncoding->fromUnicode(string);
362   }
363   return string.toAscii();
364 }
365
366 // ====================
367 //  Public Slots:
368 // ====================
369 void Network::setNetworkName(const QString &networkName) {
370   _networkName = networkName;
371   emit networkNameSet(networkName);
372 }
373
374 void Network::setCurrentServer(const QString &currentServer) {
375   _currentServer = currentServer;
376   emit currentServerSet(currentServer);
377 }
378
379 void Network::setConnected(bool connected) {
380   _connected = connected;
381   if(!connected)
382     removeChansAndUsers();
383   emit connectedSet(connected);
384 }
385
386 //void Network::setConnectionState(ConnectionState state) {
387 void Network::setConnectionState(int state) {
388   _connectionState = (ConnectionState)state;
389   //qDebug() << "netstate" << networkId() << networkName() << state;
390   emit connectionStateSet(state);
391   emit connectionStateSet(_connectionState);
392 }
393
394 void Network::setMyNick(const QString &nickname) {
395   _myNick = nickname;
396   emit myNickSet(nickname);
397 }
398
399 void Network::setIdentity(IdentityId id) {
400   _identity = id;
401   emit identitySet(id);
402 }
403
404 void Network::setServerList(const QVariantList &serverList) {
405   _serverList = serverList;
406   emit serverListSet(serverList);
407 }
408
409 void Network::addSupport(const QString &param, const QString &value) {
410   if(!_supports.contains(param)) {
411     _supports[param] = value;
412     emit supportAdded(param, value);
413   }
414 }
415
416 void Network::removeSupport(const QString &param) {
417   if(_supports.contains(param)) {
418     _supports.remove(param);
419     emit supportRemoved(param);
420   }
421 }
422
423 QVariantMap Network::initSupports() const {
424   QVariantMap supports;
425   QHashIterator<QString, QString> iter(_supports);
426   while(iter.hasNext()) {
427     iter.next();
428     supports[iter.key()] = iter.value();
429   }
430   return supports;
431 }
432
433 QVariantList Network::initServerList() const {
434   return serverList();
435 }
436
437 QStringList Network::initIrcUsers() const {
438   QStringList hostmasks;
439   foreach(IrcUser *ircuser, ircUsers()) {
440     hostmasks << ircuser->hostmask();
441   }
442   return hostmasks;
443 }
444
445 QStringList Network::initIrcChannels() const {
446   return _ircChannels.keys();
447 }
448
449 void Network::initSetSupports(const QVariantMap &supports) {
450   QMapIterator<QString, QVariant> iter(supports);
451   while(iter.hasNext()) {
452     iter.next();
453     addSupport(iter.key(), iter.value().toString());
454   }
455 }
456
457 void Network::initSetServerList(const QVariantList & serverList) {
458   setServerList(serverList);
459 }
460
461 void Network::initSetIrcUsers(const QStringList &hostmasks) {
462   if(!_ircUsers.empty())
463     return;
464   foreach(QString hostmask, hostmasks) {
465     newIrcUser(hostmask);
466   }
467 }
468
469 void Network::initSetChannels(const QStringList &channels) {
470   if(!_ircChannels.empty())
471     return;
472   foreach(QString channel, channels)
473     newIrcChannel(channel);
474 }
475
476 IrcUser *Network::updateNickFromMask(const QString &mask) {
477   QString nick(nickFromMask(mask).toLower());
478   IrcUser *ircuser;
479   
480   if(_ircUsers.contains(nick)) {
481     ircuser = _ircUsers[nick];
482     ircuser->updateHostmask(mask);
483   } else {
484     ircuser = newIrcUser(mask);
485   }
486   return ircuser;
487 }
488
489 void Network::ircUserNickChanged(QString newnick) {
490   QString oldnick = _ircUsers.key(qobject_cast<IrcUser*>(sender()));
491
492   if(oldnick.isNull())
493     return;
494
495   if(newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
496
497   if(myNick().toLower() == oldnick)
498     setMyNick(newnick);
499 }
500
501 void Network::ircUserInitDone() {
502   IrcUser *ircuser = static_cast<IrcUser *>(sender());
503   Q_ASSERT(ircuser);
504   emit ircUserInitDone(ircuser);
505 }
506
507 void Network::ircChannelInitDone() {
508   IrcChannel *ircchannel = static_cast<IrcChannel *>(sender());
509   Q_ASSERT(ircchannel);
510   emit ircChannelInitDone(ircchannel);
511 }
512
513 void Network::removeIrcChannel(IrcChannel *channel) {
514   QString chanName = _ircChannels.key(channel);
515   if(chanName.isNull())
516     return;
517   
518   _ircChannels.remove(chanName);
519   disconnect(channel, 0, this, 0);
520   emit ircChannelRemoved(chanName);
521   emit ircChannelRemoved(channel);
522   channel->deleteLater();
523 }
524
525 void Network::removeIrcChannel(const QString &channel) {
526   IrcChannel *chan;
527   if((chan = ircChannel(channel)) != 0)
528     removeIrcChannel(chan);
529 }
530
531 void Network::channelDestroyed() {
532   IrcChannel *channel = static_cast<IrcChannel *>(sender());
533   Q_ASSERT(channel);
534   _ircChannels.remove(_ircChannels.key(channel));
535   emit ircChannelRemoved(channel);
536 }
537
538 void Network::requestConnect() const {
539   if(!proxy()) return;
540   if(proxy()->proxyMode() == SignalProxy::Client) emit connectRequested(); // on the client this triggers calling this slot on the core
541   else {
542     if(connectionState() != Disconnected) {
543       qWarning() << "Requesting connect while not being disconnected!";
544       return;
545     }
546     emit connectRequested(networkId());  // and this is for CoreSession :)
547   }
548 }
549
550 void Network::requestDisconnect() const {
551   if(!proxy()) return;
552   if(proxy()->proxyMode() == SignalProxy::Client) emit disconnectRequested(); // on the client this triggers calling this slot on the core
553   else {
554     if(connectionState() == Disconnected) {
555       qWarning() << "Requesting disconnect while not being connected!";
556       return;
557     }
558     emit disconnectRequested(networkId());  // and this is for CoreSession :)
559   }
560 }
561
562 void Network::emitConnectionError(const QString &errorMsg) {
563   emit connectionError(errorMsg);
564 }
565
566 // ====================
567 //  Private:
568 // ====================
569 void Network::determinePrefixes() {
570   // seems like we have to construct them first
571   QString PREFIX = support("PREFIX");
572   
573   if(PREFIX.startsWith("(") && PREFIX.contains(")")) {
574     _prefixes = PREFIX.section(")", 1);
575     _prefixModes = PREFIX.mid(1).section(")", 0, 0);
576   } else {
577     QString defaultPrefixes("~&@%+");
578     QString defaultPrefixModes("qaohv");
579
580     // we just assume that in PREFIX are only prefix chars stored
581     for(int i = 0; i < defaultPrefixes.size(); i++) {
582       if(PREFIX.contains(defaultPrefixes[i])) {
583         _prefixes += defaultPrefixes[i];
584         _prefixModes += defaultPrefixModes[i];
585       }
586     }
587     // check for success
588     if(!_prefixes.isNull())
589       return;
590     
591     // well... our assumption was obviously wrong...
592     // check if it's only prefix modes
593     for(int i = 0; i < defaultPrefixes.size(); i++) {
594       if(PREFIX.contains(defaultPrefixModes[i])) {
595         _prefixes += defaultPrefixes[i];
596         _prefixModes += defaultPrefixModes[i];
597       }
598     }
599     // now we've done all we've could...
600   }
601 }
602
603 /************************************************************************
604  * NetworkInfo
605  ************************************************************************/
606
607 bool NetworkInfo::operator==(const NetworkInfo &other) const {
608   if(networkId != other.networkId) return false;
609   if(networkName != other.networkName) return false;
610   if(identity != other.identity) return false;
611   if(codecForEncoding != other.codecForEncoding) return false;
612   if(codecForDecoding != other.codecForDecoding) return false;
613   if(serverList != other.serverList) return false;
614   return true;
615 }
616
617 bool NetworkInfo::operator!=(const NetworkInfo &other) const {
618   return !(*this == other);
619 }
620
621 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info) {
622   QVariantMap i;
623   i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
624   i["NetworkName"] = info.networkName;
625   i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
626   i["CodecForEncoding"] = info.codecForEncoding;
627   i["CodecForDecoding"] = info.codecForDecoding;
628   i["ServerList"] = info.serverList;
629   out << i;
630   return out;
631 }
632
633 QDataStream &operator>>(QDataStream &in, NetworkInfo &info) {
634   QVariantMap i;
635   in >> i;
636   info.networkId = i["NetworkId"].value<NetworkId>();
637   info.networkName = i["NetworkName"].toString();
638   info.identity = i["Identity"].value<IdentityId>();
639   info.codecForEncoding = i["CodecForEncoding"].toByteArray();
640   info.codecForDecoding = i["CodecForDecoding"].toByteArray();
641   info.serverList = i["ServerList"].toList();
642   return in;
643 }