1 /***************************************************************************
2 * Copyright (C) 2005-09 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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"
24 #include "ctcphandler.h"
25 #include "coreidentity.h"
31 UserInputHandler::UserInputHandler(CoreNetwork *parent)
32 : BasicHandler(parent)
36 void UserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &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
49 cmd = msg.section(' ', 0, 0).remove(0, 1).toUpper();
50 msg = msg.section(' ', 1);
52 handle(cmd, Q_ARG(BufferInfo, bufferInfo), Q_ARG(QString, msg));
55 // ====================
57 // ====================
58 void UserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) {
61 QString awayMsg = msg;
62 IrcUser *me = network()->me();
64 // if there is no message supplied we have to check if we are already away or not
66 if(me && !me->isAway()) {
67 awayMsg = network()->identityPtr()->awayReason();
68 if(awayMsg.isEmpty()) {
74 me->setAwayMessage(awayMsg);
76 putCmd("AWAY", serverEncode(awayMsg));
79 void UserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
80 banOrUnban(bufferInfo, msg, true);
83 void UserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
84 banOrUnban(bufferInfo, msg, false);
87 void UserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
91 QStringList params = msg.split(" ");
93 if(!params.isEmpty() && isChannelName(params[0])) {
94 banChannel = params.takeFirst();
95 } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
96 banChannel = bufferInfo.bufferName();
98 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
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));
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, "*");
119 banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
121 banUser = params.join(" ");
124 QString banMode = ban ? "+b" : "-b";
125 QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
126 emit putRawLine(serverEncode(banMsg));
129 void UserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
132 QString nick = msg.section(' ', 0, 0);
133 QString ctcpTag = msg.section(' ', 1, 1).toUpper();
134 if(ctcpTag.isEmpty())
137 QString message = "";
138 QString verboseMessage = tr("sending CTCP-%1 request").arg(ctcpTag);
140 if(ctcpTag == "PING") {
141 uint now = QDateTime::currentDateTime().toTime_t();
142 message = QString::number(now);
145 network()->ctcpHandler()->query(nick, ctcpTag, message);
146 emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
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';
153 params << bufferInfo.bufferName() << m << nicks;
154 emit putCmd("MODE", serverEncode(params));
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';
161 params << bufferInfo.bufferName() << m << nicks;
162 emit putCmd("MODE", serverEncode(params));
165 void UserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
167 params << msg << bufferInfo.bufferName();
168 emit putCmd("INVITE", serverEncode(params));
171 void UserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
172 Q_UNUSED(bufferInfo);
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(",");
181 for(i = 0; i < chans.count(); i++) {
182 if(!network()->isChannelName(chans[i]))
183 chans[i].prepend('#');
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!
189 for(; i < keys.count(); i++) {
190 if(i >= chans.count()) break;
191 network()->addChannelKey(chans[i], keys[i]);
193 for(; i < chans.count(); i++) {
194 network()->removeChannelKey(chans[i]);
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();
202 reason = network()->identityPtr()->kickReason();
204 QList<QByteArray> params;
205 params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
206 emit putCmd("KICK", params);
209 void UserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
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);
219 void UserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
221 emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
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);
230 void UserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
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());
238 // TODO handle correct encoding for buffer modes (channelEncode())
239 emit putCmd("MODE", serverEncode(params));
242 // TODO: show privmsgs
243 void UserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
244 Q_UNUSED(bufferInfo);
245 if(!msg.contains(' '))
248 QByteArray target = serverEncode(msg.section(' ', 0, 0));
249 putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
252 void UserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
254 QString nick = msg.section(' ', 0, 0);
255 emit putCmd("NICK", serverEncode(nick));
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);
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';
271 params << bufferInfo.bufferName() << m << nicks;
272 emit putCmd("MODE", serverEncode(params));
275 void UserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
277 emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
280 void UserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
281 QList<QByteArray> params;
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();
290 partReason = msg.mid(channelName.length() + 1);
293 if(partReason.isEmpty())
294 partReason = network()->identityPtr()->partReason();
296 params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
297 emit putCmd("PART", params);
300 void UserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
305 param = QTime::currentTime().toString("hh:mm:ss.zzz");
307 putCmd("PING", serverEncode(param));
310 // TODO: implement queries
311 void UserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
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);
318 emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
319 handleMsg(bufferInfo, msg);
322 void UserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
324 network()->disconnectFromIrc(true, msg);
327 void UserInputHandler::issueQuit(const QString &reason) {
328 emit putCmd("QUIT", serverEncode(reason));
331 void UserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
333 emit putRawLine(serverEncode(msg));
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);
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());
348 params << channelEncode(bufferInfo.bufferName(), msg);
349 emit putCmd("TOPIC", params);
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';
356 params << bufferInfo.bufferName() << m << nicks;
357 emit putCmd("MODE", serverEncode(params));
360 void UserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
361 int splitPos = msg.indexOf(';');
366 int delay = msg.left(splitPos).trimmed().toInt(&ok);
372 QString command = msg.mid(splitPos + 1).trimmed();
373 if(command.isEmpty())
376 _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
379 void UserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
381 emit putCmd("WHO", serverEncode(msg.split(' ')));
384 void UserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
386 emit putCmd("WHOIS", serverEncode(msg.split(' ')));
389 void UserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
391 emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
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);
401 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: %1 %2").arg(cmd, msg));
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];
412 // replace ranges like $1..3
413 if(!params.isEmpty()) {
415 while((pos = paramRangeR.indexIn(command)) != -1) {
416 int start = paramRangeR.cap(1).toInt();
418 int end = paramRangeR.cap(2).toInt(&ok);
420 end = params.count();
423 command = command.replace(pos, paramRangeR.matchedLength(), QString());
425 command = command.replace(pos, paramRangeR.matchedLength(), QStringList(params.mid(start - 1, end - start + 1)).join(" "));
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]);
435 command = command.replace("$0", msg);
436 command = command.replace("$channelname", bufferInfo.bufferName());
437 command = command.replace("$currentnick", network()->myNick());
438 expandedCommands << command;
441 while(!expandedCommands.isEmpty()) {
443 if(expandedCommands[0].trimmed().toLower().startsWith("/wait")) {
444 command = expandedCommands.join("; ");
445 expandedCommands.clear();
447 command = expandedCommands.takeFirst();
449 handleUserInput(bufferInfo, command);
454 void UserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
455 static const char *cmd = "PRIVMSG";
456 int overrun = lastParamOverrun(cmd, QList<QByteArray>() << message);
458 static const char *splitter = " .,-";
459 int maxSplitPos = message.count() - overrun;
461 for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
462 splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
465 splitPos = maxSplitPos;
467 putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
468 putPrivmsg(target, message.mid(splitPos));
471 putCmd(cmd, QList<QByteArray>() << target << message);
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> ¶ms) {
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?)
486 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
488 if(!params.isEmpty()) {
489 for(int i = 0; i < params.count() - 1; i++) {
490 maxLen -= (params[i].count() + 1);
492 maxLen -= 2; // " :" last param separator;
494 if(params.last().count() > maxLen) {
495 return params.last().count() - maxLen;
505 void UserInputHandler::timerEvent(QTimerEvent *event) {
506 if(!_delayedCommands.contains(event->timerId())) {
507 QObject::timerEvent(event);
510 BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
511 QString rawCommand = _delayedCommands[event->timerId()].command;
512 _delayedCommands.remove(event->timerId());
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);