70db4342820fd28eb51e355dabd6a799b6968661
[quassel.git] / src / core / userinputhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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"
21
22 #include "util.h"
23
24 #include "ctcphandler.h"
25 #include "coreidentity.h"
26 #include "ircuser.h"
27
28 #include <QDebug>
29 #include <QRegExp>
30
31 UserInputHandler::UserInputHandler(CoreNetwork *parent)
32   : BasicHandler(parent)
33 {
34 }
35
36 void UserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg_) {
37   if(msg_.isEmpty())
38     return;
39   QString cmd;
40   QString msg = 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
47     cmd = QString("SAY");
48   } else {
49     cmd = msg.section(' ', 0, 0).remove(0, 1).toUpper();
50     msg = msg.section(' ', 1);
51   }
52   handle(cmd, Q_ARG(BufferInfo, bufferInfo), Q_ARG(QString, msg));
53 }
54
55 // ====================
56 //  Public Slots
57 // ====================
58 void UserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) {
59   Q_UNUSED(bufferInfo)
60
61   QString awayMsg = msg;
62   IrcUser *me = network()->me();
63
64   // if there is no message supplied we have to check if we are already away or not
65   if(msg.isEmpty()) {
66     if(me && !me->isAway())
67       awayMsg = network()->identityPtr()->awayReason();
68   }
69   if(me)
70     me->setAwayMessage(awayMsg);
71
72   putCmd("AWAY", serverEncode(awayMsg));
73 }
74
75 void UserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
76   banOrUnban(bufferInfo, msg, true);
77 }
78
79 void UserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
80   banOrUnban(bufferInfo, msg, false);
81 }
82
83 void UserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
84   QString banChannel;
85   QString banUser;
86
87   QStringList params = msg.split(" ");
88
89   if(!params.isEmpty() && isChannelName(params[0])) {
90     banChannel = params.takeFirst();
91   } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
92     banChannel = bufferInfo.bufferName();
93   } else {
94     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
95     return;
96   }
97
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));
104       return;
105     }
106
107     if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
108       int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
109       generalizedHost.replace(0, secondLastPeriodPosition, "*");
110     }
111     banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
112   } else {
113     banUser = params.join(" ");
114   }
115
116   QString banMode = ban ? "+b" : "-b";
117   QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
118   emit putRawLine(serverEncode(banMsg));
119 }
120
121 void UserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
122   Q_UNUSED(bufferInfo)
123
124   QString nick = msg.section(' ', 0, 0);
125   QString ctcpTag = msg.section(' ', 1, 1).toUpper();
126   if(ctcpTag.isEmpty())
127     return;
128
129   QString message = "";
130   QString verboseMessage = tr("sending CTCP-%1 request").arg(ctcpTag);
131
132   if(ctcpTag == "PING") {
133     uint now = QDateTime::currentDateTime().toTime_t();
134     message = QString::number(now);
135   }
136
137   network()->ctcpHandler()->query(nick, ctcpTag, message);
138   emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
139 }
140
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';
144   QStringList params;
145   params << bufferInfo.bufferName() << m << nicks;
146   emit putCmd("MODE", serverEncode(params));
147 }
148
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';
152   QStringList params;
153   params << bufferInfo.bufferName() << m << nicks;
154   emit putCmd("MODE", serverEncode(params));
155 }
156
157 void UserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
158   QStringList params;
159   params << msg << bufferInfo.bufferName();
160   emit putCmd("INVITE", serverEncode(params));
161 }
162
163 void UserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
164   Q_UNUSED(bufferInfo);
165
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(",");
171   QStringList keys;
172   int i;
173   for(i = 0; i < chans.count(); i++) {
174     if(!network()->isChannelName(chans[i]))
175       chans[i].prepend('#');
176   }
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!
180   i = 0;
181   for(; i < keys.count(); i++) {
182     if(i >= chans.count()) break;
183     network()->addChannelKey(chans[i], keys[i]);
184   }
185   for(; i < chans.count(); i++) {
186     network()->removeChannelKey(chans[i]);
187   }
188 }
189
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();
193   if(reason.isEmpty())
194     reason = network()->identityPtr()->kickReason();
195
196   QList<QByteArray> params;
197   params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
198   emit putCmd("KICK", params);
199 }
200
201 void UserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
202   Q_UNUSED(bufferInfo)
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);
208 }
209
210
211 void UserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
212   Q_UNUSED(bufferInfo)
213   emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
214 }
215
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);
220 }
221
222 void UserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
223   Q_UNUSED(bufferInfo)
224
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());
229
230   // TODO handle correct encoding for buffer modes (channelEncode())
231   emit putCmd("MODE", serverEncode(params));
232 }
233
234 // TODO: show privmsgs
235 void UserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
236   Q_UNUSED(bufferInfo);
237   if(!msg.contains(' '))
238     return;
239
240   QByteArray target = serverEncode(msg.section(' ', 0, 0));
241   putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
242 }
243
244 void UserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
245   Q_UNUSED(bufferInfo)
246   QString nick = msg.section(' ', 0, 0);
247   emit putCmd("NICK", serverEncode(nick));
248 }
249
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);
257 }
258
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';
262   QStringList params;
263   params << bufferInfo.bufferName() << m << nicks;
264   emit putCmd("MODE", serverEncode(params));
265 }
266
267 void UserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
268   Q_UNUSED(bufferInfo)
269   emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
270 }
271
272 void UserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
273   QList<QByteArray> params;
274   QString partReason;
275
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();
280     partReason = msg;
281   } else {
282     partReason = msg.mid(channelName.length() + 1);
283   }
284
285   if(partReason.isEmpty())
286     partReason = network()->identityPtr()->partReason();
287
288   params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
289   emit putCmd("PART", params);
290 }
291
292 void UserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
293   Q_UNUSED(bufferInfo)
294
295   QString param = msg;
296   if(param.isEmpty())
297     param = QTime::currentTime().toString("hh:mm:ss.zzz");
298
299   putCmd("PING", serverEncode(param));
300 }
301
302 // TODO: implement queries
303 void UserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
304   Q_UNUSED(bufferInfo)
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);
309   else
310     emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
311   handleMsg(bufferInfo, msg);
312 }
313
314 void UserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
315   Q_UNUSED(bufferInfo)
316   network()->disconnectFromIrc(true, msg);
317 }
318
319 void UserInputHandler::issueQuit(const QString &reason) {
320   QString quitReason;
321   if(reason.isEmpty())
322     quitReason = network()->identityPtr()->quitReason();
323   else
324     quitReason = reason;
325   emit putCmd("QUIT", serverEncode(quitReason));
326 }
327
328 void UserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
329   Q_UNUSED(bufferInfo)
330   emit putRawLine(serverEncode(msg));
331 }
332
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);
338 }
339
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());
344   if(!msg.isEmpty())
345     params << channelEncode(bufferInfo.bufferName(), msg);
346   emit putCmd("TOPIC", params);
347 }
348
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';
352   QStringList params;
353   params << bufferInfo.bufferName() << m << nicks;
354   emit putCmd("MODE", serverEncode(params));
355 }
356
357 void UserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
358   Q_UNUSED(bufferInfo)
359   emit putCmd("WHO", serverEncode(msg.split(' ')));
360 }
361
362 void UserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
363   Q_UNUSED(bufferInfo)
364   emit putCmd("WHOIS", serverEncode(msg.split(' ')));
365 }
366
367 void UserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
368   Q_UNUSED(bufferInfo)
369   emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
370 }
371
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);
376       return;
377     }
378   }
379   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: %1 %2").arg(cmd, msg));
380 }
381
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];
388
389     // replace ranges like $1..3
390     if(!params.isEmpty()) {
391       int pos;
392       while((pos = paramRangeR.indexIn(command)) != -1) {
393         int start = paramRangeR.cap(1).toInt();
394         bool ok;
395         int end = paramRangeR.cap(2).toInt(&ok);
396         if(!ok) {
397           end = params.count();
398         }
399         if(end < start)
400           command = command.replace(pos, paramRangeR.matchedLength(), QString());
401         else {
402           command = command.replace(pos, paramRangeR.matchedLength(), QStringList(params.mid(start - 1, end - start + 1)).join(" "));
403         }
404       }
405     }
406
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]);
411     }
412     command = command.replace("$0", msg);
413     command = command.replace("$channelname", bufferInfo.bufferName());
414     command = command.replace("$currentnick", network()->myNick());
415     handleUserInput(bufferInfo, command);
416   }
417 }
418
419
420 void UserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
421   static const char *cmd = "PRIVMSG";
422   int overrun = lastParamOverrun(cmd, QList<QByteArray>() << message);
423   if(overrun) {
424     static const char *splitter = " .,-";
425     int maxSplitPos = message.count() - overrun;
426     int splitPos = -1;
427     for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
428       splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
429     }
430     if(splitPos <= 0) {
431       splitPos = maxSplitPos;
432     }
433     putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
434     putPrivmsg(target, message.mid(splitPos));
435     return;
436   } else {
437     putCmd(cmd, QList<QByteArray>() << target << message);
438   }
439 }
440
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> &params) {
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?)
450
451   if(me)
452     maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
453
454   if(!params.isEmpty()) {
455     for(int i = 0; i < params.count() - 1; i++) {
456       maxLen -= (params[i].count() + 1);
457     }
458     maxLen -= 2; // " :" last param separator;
459
460     if(params.last().count() > maxLen) {
461       return params.last().count() - maxLen;
462     } else {
463       return 0;
464     }
465   } else {
466     return 0;
467   }
468 }
469