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