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