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 "coreuserinputhandler.h"
24 #include "ctcphandler.h"
25 #include "coreidentity.h"
31 CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent)
32 : BasicHandler(parent)
36 void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg) {
40 AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
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));
49 // ====================
51 // ====================
52 void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) {
55 QString awayMsg = msg;
56 IrcUser *me = network()->me();
58 // if there is no message supplied we have to check if we are already away or not
60 if(me && !me->isAway()) {
61 awayMsg = network()->identityPtr()->awayReason();
62 if(awayMsg.isEmpty()) {
68 me->setAwayMessage(awayMsg);
70 putCmd("AWAY", serverEncode(awayMsg));
73 void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
74 banOrUnban(bufferInfo, msg, true);
77 void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
78 banOrUnban(bufferInfo, msg, false);
81 void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
85 QStringList params = msg.split(" ");
87 if(!params.isEmpty() && isChannelName(params[0])) {
88 banChannel = params.takeFirst();
89 } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
90 banChannel = bufferInfo.bufferName();
92 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
96 if(!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
97 IrcUser *ircuser = network()->ircUser(params[0]);
98 // generalizedHost changes <nick> to *!ident@*.sld.tld.
99 QString generalizedHost = ircuser->host();
100 if(generalizedHost.isEmpty()) {
101 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
105 static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
106 if(ipAddress.exactMatch(generalizedHost)) {
107 int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
108 generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
109 } else if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
110 int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
111 generalizedHost.replace(0, secondLastPeriodPosition, "*");
113 banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
115 banUser = params.join(" ");
118 QString banMode = ban ? "+b" : "-b";
119 QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
120 emit putRawLine(serverEncode(banMsg));
123 void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
126 QString nick = msg.section(' ', 0, 0);
127 QString ctcpTag = msg.section(' ', 1, 1).toUpper();
128 if(ctcpTag.isEmpty())
131 QString message = "";
132 QString verboseMessage = tr("sending CTCP-%1 request").arg(ctcpTag);
134 if(ctcpTag == "PING") {
135 uint now = QDateTime::currentDateTime().toTime_t();
136 message = QString::number(now);
139 network()->ctcpHandler()->query(nick, ctcpTag, message);
140 emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
143 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg) {
144 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
145 QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
147 params << bufferInfo.bufferName() << m << nicks;
148 emit putCmd("MODE", serverEncode(params));
151 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg) {
152 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
153 QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
155 params << bufferInfo.bufferName() << m << nicks;
156 emit putCmd("MODE", serverEncode(params));
159 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
161 params << msg << bufferInfo.bufferName();
162 emit putCmd("INVITE", serverEncode(params));
165 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
166 Q_UNUSED(bufferInfo);
168 // trim spaces before chans or keys
169 QString sane_msg = msg;
170 sane_msg.replace(QRegExp(", +"), ",");
171 QStringList params = sane_msg.trimmed().split(" ");
173 QStringList chans = params[0].split(",", QString::SkipEmptyParts);
175 if(params.count() > 1)
176 keys = params[1].split(",");
179 for(i = 0; i < chans.count(); i++) {
180 if(!network()->isChannelName(chans[i]))
181 chans[i].prepend('#');
183 if(i < keys.count()) {
184 network()->addChannelKey(chans[i], keys[i]);
186 network()->removeChannelKey(chans[i]);
190 static const char *cmd = "JOIN";
192 QStringList joinChans, joinKeys;
193 int slicesize = chans.count();
194 QList<QByteArray> encodedParams;
196 // go through all to-be-joined channels and (re)build the join list
197 while(i < chans.count()) {
198 joinChans.append(chans.at(i));
200 joinKeys.append(keys.at(i));
202 // if the channel list we built so far either contains all requested channels or exceeds
203 // the desired amount of channels in this slice, try to send what we have so far
204 if(++i == chans.count() || joinChans.count() >= slicesize) {
206 params.append(joinChans.join(","));
207 params.append(joinKeys.join(","));
208 encodedParams = serverEncode(params);
209 // check if it fits in one command
210 if(lastParamOverrun(cmd, encodedParams) == 0) {
211 emit putCmd(cmd, encodedParams);
212 } else if(slicesize > 1) {
213 // back to start of slice, try again with half the amount of channels
223 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
224 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
225 QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
227 reason = network()->identityPtr()->kickReason();
229 QList<QByteArray> params;
230 params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
231 emit putCmd("KICK", params);
234 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
236 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
237 QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
238 QList<QByteArray> params;
239 params << serverEncode(nick) << serverEncode(pass);
240 emit putCmd("KILL", params);
244 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
246 emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
249 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
250 if(bufferInfo.bufferName().isEmpty()) return; // server buffer
251 network()->ctcpHandler()->query(bufferInfo.bufferName(), "ACTION", msg);
252 emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
255 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
258 QStringList params = msg.split(' ', QString::SkipEmptyParts);
259 // 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
260 if(!params.isEmpty() && !network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
261 params.prepend(bufferInfo.bufferName());
263 // TODO handle correct encoding for buffer modes (channelEncode())
264 emit putCmd("MODE", serverEncode(params));
267 // TODO: show privmsgs
268 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
269 Q_UNUSED(bufferInfo);
270 if(!msg.contains(' '))
273 QByteArray target = serverEncode(msg.section(' ', 0, 0));
274 putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
277 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
279 QString nick = msg.section(' ', 0, 0);
280 emit putCmd("NICK", serverEncode(nick));
283 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
284 QString bufferName = msg.section(' ', 0, 0);
285 QString payload = msg.section(' ', 1);
286 QList<QByteArray> params;
287 params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
288 emit putCmd("NOTICE", params);
289 emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
292 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
293 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
294 QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
296 params << bufferInfo.bufferName() << m << nicks;
297 emit putCmd("MODE", serverEncode(params));
300 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
302 emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
305 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
306 QList<QByteArray> params;
309 // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
310 QString channelName = msg.section(' ', 0, 0);
311 if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
312 channelName = bufferInfo.bufferName();
315 partReason = msg.mid(channelName.length() + 1);
318 if(partReason.isEmpty())
319 partReason = network()->identityPtr()->partReason();
321 params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
322 emit putCmd("PART", params);
325 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
330 param = QTime::currentTime().toString("hh:mm:ss.zzz");
332 putCmd("PING", serverEncode(param));
335 // TODO: implement queries
336 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
338 QString target = msg.section(' ', 0, 0);
339 QString message = msg.section(' ', 1);
340 if(message.isEmpty())
341 emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, "Starting query with " + target, network()->myNick(), Message::Self);
343 emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
344 handleMsg(bufferInfo, msg);
347 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
349 network()->disconnectFromIrc(true, msg);
352 void CoreUserInputHandler::issueQuit(const QString &reason) {
353 emit putCmd("QUIT", serverEncode(reason));
356 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
358 emit putRawLine(serverEncode(msg));
361 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
362 if(bufferInfo.bufferName().isEmpty())
363 return; // server buffer
364 putPrivmsg(serverEncode(bufferInfo.bufferName()), channelEncode(bufferInfo.bufferName(), msg));
365 emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
368 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
369 if(bufferInfo.bufferName().isEmpty()) return;
370 QList<QByteArray> params;
371 params << serverEncode(bufferInfo.bufferName());
373 params << channelEncode(bufferInfo.bufferName(), msg);
374 emit putCmd("TOPIC", params);
377 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
378 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
379 QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
381 params << bufferInfo.bufferName() << m << nicks;
382 emit putCmd("MODE", serverEncode(params));
385 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
386 int splitPos = msg.indexOf(';');
391 int delay = msg.left(splitPos).trimmed().toInt(&ok);
397 QString command = msg.mid(splitPos + 1).trimmed();
398 if(command.isEmpty())
401 _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
404 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
406 emit putCmd("WHO", serverEncode(msg.split(' ')));
409 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
411 emit putCmd("WHOIS", serverEncode(msg.split(' ')));
414 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
416 emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
419 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
420 Q_UNUSED(bufferInfo);
421 emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg));
424 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
425 static const char *cmd = "PRIVMSG";
426 int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << message);
428 static const char *splitter = " .,-";
429 int maxSplitPos = message.count() - overrun;
431 for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
432 splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
435 splitPos = maxSplitPos;
437 putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
438 putPrivmsg(target, message.mid(splitPos));
441 putCmd(cmd, QList<QByteArray>() << target << message);
445 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
446 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms) {
447 // the server will pass our message truncated to 512 bytes including CRLF with the following format:
448 // ":prefix COMMAND param0 param1 :lastparam"
449 // where prefix = "nickname!user@host"
450 // that means that the last message can be as long as:
451 // 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)
452 IrcUser *me = network()->me();
453 int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
456 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
458 if(!params.isEmpty()) {
459 for(int i = 0; i < params.count() - 1; i++) {
460 maxLen -= (params[i].count() + 1);
462 maxLen -= 2; // " :" last param separator;
464 if(params.last().count() > maxLen) {
465 return params.last().count() - maxLen;
474 void CoreUserInputHandler::timerEvent(QTimerEvent *event) {
475 if(!_delayedCommands.contains(event->timerId())) {
476 QObject::timerEvent(event);
479 BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
480 QString rawCommand = _delayedCommands[event->timerId()].command;
481 _delayedCommands.remove(event->timerId());
484 // the stored command might be the result of an alias expansion, so we need to split it up again
485 QStringList commands = rawCommand.split(QRegExp("; ?"));
486 foreach(QString command, commands) {
487 handleUserInput(bufferInfo, command);