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