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