Fixes #746 - Quassel unsets default modes set by server upon first connect
[quassel.git] / src / core / coreuserinputhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-10 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 "coreuserinputhandler.h"
21
22 #include "util.h"
23
24 #include "ctcphandler.h"
25 #include "coreidentity.h"
26 #include "ircuser.h"
27
28 #include <QDebug>
29 #include <QRegExp>
30
31 CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent)
32   : CoreBasicHandler(parent)
33 {
34 }
35
36 void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg) {
37   if(msg.isEmpty())
38     return;
39
40   AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
41
42   for(int i = 0; i < list.count(); i++) {
43     QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper();
44     QString payload = list.at(i).second.section(' ', 1);
45     handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload));
46   }
47 }
48
49 // ====================
50 //  Public Slots
51 // ====================
52 void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) {
53   Q_UNUSED(bufferInfo)
54   if(msg.startsWith("-all")) {
55     if(msg.length() == 4) {
56       coreSession()->globalAway();
57       return;
58     }
59     Q_ASSERT(msg.length() > 4);
60     if(msg[4] == ' ') {
61       coreSession()->globalAway(msg.mid(5));
62       return;
63     }
64   }
65   issueAway(msg);
66 }
67
68 void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck) {
69   QString awayMsg = msg;
70   IrcUser *me = network()->me();
71
72   // if there is no message supplied we have to check if we are already away or not
73   if(autoCheck && msg.isEmpty()) {
74     if(me && !me->isAway()) {
75       Identity *identity = network()->identityPtr();
76       if(identity) {
77         awayMsg = identity->awayReason();
78       }
79       if(awayMsg.isEmpty()) {
80         awayMsg = tr("away");
81       }
82     }
83   }
84   if(me)
85     me->setAwayMessage(awayMsg);
86
87   putCmd("AWAY", serverEncode(awayMsg));
88 }
89
90 void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
91   banOrUnban(bufferInfo, msg, true);
92 }
93
94 void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
95   banOrUnban(bufferInfo, msg, false);
96 }
97
98 void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
99   QString banChannel;
100   QString banUser;
101
102   QStringList params = msg.split(" ");
103
104   if(!params.isEmpty() && isChannelName(params[0])) {
105     banChannel = params.takeFirst();
106   } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
107     banChannel = bufferInfo.bufferName();
108   } else {
109     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
110     return;
111   }
112
113   if(!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
114     IrcUser *ircuser = network()->ircUser(params[0]);
115     // generalizedHost changes <nick> to  *!ident@*.sld.tld.
116     QString generalizedHost = ircuser->host();
117     if(generalizedHost.isEmpty()) {
118       emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
119       return;
120     }
121
122     static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
123     if(ipAddress.exactMatch(generalizedHost))    {
124         int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
125         generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
126     } else if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
127       int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
128       generalizedHost.replace(0, secondLastPeriodPosition, "*");
129     }
130     banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
131   } else {
132     banUser = params.join(" ");
133   }
134
135   QString banMode = ban ? "+b" : "-b";
136   QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
137   emit putRawLine(serverEncode(banMsg));
138 }
139
140 void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
141   Q_UNUSED(bufferInfo)
142
143   QString nick = msg.section(' ', 0, 0);
144   QString ctcpTag = msg.section(' ', 1, 1).toUpper();
145   if(ctcpTag.isEmpty())
146     return;
147
148   QString message = msg.section(' ', 2);
149   QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
150
151   if(ctcpTag == "PING") {
152     uint now = QDateTime::currentDateTime().toTime_t();
153     message = QString::number(now);
154   }
155
156   network()->ctcpHandler()->query(nick, ctcpTag, message);
157   emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
158 }
159
160 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg) {
161   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
162   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
163   QStringList params;
164   params << bufferInfo.bufferName() << m << nicks;
165   emit putCmd("MODE", serverEncode(params));
166 }
167
168 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg) {
169   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
170   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
171   QStringList params;
172   params << bufferInfo.bufferName() << m << nicks;
173   emit putCmd("MODE", serverEncode(params));
174 }
175
176 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
177   QStringList params;
178   params << msg << bufferInfo.bufferName();
179   emit putCmd("INVITE", serverEncode(params));
180 }
181
182 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
183   Q_UNUSED(bufferInfo);
184
185   // trim spaces before chans or keys
186   QString sane_msg = msg;
187   sane_msg.replace(QRegExp(", +"), ",");
188   QStringList params = sane_msg.trimmed().split(" ");
189
190   QStringList chans = params[0].split(",", QString::SkipEmptyParts);
191   QStringList keys;
192   if(params.count() > 1)
193     keys = params[1].split(",");
194
195   int i;
196   for(i = 0; i < chans.count(); i++) {
197     if(!network()->isChannelName(chans[i]))
198       chans[i].prepend('#');
199
200     if(i < keys.count()) {
201       network()->addChannelKey(chans[i], keys[i]);
202     } else {
203       network()->removeChannelKey(chans[i]);
204     }
205   }
206
207   static const char *cmd = "JOIN";
208   i = 0;
209   QStringList joinChans, joinKeys;
210   int slicesize = chans.count();
211   QList<QByteArray> encodedParams;
212
213   // go through all to-be-joined channels and (re)build the join list
214   while(i < chans.count()) {
215     joinChans.append(chans.at(i));
216     if(i < keys.count())
217       joinKeys.append(keys.at(i));
218
219     // if the channel list we built so far either contains all requested channels or exceeds
220     // the desired amount of channels in this slice, try to send what we have so far
221     if(++i == chans.count() || joinChans.count() >= slicesize) {
222       params.clear();
223       params.append(joinChans.join(","));
224       params.append(joinKeys.join(","));
225       encodedParams = serverEncode(params);
226       // check if it fits in one command
227       if(lastParamOverrun(cmd, encodedParams) == 0) {
228         emit putCmd(cmd, encodedParams);
229       } else if(slicesize > 1) {
230         // back to start of slice, try again with half the amount of channels
231         i -= slicesize;
232         slicesize /= 2;
233       }
234       joinChans.clear();
235       joinKeys.clear();
236     }
237   }
238 }
239
240 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
241   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
242   QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
243   if(reason.isEmpty())
244     reason = network()->identityPtr()->kickReason();
245
246   QList<QByteArray> params;
247   params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
248   emit putCmd("KICK", params);
249 }
250
251 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
252   Q_UNUSED(bufferInfo)
253   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
254   QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
255   QList<QByteArray> params;
256   params << serverEncode(nick) << serverEncode(pass);
257   emit putCmd("KILL", params);
258 }
259
260
261 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
262   Q_UNUSED(bufferInfo)
263   emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
264 }
265
266 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
267   if(bufferInfo.bufferName().isEmpty()) return; // server buffer
268   network()->ctcpHandler()->query(bufferInfo.bufferName(), "ACTION", msg);
269   emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
270 }
271
272 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
273   Q_UNUSED(bufferInfo)
274
275   QStringList params = msg.split(' ', QString::SkipEmptyParts);
276   // if the first argument is neither a channel nor us (user modes are only to oneself) the current buffer is assumed to be the target
277   if(!params.isEmpty()) {
278     if(!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
279       params.prepend(bufferInfo.bufferName());
280     if(network()->isMyNick(params[0]) && params.count() == 2)
281       network()->updateIssuedModes(params[1]);
282     if(params[0] == "-reset" && params.count() == 1) {
283       // FIXME: give feedback to the user (I don't want to add new strings right now)
284       network()->resetPersistentModes();
285       return;
286     }
287   }
288
289   // TODO handle correct encoding for buffer modes (channelEncode())
290   emit putCmd("MODE", serverEncode(params));
291 }
292
293 // TODO: show privmsgs
294 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
295   Q_UNUSED(bufferInfo);
296   if(!msg.contains(' '))
297     return;
298
299   QByteArray target = serverEncode(msg.section(' ', 0, 0));
300   putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
301 }
302
303 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
304   Q_UNUSED(bufferInfo)
305   QString nick = msg.section(' ', 0, 0);
306   emit putCmd("NICK", serverEncode(nick));
307 }
308
309 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
310   QString bufferName = msg.section(' ', 0, 0);
311   QString payload = msg.section(' ', 1);
312   QList<QByteArray> params;
313   params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
314   emit putCmd("NOTICE", params);
315   emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
316 }
317
318 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
319   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
320   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
321   QStringList params;
322   params << bufferInfo.bufferName() << m << nicks;
323   emit putCmd("MODE", serverEncode(params));
324 }
325
326 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
327   Q_UNUSED(bufferInfo)
328   emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
329 }
330
331 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
332   QList<QByteArray> params;
333   QString partReason;
334
335   // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
336   QString channelName = msg.section(' ', 0, 0);
337   if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
338     channelName = bufferInfo.bufferName();
339     partReason = msg;
340   } else {
341     partReason = msg.mid(channelName.length() + 1);
342   }
343
344   if(partReason.isEmpty())
345     partReason = network()->identityPtr()->partReason();
346
347   params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
348   emit putCmd("PART", params);
349 }
350
351 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
352   Q_UNUSED(bufferInfo)
353
354   QString param = msg;
355   if(param.isEmpty())
356     param = QTime::currentTime().toString("hh:mm:ss.zzz");
357
358   putCmd("PING", serverEncode(param));
359 }
360
361 // TODO: implement queries
362 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
363   Q_UNUSED(bufferInfo)
364   QString target = msg.section(' ', 0, 0);
365   QString message = msg.section(' ', 1);
366   if(message.isEmpty())
367     emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, "Starting query with " + target, network()->myNick(), Message::Self);
368   else
369     emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
370   handleMsg(bufferInfo, msg);
371 }
372
373 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
374   Q_UNUSED(bufferInfo)
375   network()->disconnectFromIrc(true, msg);
376 }
377
378 void CoreUserInputHandler::issueQuit(const QString &reason) {
379   emit putCmd("QUIT", serverEncode(reason));
380 }
381
382 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
383   Q_UNUSED(bufferInfo)
384   emit putRawLine(serverEncode(msg));
385 }
386
387 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
388   if(bufferInfo.bufferName().isEmpty())
389     return;  // server buffer
390   putPrivmsg(serverEncode(bufferInfo.bufferName()), channelEncode(bufferInfo.bufferName(), msg));
391   emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
392 }
393
394 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
395   if(bufferInfo.bufferName().isEmpty()) return;
396   QList<QByteArray> params;
397   params << serverEncode(bufferInfo.bufferName());
398   if(!msg.isEmpty())
399     params << channelEncode(bufferInfo.bufferName(), msg);
400   emit putCmd("TOPIC", params);
401 }
402
403 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
404   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
405   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
406   QStringList params;
407   params << bufferInfo.bufferName() << m << nicks;
408   emit putCmd("MODE", serverEncode(params));
409 }
410
411 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
412   int splitPos = msg.indexOf(';');
413   if(splitPos <= 0)
414     return;
415
416   bool ok;
417   int delay = msg.left(splitPos).trimmed().toInt(&ok);
418   if(!ok)
419     return;
420
421   delay *= 1000;
422
423   QString command = msg.mid(splitPos + 1).trimmed();
424   if(command.isEmpty())
425     return;
426
427   _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
428 }
429
430 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
431   Q_UNUSED(bufferInfo)
432   emit putCmd("WHO", serverEncode(msg.split(' ')));
433 }
434
435 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
436   Q_UNUSED(bufferInfo)
437   emit putCmd("WHOIS", serverEncode(msg.split(' ')));
438 }
439
440 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
441   Q_UNUSED(bufferInfo)
442   emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
443 }
444
445 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
446   Q_UNUSED(bufferInfo);
447   emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
448 }
449
450 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
451   static const char *cmd = "PRIVMSG";
452   int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << message);
453   if(overrun) {
454     static const char *splitter = " .,-";
455     int maxSplitPos = message.count() - overrun;
456     int splitPos = -1;
457     for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
458       splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
459     }
460     if(splitPos <= 0) {
461       splitPos = maxSplitPos;
462     }
463     putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
464     putPrivmsg(target, message.mid(splitPos));
465     return;
466   } else {
467     putCmd(cmd, QList<QByteArray>() << target << message);
468   }
469 }
470
471 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
472 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params) {
473   // the server will pass our message truncated to 512 bytes including CRLF with the following format:
474   // ":prefix COMMAND param0 param1 :lastparam"
475   // where prefix = "nickname!user@host"
476   // that means that the last message can be as long as:
477   // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
478   IrcUser *me = network()->me();
479   int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
480
481   if(me)
482     maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
483
484   if(!params.isEmpty()) {
485     for(int i = 0; i < params.count() - 1; i++) {
486       maxLen -= (params[i].count() + 1);
487     }
488     maxLen -= 2; // " :" last param separator;
489
490     if(params.last().count() > maxLen) {
491       return params.last().count() - maxLen;
492     } else {
493       return 0;
494     }
495   } else {
496     return 0;
497   }
498 }
499
500 void CoreUserInputHandler::timerEvent(QTimerEvent *event) {
501   if(!_delayedCommands.contains(event->timerId())) {
502     QObject::timerEvent(event);
503     return;
504   }
505   BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
506   QString rawCommand = _delayedCommands[event->timerId()].command;
507   _delayedCommands.remove(event->timerId());
508   event->accept();
509
510   // the stored command might be the result of an alias expansion, so we need to split it up again
511   QStringList commands = rawCommand.split(QRegExp("; ?"));
512   foreach(QString command, commands) {
513     handleUserInput(bufferInfo, command);
514   }
515 }