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) {
54 if(msg.startsWith("-all")) {
55 if(msg.length() == 4) {
56 coreSession()->globalAway();
59 Q_ASSERT(msg.length() > 4);
61 coreSession()->globalAway(msg.mid(5));
68 void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck) {
69 QString awayMsg = msg;
70 IrcUser *me = network()->me();
72 // if there is no message supplied we have to check if we are already away or not
73 if(autoCheck && msg.isEmpty()) {
74 if(me && !me->isAway()) {
75 Identity *identity = network()->identityPtr();
77 awayMsg = identity->awayReason();
79 if(awayMsg.isEmpty()) {
85 me->setAwayMessage(awayMsg);
87 putCmd("AWAY", serverEncode(awayMsg));
90 void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
91 banOrUnban(bufferInfo, msg, true);
94 void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
95 banOrUnban(bufferInfo, msg, false);
98 void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
102 QStringList params = msg.split(" ");
104 if(!params.isEmpty() && isChannelName(params[0])) {
105 banChannel = params.takeFirst();
106 } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
107 banChannel = bufferInfo.bufferName();
109 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
113 if(!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
114 IrcUser *ircuser = network()->ircUser(params[0]);
115 // generalizedHost changes <nick> to *!ident@*.sld.tld.
116 QString generalizedHost = ircuser->host();
117 if(generalizedHost.isEmpty()) {
118 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
122 static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
123 if(ipAddress.exactMatch(generalizedHost)) {
124 int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
125 generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
126 } else if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
127 int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
128 generalizedHost.replace(0, secondLastPeriodPosition, "*");
130 banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
132 banUser = params.join(" ");
135 QString banMode = ban ? "+b" : "-b";
136 QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
137 emit putRawLine(serverEncode(banMsg));
140 void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
143 QString nick = msg.section(' ', 0, 0);
144 QString ctcpTag = msg.section(' ', 1, 1).toUpper();
145 if(ctcpTag.isEmpty())
148 QString message = msg.section(' ', 2);
149 QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
151 if(ctcpTag == "PING") {
152 uint now = QDateTime::currentDateTime().toTime_t();
153 message = QString::number(now);
156 network()->ctcpHandler()->query(nick, ctcpTag, message);
157 emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
160 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg) {
161 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
162 QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
164 params << bufferInfo.bufferName() << m << nicks;
165 emit putCmd("MODE", serverEncode(params));
168 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg) {
169 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
170 QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
172 params << bufferInfo.bufferName() << m << nicks;
173 emit putCmd("MODE", serverEncode(params));
176 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
178 params << msg << bufferInfo.bufferName();
179 emit putCmd("INVITE", serverEncode(params));
182 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
183 Q_UNUSED(bufferInfo);
185 // trim spaces before chans or keys
186 QString sane_msg = msg;
187 sane_msg.replace(QRegExp(", +"), ",");
188 QStringList params = sane_msg.trimmed().split(" ");
190 QStringList chans = params[0].split(",", QString::SkipEmptyParts);
192 if(params.count() > 1)
193 keys = params[1].split(",");
196 for(i = 0; i < chans.count(); i++) {
197 if(!network()->isChannelName(chans[i]))
198 chans[i].prepend('#');
200 if(i < keys.count()) {
201 network()->addChannelKey(chans[i], keys[i]);
203 network()->removeChannelKey(chans[i]);
207 static const char *cmd = "JOIN";
209 QStringList joinChans, joinKeys;
210 int slicesize = chans.count();
211 QList<QByteArray> encodedParams;
213 // go through all to-be-joined channels and (re)build the join list
214 while(i < chans.count()) {
215 joinChans.append(chans.at(i));
217 joinKeys.append(keys.at(i));
219 // if the channel list we built so far either contains all requested channels or exceeds
220 // the desired amount of channels in this slice, try to send what we have so far
221 if(++i == chans.count() || joinChans.count() >= slicesize) {
223 params.append(joinChans.join(","));
224 params.append(joinKeys.join(","));
225 encodedParams = serverEncode(params);
226 // check if it fits in one command
227 if(lastParamOverrun(cmd, encodedParams) == 0) {
228 emit putCmd(cmd, encodedParams);
229 } else if(slicesize > 1) {
230 // back to start of slice, try again with half the amount of channels
240 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
241 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
242 QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
244 reason = network()->identityPtr()->kickReason();
246 QList<QByteArray> params;
247 params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
248 emit putCmd("KICK", params);
251 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
253 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
254 QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
255 QList<QByteArray> params;
256 params << serverEncode(nick) << serverEncode(pass);
257 emit putCmd("KILL", params);
261 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
263 emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
266 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
267 if(bufferInfo.bufferName().isEmpty()) return; // server buffer
268 network()->ctcpHandler()->query(bufferInfo.bufferName(), "ACTION", msg);
269 emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
272 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
275 QStringList params = msg.split(' ', QString::SkipEmptyParts);
276 // 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
277 if(!params.isEmpty() && !network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
278 params.prepend(bufferInfo.bufferName());
280 // TODO handle correct encoding for buffer modes (channelEncode())
281 emit putCmd("MODE", serverEncode(params));
284 // TODO: show privmsgs
285 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
286 Q_UNUSED(bufferInfo);
287 if(!msg.contains(' '))
290 QByteArray target = serverEncode(msg.section(' ', 0, 0));
291 putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
294 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
296 QString nick = msg.section(' ', 0, 0);
297 emit putCmd("NICK", serverEncode(nick));
300 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
301 QString bufferName = msg.section(' ', 0, 0);
302 QString payload = msg.section(' ', 1);
303 QList<QByteArray> params;
304 params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
305 emit putCmd("NOTICE", params);
306 emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
309 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
310 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
311 QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
313 params << bufferInfo.bufferName() << m << nicks;
314 emit putCmd("MODE", serverEncode(params));
317 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
319 emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
322 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
323 QList<QByteArray> params;
326 // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
327 QString channelName = msg.section(' ', 0, 0);
328 if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
329 channelName = bufferInfo.bufferName();
332 partReason = msg.mid(channelName.length() + 1);
335 if(partReason.isEmpty())
336 partReason = network()->identityPtr()->partReason();
338 params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
339 emit putCmd("PART", params);
342 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
347 param = QTime::currentTime().toString("hh:mm:ss.zzz");
349 putCmd("PING", serverEncode(param));
352 // TODO: implement queries
353 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
355 QString target = msg.section(' ', 0, 0);
356 QString message = msg.section(' ', 1);
357 if(message.isEmpty())
358 emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, "Starting query with " + target, network()->myNick(), Message::Self);
360 emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
361 handleMsg(bufferInfo, msg);
364 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
366 network()->disconnectFromIrc(true, msg);
369 void CoreUserInputHandler::issueQuit(const QString &reason) {
370 emit putCmd("QUIT", serverEncode(reason));
373 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
375 emit putRawLine(serverEncode(msg));
378 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
379 if(bufferInfo.bufferName().isEmpty())
380 return; // server buffer
381 putPrivmsg(serverEncode(bufferInfo.bufferName()), channelEncode(bufferInfo.bufferName(), msg));
382 emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
385 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
386 if(bufferInfo.bufferName().isEmpty()) return;
387 QList<QByteArray> params;
388 params << serverEncode(bufferInfo.bufferName());
390 params << channelEncode(bufferInfo.bufferName(), msg);
391 emit putCmd("TOPIC", params);
394 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
395 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
396 QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
398 params << bufferInfo.bufferName() << m << nicks;
399 emit putCmd("MODE", serverEncode(params));
402 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
403 int splitPos = msg.indexOf(';');
408 int delay = msg.left(splitPos).trimmed().toInt(&ok);
414 QString command = msg.mid(splitPos + 1).trimmed();
415 if(command.isEmpty())
418 _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
421 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
423 emit putCmd("WHO", serverEncode(msg.split(' ')));
426 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
428 emit putCmd("WHOIS", serverEncode(msg.split(' ')));
431 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
433 emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
436 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
437 Q_UNUSED(bufferInfo);
438 emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
441 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
442 static const char *cmd = "PRIVMSG";
443 int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << message);
445 static const char *splitter = " .,-";
446 int maxSplitPos = message.count() - overrun;
448 for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
449 splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
452 splitPos = maxSplitPos;
454 putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
455 putPrivmsg(target, message.mid(splitPos));
458 putCmd(cmd, QList<QByteArray>() << target << message);
462 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
463 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms) {
464 // the server will pass our message truncated to 512 bytes including CRLF with the following format:
465 // ":prefix COMMAND param0 param1 :lastparam"
466 // where prefix = "nickname!user@host"
467 // that means that the last message can be as long as:
468 // 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)
469 IrcUser *me = network()->me();
470 int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
473 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
475 if(!params.isEmpty()) {
476 for(int i = 0; i < params.count() - 1; i++) {
477 maxLen -= (params[i].count() + 1);
479 maxLen -= 2; // " :" last param separator;
481 if(params.last().count() > maxLen) {
482 return params.last().count() - maxLen;
491 void CoreUserInputHandler::timerEvent(QTimerEvent *event) {
492 if(!_delayedCommands.contains(event->timerId())) {
493 QObject::timerEvent(event);
496 BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
497 QString rawCommand = _delayedCommands[event->timerId()].command;
498 _delayedCommands.remove(event->timerId());
501 // the stored command might be the result of an alias expansion, so we need to split it up again
502 QStringList commands = rawCommand.split(QRegExp("; ?"));
503 foreach(QString command, commands) {
504 handleUserInput(bufferInfo, command);