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