1 /***************************************************************************
2 * Copyright (C) 2005-10 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 : CoreBasicHandler(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 = msg.section(' ', 2);
132 QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
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()) {
261 if(!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
262 params.prepend(bufferInfo.bufferName());
263 if(network()->isMyNick(params[0]) && params.count() == 2)
264 network()->updateIssuedModes(params[1]);
265 if(params[0] == "-reset" && params.count() == 1) {
266 // FIXME: give feedback to the user (I don't want to add new strings right now)
267 network()->resetPersistentModes();
272 // TODO handle correct encoding for buffer modes (channelEncode())
273 emit putCmd("MODE", serverEncode(params));
276 // TODO: show privmsgs
277 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
278 Q_UNUSED(bufferInfo);
279 if(!msg.contains(' '))
282 QByteArray target = serverEncode(msg.section(' ', 0, 0));
283 putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
286 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
288 QString nick = msg.section(' ', 0, 0);
289 emit putCmd("NICK", serverEncode(nick));
292 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
293 QString bufferName = msg.section(' ', 0, 0);
294 QString payload = msg.section(' ', 1);
295 QList<QByteArray> params;
296 params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
297 emit putCmd("NOTICE", params);
298 emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
301 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
302 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
303 QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
305 params << bufferInfo.bufferName() << m << nicks;
306 emit putCmd("MODE", serverEncode(params));
309 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
311 emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
314 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
315 QList<QByteArray> params;
318 // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
319 QString channelName = msg.section(' ', 0, 0);
320 if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
321 channelName = bufferInfo.bufferName();
324 partReason = msg.mid(channelName.length() + 1);
327 if(partReason.isEmpty())
328 partReason = network()->identityPtr()->partReason();
330 params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
331 emit putCmd("PART", params);
334 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
339 param = QTime::currentTime().toString("hh:mm:ss.zzz");
341 putCmd("PING", serverEncode(param));
344 // TODO: implement queries
345 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
347 QString target = msg.section(' ', 0, 0);
348 QString message = msg.section(' ', 1);
349 if(message.isEmpty())
350 emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, "Starting query with " + target, network()->myNick(), Message::Self);
352 emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
353 handleMsg(bufferInfo, msg);
356 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
358 network()->disconnectFromIrc(true, msg);
361 void CoreUserInputHandler::issueQuit(const QString &reason) {
362 emit putCmd("QUIT", serverEncode(reason));
365 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
367 emit putRawLine(serverEncode(msg));
370 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
371 if(bufferInfo.bufferName().isEmpty())
372 return; // server buffer
373 putPrivmsg(serverEncode(bufferInfo.bufferName()), channelEncode(bufferInfo.bufferName(), msg));
374 emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
377 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
378 if(bufferInfo.bufferName().isEmpty()) return;
379 QList<QByteArray> params;
380 params << serverEncode(bufferInfo.bufferName());
382 params << channelEncode(bufferInfo.bufferName(), msg);
383 emit putCmd("TOPIC", params);
386 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
387 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
388 QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
390 params << bufferInfo.bufferName() << m << nicks;
391 emit putCmd("MODE", serverEncode(params));
394 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
395 int splitPos = msg.indexOf(';');
400 int delay = msg.left(splitPos).trimmed().toInt(&ok);
406 QString command = msg.mid(splitPos + 1).trimmed();
407 if(command.isEmpty())
410 _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
413 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
415 emit putCmd("WHO", serverEncode(msg.split(' ')));
418 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
420 emit putCmd("WHOIS", serverEncode(msg.split(' ')));
423 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
425 emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
428 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
429 Q_UNUSED(bufferInfo);
430 emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
433 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
434 static const char *cmd = "PRIVMSG";
435 int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << message);
437 static const char *splitter = " .,-";
438 int maxSplitPos = message.count() - overrun;
440 for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
441 splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
444 splitPos = maxSplitPos;
446 putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
447 putPrivmsg(target, message.mid(splitPos));
450 putCmd(cmd, QList<QByteArray>() << target << message);
454 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
455 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms) {
456 // the server will pass our message truncated to 512 bytes including CRLF with the following format:
457 // ":prefix COMMAND param0 param1 :lastparam"
458 // where prefix = "nickname!user@host"
459 // that means that the last message can be as long as:
460 // 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)
461 IrcUser *me = network()->me();
462 int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
465 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
467 if(!params.isEmpty()) {
468 for(int i = 0; i < params.count() - 1; i++) {
469 maxLen -= (params[i].count() + 1);
471 maxLen -= 2; // " :" last param separator;
473 if(params.last().count() > maxLen) {
474 return params.last().count() - maxLen;
483 void CoreUserInputHandler::timerEvent(QTimerEvent *event) {
484 if(!_delayedCommands.contains(event->timerId())) {
485 QObject::timerEvent(event);
488 BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
489 QString rawCommand = _delayedCommands[event->timerId()].command;
490 _delayedCommands.remove(event->timerId());
493 // the stored command might be the result of an alias expansion, so we need to split it up again
494 QStringList commands = rawCommand.split(QRegExp("; ?"));
495 foreach(QString command, commands) {
496 handleUserInput(bufferInfo, command);