1 /***************************************************************************
2 * Copyright (C) 2005-08 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();
70 me->setAwayMessage(awayMsg);
72 putCmd("AWAY", serverEncode(awayMsg));
75 void UserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
76 banOrUnban(bufferInfo, msg, true);
79 void UserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
80 banOrUnban(bufferInfo, msg, false);
83 void UserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
87 QStringList params = msg.split(" ");
89 if(!params.isEmpty() && isChannelName(params[0])) {
90 banChannel = params.takeFirst();
91 } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
92 banChannel = bufferInfo.bufferName();
94 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
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));
107 if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
108 int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
109 generalizedHost.replace(0, secondLastPeriodPosition, "*");
111 banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
113 banUser = params.join(" ");
116 QString banMode = ban ? "+b" : "-b";
117 QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
118 emit putRawLine(serverEncode(banMsg));
121 void UserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
124 QString nick = msg.section(' ', 0, 0);
125 QString ctcpTag = msg.section(' ', 1, 1).toUpper();
126 if(ctcpTag.isEmpty())
129 QString message = "";
130 QString verboseMessage = tr("sending CTCP-%1 request").arg(ctcpTag);
132 if(ctcpTag == "PING") {
133 uint now = QDateTime::currentDateTime().toTime_t();
134 message = QString::number(now);
137 network()->ctcpHandler()->query(nick, ctcpTag, message);
138 emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
141 void UserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg) {
142 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
143 QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
145 params << bufferInfo.bufferName() << m << nicks;
146 emit putCmd("MODE", serverEncode(params));
149 void UserInputHandler::handleDevoice(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 += 'v';
153 params << bufferInfo.bufferName() << m << nicks;
154 emit putCmd("MODE", serverEncode(params));
157 void UserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
159 params << msg << bufferInfo.bufferName();
160 emit putCmd("INVITE", serverEncode(params));
163 void UserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
164 Q_UNUSED(bufferInfo);
166 // trim spaces before chans or keys
167 QString sane_msg = msg;
168 sane_msg.replace(QRegExp(", +"), ",");
169 QStringList params = sane_msg.trimmed().split(" ");
170 QStringList chans = params[0].split(",");
173 for(i = 0; i < chans.count(); i++) {
174 if(!network()->isChannelName(chans[i]))
175 chans[i].prepend('#');
177 params[0] = chans.join(",");
178 if(params.count() > 1) keys = params[1].split(",");
179 emit putCmd("JOIN", serverEncode(params)); // FIXME handle messages longer than 512 bytes!
181 for(; i < keys.count(); i++) {
182 if(i >= chans.count()) break;
183 network()->addChannelKey(chans[i], keys[i]);
185 for(; i < chans.count(); i++) {
186 network()->removeChannelKey(chans[i]);
190 void UserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
191 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
192 QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
194 reason = network()->identityPtr()->kickReason();
196 QList<QByteArray> params;
197 params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
198 emit putCmd("KICK", params);
201 void UserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
203 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
204 QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
205 QList<QByteArray> params;
206 params << serverEncode(nick) << serverEncode(pass);
207 emit putCmd("KILL", params);
211 void UserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
213 emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
216 void UserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
217 if(bufferInfo.bufferName().isEmpty()) return; // server buffer
218 network()->ctcpHandler()->query(bufferInfo.bufferName(), "ACTION", msg);
219 emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
222 void UserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
225 QStringList params = msg.split(' ', QString::SkipEmptyParts);
226 // 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
227 if(!params.isEmpty() && !network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
228 params.prepend(bufferInfo.bufferName());
230 // TODO handle correct encoding for buffer modes (channelEncode())
231 emit putCmd("MODE", serverEncode(params));
234 // TODO: show privmsgs
235 void UserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
236 Q_UNUSED(bufferInfo);
237 if(!msg.contains(' '))
240 QByteArray target = serverEncode(msg.section(' ', 0, 0));
241 putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
244 void UserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
246 QString nick = msg.section(' ', 0, 0);
247 emit putCmd("NICK", serverEncode(nick));
250 void UserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
251 QString bufferName = msg.section(' ', 0, 0);
252 QString payload = msg.section(' ', 1);
253 QList<QByteArray> params;
254 params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
255 emit putCmd("NOTICE", params);
256 emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
259 void UserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
260 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
261 QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
263 params << bufferInfo.bufferName() << m << nicks;
264 emit putCmd("MODE", serverEncode(params));
267 void UserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
269 emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
272 void UserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
273 QList<QByteArray> params;
276 // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
277 QString channelName = msg.section(' ', 0, 0);
278 if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
279 channelName = bufferInfo.bufferName();
282 partReason = msg.mid(channelName.length() + 1);
285 if(partReason.isEmpty())
286 partReason = network()->identityPtr()->partReason();
288 params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
289 emit putCmd("PART", params);
292 void UserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
297 param = QTime::currentTime().toString("hh:mm:ss.zzz");
299 putCmd("PING", serverEncode(param));
302 // TODO: implement queries
303 void UserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
305 QString target = msg.section(' ', 0, 0);
306 QString message = msg.section(' ', 1);
307 if(message.isEmpty())
308 emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, "Starting query with " + target, network()->myNick(), Message::Self);
310 emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
311 handleMsg(bufferInfo, msg);
314 void UserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
316 network()->disconnectFromIrc(true, msg);
319 void UserInputHandler::issueQuit(const QString &reason) {
322 quitReason = network()->identityPtr()->quitReason();
325 emit putCmd("QUIT", serverEncode(quitReason));
328 void UserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
330 emit putRawLine(serverEncode(msg));
333 void UserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
334 if(bufferInfo.bufferName().isEmpty())
335 return; // server buffer
336 putPrivmsg(serverEncode(bufferInfo.bufferName()), channelEncode(bufferInfo.bufferName(), msg));
337 emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
340 void UserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
341 if(bufferInfo.bufferName().isEmpty()) return;
342 QList<QByteArray> params;
343 params << serverEncode(bufferInfo.bufferName());
345 params << channelEncode(bufferInfo.bufferName(), msg);
346 emit putCmd("TOPIC", params);
349 void UserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
350 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
351 QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
353 params << bufferInfo.bufferName() << m << nicks;
354 emit putCmd("MODE", serverEncode(params));
357 void UserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
359 emit putCmd("WHO", serverEncode(msg.split(' ')));
362 void UserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
364 emit putCmd("WHOIS", serverEncode(msg.split(' ')));
367 void UserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
369 emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
372 void UserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
373 for(int i = 0; i < coreSession()->aliasManager().count(); i++) {
374 if(coreSession()->aliasManager()[i].name.toLower() == cmd.toLower()) {
375 expand(coreSession()->aliasManager()[i].expansion, bufferInfo, msg);
379 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: %1 %2").arg(cmd, msg));
382 void UserInputHandler::expand(const QString &alias, const BufferInfo &bufferInfo, const QString &msg) {
383 QRegExp paramRangeR("\\$(\\d+)\\.\\.(\\d*)");
384 QStringList commands = alias.split(QRegExp("; ?"));
385 QStringList params = msg.split(' ');
386 for(int i = 0; i < commands.count(); i++) {
387 QString command = commands[i];
389 // replace ranges like $1..3
390 if(!params.isEmpty()) {
392 while((pos = paramRangeR.indexIn(command)) != -1) {
393 int start = paramRangeR.cap(1).toInt();
395 int end = paramRangeR.cap(2).toInt(&ok);
397 end = params.count();
400 command = command.replace(pos, paramRangeR.matchedLength(), QString());
402 command = command.replace(pos, paramRangeR.matchedLength(), QStringList(params.mid(start - 1, end - start + 1)).join(" "));
407 for(int j = params.count(); j > 0; j--) {
408 IrcUser *ircUser = network()->ircUser(params[j - 1]);
409 command = command.replace(QString("$%1:hostname").arg(j), ircUser ? ircUser->host() : QString("*"));
410 command = command.replace(QString("$%1").arg(j), params[j - 1]);
412 command = command.replace("$0", msg);
413 command = command.replace("$channelname", bufferInfo.bufferName());
414 command = command.replace("$currentnick", network()->myNick());
415 handleUserInput(bufferInfo, command);
420 void UserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
421 static const char *cmd = "PRIVMSG";
422 int overrun = lastParamOverrun(cmd, QList<QByteArray>() << message);
424 static const char *splitter = " .,-";
425 int maxSplitPos = message.count() - overrun;
427 for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
428 splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
431 splitPos = maxSplitPos;
433 putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
434 putPrivmsg(target, message.mid(splitPos));
437 putCmd(cmd, QList<QByteArray>() << target << message);
441 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
442 int UserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms) {
443 // the server will pass our message trunkated to 512 bytes including CRLF with the following format:
444 // ":prefix COMMAND param0 param1 :lastparam"
445 // where prefix = "nickname!user@host"
446 // that means that the last message can be as long as:
447 // 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)
448 IrcUser *me = network()->me();
449 int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
452 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
454 if(!params.isEmpty()) {
455 for(int i = 0; i < params.count() - 1; i++) {
456 maxLen -= (params[i].count() + 1);
458 maxLen -= 2; // " :" last param separator;
460 if(params.last().count() > maxLen) {
461 return params.last().count() - maxLen;