d3ecab560f61f354681e67f7ff3d6d523b7da1f4
[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     connect(ircuser, SIGNAL(destroyed()), this, SLOT(ircUserDestroyed()));
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   emit ircUserRemoved(nick);
240   emit ircUserRemoved(ircuser);
241   ircuser->deleteLater();
242 }
243
244 void Network::removeIrcUser(QString nick) {
245   IrcUser *ircuser;
246   if((ircuser = ircUser(nick)) != 0)
247     removeIrcUser(ircuser);
248 }
249
250 IrcUser *Network::ircUser(QString nickname) const {
251   nickname = nickname.toLower();
252   if(_ircUsers.contains(nickname))
253     return _ircUsers[nickname];
254   else
255     return 0;
256 }
257
258 IrcUser *Network::ircUser(const QByteArray &nickname) const {
259   return ircUser(decodeString(nickname));
260 }
261
262 QList<IrcUser *> Network::ircUsers() const {
263   return _ircUsers.values();
264 }
265
266 quint32 Network::ircUserCount() const {
267   return _ircUsers.count();
268 }
269
270 IrcChannel *Network::newIrcChannel(const QString &channelname) {
271   if(!_ircChannels.contains(channelname.toLower())) {
272     IrcChannel *channel = new IrcChannel(channelname, this);
273     // mark IrcUser as already initialized to keep the SignalProxy from requesting initData
274     //if(isInitialized())
275     //  channel->setInitialized();
276
277     if(proxy())
278       proxy()->synchronize(channel);
279     else
280       qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
281
282     connect(channel, SIGNAL(initDone()), this, SLOT(ircChannelInitDone()));
283     connect(channel, SIGNAL(destroyed()), this, SLOT(channelDestroyed()));
284     _ircChannels[channelname.toLower()] = channel;
285     emit ircChannelAdded(channelname);
286     emit ircChannelAdded(channel);
287   }
288   return _ircChannels[channelname.toLower()];
289 }
290
291 IrcChannel *Network::newIrcChannel(const QByteArray &channelname) {
292   return newIrcChannel(decodeString(channelname));
293 }
294
295 IrcChannel *Network::ircChannel(QString channelname) const {
296   channelname = channelname.toLower();
297   if(_ircChannels.contains(channelname))
298     return _ircChannels[channelname];
299   else
300     return 0;
301 }
302
303 IrcChannel *Network::ircChannel(const QByteArray &channelname) const {
304   return ircChannel(decodeString(channelname));
305 }
306
307
308 QList<IrcChannel *> Network::ircChannels() const {
309   return _ircChannels.values();
310 }
311
312 quint32 Network::ircChannelCount() const {
313   return _ircChannels.count();
314 }
315
316 QByteArray Network::codecForEncoding() const {
317   if(_codecForEncoding) return _codecForEncoding->name();
318   return QByteArray();
319 }
320
321 void Network::setCodecForEncoding(const QByteArray &name) {
322   setCodecForEncoding(QTextCodec::codecForName(name));
323 }
324
325 void Network::setCodecForEncoding(QTextCodec *codec) {
326   _codecForEncoding = codec;
327   emit codecForEncodingSet(codecForEncoding());
328 }
329
330 QByteArray Network::codecForDecoding() const {
331   if(_codecForDecoding) return _codecForDecoding->name();
332   else return QByteArray();
333 }
334
335 void Network::setCodecForDecoding(const QByteArray &name) {
336   setCodecForDecoding(QTextCodec::codecForName(name));
337 }
338
339 void Network::setCodecForDecoding(QTextCodec *codec) {
340   _codecForDecoding = codec;
341   emit codecForDecodingSet(codecForDecoding());
342 }
343
344 QString Network::decodeString(const QByteArray &text) const {
345   return ::decodeString(text, _codecForDecoding);
346 }
347
348 QByteArray Network::encodeString(const QString string) const {
349   if(_codecForEncoding) {
350     return _codecForEncoding->fromUnicode(string);
351   }
352   return string.toAscii();
353 }
354
355 // ====================
356 //  Public Slots:
357 // ====================
358 void Network::setNetworkName(const QString &networkName) {
359   _networkName = networkName;
360   emit networkNameSet(networkName);
361 }
362
363 void Network::setCurrentServer(const QString &currentServer) {
364   _currentServer = currentServer;
365   emit currentServerSet(currentServer);
366 }
367
368 void Network::setConnected(bool connected) {
369   _connected = connected;
370   emit connectedSet(connected);
371 }
372
373 //void Network::setConnectionState(ConnectionState state) {
374 void Network::setConnectionState(int state) {
375   _connectionState = (ConnectionState)state;
376   //qDebug() << "netstate" << networkId() << networkName() << state;
377   emit connectionStateSet(state);
378   emit connectionStateSet(_connectionState);
379 }
380
381 void Network::setMyNick(const QString &nickname) {
382   _myNick = nickname;
383   emit myNickSet(nickname);
384 }
385
386 void Network::setIdentity(IdentityId id) {
387   _identity = id;
388   emit identitySet(id);
389 }
390
391 void Network::setServerList(const QVariantList &serverList) {
392   _serverList = serverList;
393   emit serverListSet(serverList);
394 }
395
396 void Network::addSupport(const QString &param, const QString &value) {
397   if(!_supports.contains(param)) {
398     _supports[param] = value;
399     emit supportAdded(param, value);
400   }
401 }
402
403 void Network::removeSupport(const QString &param) {
404   if(_supports.contains(param)) {
405     _supports.remove(param);
406     emit supportRemoved(param);
407   }
408 }
409
410 QVariantMap Network::initSupports() const {
411   QVariantMap supports;
412   QHashIterator<QString, QString> iter(_supports);
413   while(iter.hasNext()) {
414     iter.next();
415     supports[iter.key()] = iter.value();
416   }
417   return supports;
418 }
419
420 QVariantList Network::initServerList() const {
421   return serverList();
422 }
423
424 QStringList Network::initIrcUsers() const {
425   QStringList hostmasks;
426   foreach(IrcUser *ircuser, ircUsers()) {
427     hostmasks << ircuser->hostmask();
428   }
429   return hostmasks;
430 }
431
432 QStringList Network::initIrcChannels() const {
433   return _ircChannels.keys();
434 }
435
436 void Network::initSetSupports(const QVariantMap &supports) {
437   QMapIterator<QString, QVariant> iter(supports);
438   while(iter.hasNext()) {
439     iter.next();
440     addSupport(iter.key(), iter.value().toString());
441   }
442 }
443
444 void Network::initSetServerList(const QVariantList & serverList) {
445   setServerList(serverList);
446 }
447
448 void Network::initSetIrcUsers(const QStringList &hostmasks) {
449   if(!_ircUsers.empty())
450     return;
451   foreach(QString hostmask, hostmasks) {
452     newIrcUser(hostmask);
453   }
454 }
455
456 void Network::initSetChannels(const QStringList &channels) {
457   if(!_ircChannels.empty())
458     return;
459   foreach(QString channel, channels)
460     newIrcChannel(channel);
461 }
462
463 IrcUser *Network::updateNickFromMask(const QString &mask) {
464   QString nick(nickFromMask(mask).toLower());
465   IrcUser *ircuser;
466   
467   if(_ircUsers.contains(nick)) {
468     ircuser = _ircUsers[nick];
469     ircuser->updateHostmask(mask);
470   } else {
471     ircuser = newIrcUser(mask);
472   }
473   return ircuser;
474 }
475
476 void Network::ircUserNickChanged(QString newnick) {
477   QString oldnick = _ircUsers.key(qobject_cast<IrcUser*>(sender()));
478
479   if(oldnick.isNull())
480     return;
481
482   if(newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
483
484   if(myNick().toLower() == oldnick)
485     setMyNick(newnick);
486 }
487
488 void Network::ircUserInitDone() {
489   IrcUser *ircuser = static_cast<IrcUser *>(sender());
490   Q_ASSERT(ircuser);
491   emit ircUserInitDone(ircuser);
492 }
493
494 void Network::ircChannelInitDone() {
495   IrcChannel *ircchannel = static_cast<IrcChannel *>(sender());
496   Q_ASSERT(ircchannel);
497   emit ircChannelInitDone(ircchannel);
498 }
499
500 void Network::ircUserDestroyed() {
501   IrcUser *ircuser = static_cast<IrcUser *>(sender());
502   Q_ASSERT(ircuser);
503   removeIrcUser(ircuser);
504 }
505
506 void Network::channelDestroyed() {
507   IrcChannel *channel = static_cast<IrcChannel *>(sender());
508   Q_ASSERT(channel);
509   emit ircChannelRemoved(sender());
510   _ircChannels.remove(_ircChannels.key(channel));
511 }
512
513 void Network::requestConnect() const {
514   if(!proxy()) return;
515   if(proxy()->proxyMode() == SignalProxy::Client) emit connectRequested(); // on the client this triggers calling this slot on the core
516   else {
517     if(connectionState() != Disconnected) {
518       qWarning() << "Requesting connect while not being disconnected!";
519       return;
520     }
521     emit connectRequested(networkId());  // and this is for CoreSession :)
522   }
523 }
524
525 void Network::requestDisconnect() const {
526   if(!proxy()) return;
527   if(proxy()->proxyMode() == SignalProxy::Client) emit disconnectRequested(); // on the client this triggers calling this slot on the core
528   else {
529     if(connectionState() == Disconnected) {
530       qWarning() << "Requesting disconnect while not being connected!";
531       return;
532     }
533     emit disconnectRequested(networkId());  // and this is for CoreSession :)
534   }
535 }
536
537 void Network::emitConnectionError(const QString &errorMsg) {
538   emit connectionError(errorMsg);
539 }
540
541 // ====================
542 //  Private:
543 // ====================
544 void Network::determinePrefixes() {
545   // seems like we have to construct them first
546   QString PREFIX = support("PREFIX");
547   
548   if(PREFIX.startsWith("(") && PREFIX.contains(")")) {
549     _prefixes = PREFIX.section(")", 1);
550     _prefixModes = PREFIX.mid(1).section(")", 0, 0);
551   } else {
552     QString defaultPrefixes("~&@%+");
553     QString defaultPrefixModes("qaohv");
554
555     // we just assume that in PREFIX are only prefix chars stored
556     for(int i = 0; i < defaultPrefixes.size(); i++) {
557       if(PREFIX.contains(defaultPrefixes[i])) {
558         _prefixes += defaultPrefixes[i];
559         _prefixModes += defaultPrefixModes[i];
560       }
561     }
562     // check for success
563     if(!_prefixes.isNull())
564       return;
565     
566     // well... our assumption was obviously wrong...
567     // check if it's only prefix modes
568     for(int i = 0; i < defaultPrefixes.size(); i++) {
569       if(PREFIX.contains(defaultPrefixModes[i])) {
570         _prefixes += defaultPrefixes[i];
571         _prefixModes += defaultPrefixModes[i];
572       }
573     }
574     // now we've done all we've could...
575   }
576 }
577
578 /************************************************************************
579  * NetworkInfo
580  ************************************************************************/
581
582 bool NetworkInfo::operator==(const NetworkInfo &other) const {
583   if(networkId != other.networkId) return false;
584   if(networkName != other.networkName) return false;
585   if(identity != other.identity) return false;
586   if(codecForEncoding != other.codecForEncoding) return false;
587   if(codecForDecoding != other.codecForDecoding) return false;
588   if(serverList != other.serverList) return false;
589   return true;
590 }
591
592 bool NetworkInfo::operator!=(const NetworkInfo &other) const {
593   return !(*this == other);
594 }
595
596 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info) {
597   QVariantMap i;
598   i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
599   i["NetworkName"] = info.networkName;
600   i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
601   i["CodecForEncoding"] = info.codecForEncoding;
602   i["CodecForDecoding"] = info.codecForDecoding;
603   i["ServerList"] = info.serverList;
604   out << i;
605   return out;
606 }
607
608 QDataStream &operator>>(QDataStream &in, NetworkInfo &info) {
609   QVariantMap i;
610   in >> i;
611   info.networkId = i["NetworkId"].value<NetworkId>();
612   info.networkName = i["NetworkName"].toString();
613   info.identity = i["Identity"].value<IdentityId>();
614   info.codecForEncoding = i["CodecForEncoding"].toByteArray();
615   info.codecForDecoding = i["CodecForDecoding"].toByteArray();
616   info.serverList = i["ServerList"].toList();
617   return in;
618 }