Move alias handling into the client
[quassel.git] / src / core / userinputhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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
40   // FIXME: With protocol >= v10, this is all done in the client -> remove
41   QString cmd;
42   QString msg = msg_;
43   // leading slashes indicate there's a command to call unless there is another one in the first section (like a path /proc/cpuinfo)
44   int secondSlashPos = msg.indexOf('/', 1);
45   int firstSpacePos = msg.indexOf(' ');
46   if(!msg.startsWith('/') || (secondSlashPos != -1 && (secondSlashPos < firstSpacePos || firstSpacePos == -1))) {
47     if(msg.startsWith("//"))
48       msg.remove(0, 1); // //asdf is transformed to /asdf
49     cmd = QString("SAY");
50   } else {
51     cmd = msg.section(' ', 0, 0).remove(0, 1).toUpper();
52     msg = msg.section(' ', 1);
53   }
54   handle(cmd, Q_ARG(BufferInfo, bufferInfo), Q_ARG(QString, msg));
55 }
56
57 // ====================
58 //  Public Slots
59 // ====================
60 void UserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) {
61   Q_UNUSED(bufferInfo)
62
63   QString awayMsg = msg;
64   IrcUser *me = network()->me();
65
66   // if there is no message supplied we have to check if we are already away or not
67   if(msg.isEmpty()) {
68     if(me && !me->isAway()) {
69       awayMsg = network()->identityPtr()->awayReason();
70       if(awayMsg.isEmpty()) {
71         awayMsg = tr("away");
72       }
73     }
74   }
75   if(me)
76     me->setAwayMessage(awayMsg);
77
78   putCmd("AWAY", serverEncode(awayMsg));
79 }
80
81 void UserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
82   banOrUnban(bufferInfo, msg, true);
83 }
84
85 void UserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
86   banOrUnban(bufferInfo, msg, false);
87 }
88
89 void UserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
90   QString banChannel;
91   QString banUser;
92
93   QStringList params = msg.split(" ");
94
95   if(!params.isEmpty() && isChannelName(params[0])) {
96     banChannel = params.takeFirst();
97   } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
98     banChannel = bufferInfo.bufferName();
99   } else {
100     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
101     return;
102   }
103
104   if(!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
105     IrcUser *ircuser = network()->ircUser(params[0]);
106     // generalizedHost changes <nick> to  *!ident@*.sld.tld.
107     QString generalizedHost = ircuser->host();
108     if(generalizedHost.isEmpty()) {
109       emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
110       return;
111     }
112
113     static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
114     if(ipAddress.exactMatch(generalizedHost))    {
115         int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
116         generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
117     } else if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
118       int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
119       generalizedHost.replace(0, secondLastPeriodPosition, "*");
120     }
121     banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
122   } else {
123     banUser = params.join(" ");
124   }
125
126   QString banMode = ban ? "+b" : "-b";
127   QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
128   emit putRawLine(serverEncode(banMsg));
129 }
130
131 void UserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
132   Q_UNUSED(bufferInfo)
133
134   QString nick = msg.section(' ', 0, 0);
135   QString ctcpTag = msg.section(' ', 1, 1).toUpper();
136   if(ctcpTag.isEmpty())
137     return;
138
139   QString message = "";
140   QString verboseMessage = tr("sending CTCP-%1 request").arg(ctcpTag);
141
142   if(ctcpTag == "PING") {
143     uint now = QDateTime::currentDateTime().toTime_t();
144     message = QString::number(now);
145   }
146
147   network()->ctcpHandler()->query(nick, ctcpTag, message);
148   emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
149 }
150
151 void UserInputHandler::handleDeop(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 += 'o';
154   QStringList params;
155   params << bufferInfo.bufferName() << m << nicks;
156   emit putCmd("MODE", serverEncode(params));
157 }
158
159 void UserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg) {
160   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
161   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
162   QStringList params;
163   params << bufferInfo.bufferName() << m << nicks;
164   emit putCmd("MODE", serverEncode(params));
165 }
166
167 void UserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
168   QStringList params;
169   params << msg << bufferInfo.bufferName();
170   emit putCmd("INVITE", serverEncode(params));
171 }
172
173 void UserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
174   Q_UNUSED(bufferInfo);
175
176   // trim spaces before chans or keys
177   QString sane_msg = msg;
178   sane_msg.replace(QRegExp(", +"), ",");
179   QStringList params = sane_msg.trimmed().split(" ");
180   QStringList chans = params[0].split(",");
181   QStringList keys;
182   int i;
183   for(i = 0; i < chans.count(); i++) {
184     if(!network()->isChannelName(chans[i]))
185       chans[i].prepend('#');
186   }
187   params[0] = chans.join(",");
188   if(params.count() > 1) keys = params[1].split(",");
189   emit putCmd("JOIN", serverEncode(params)); // FIXME handle messages longer than 512 bytes!
190   i = 0;
191   for(; i < keys.count(); i++) {
192     if(i >= chans.count()) break;
193     network()->addChannelKey(chans[i], keys[i]);
194   }
195   for(; i < chans.count(); i++) {
196     network()->removeChannelKey(chans[i]);
197   }
198 }
199
200 void UserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
201   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
202   QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
203   if(reason.isEmpty())
204     reason = network()->identityPtr()->kickReason();
205
206   QList<QByteArray> params;
207   params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
208   emit putCmd("KICK", params);
209 }
210
211 void UserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
212   Q_UNUSED(bufferInfo)
213   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
214   QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
215   QList<QByteArray> params;
216   params << serverEncode(nick) << serverEncode(pass);
217   emit putCmd("KILL", params);
218 }
219
220
221 void UserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
222   Q_UNUSED(bufferInfo)
223   emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
224 }
225
226 void UserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
227   if(bufferInfo.bufferName().isEmpty()) return; // server buffer
228   network()->ctcpHandler()->query(bufferInfo.bufferName(), "ACTION", msg);
229   emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
230 }
231
232 void UserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
233   Q_UNUSED(bufferInfo)
234
235   QStringList params = msg.split(' ', QString::SkipEmptyParts);
236   // 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
237   if(!params.isEmpty() && !network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
238     params.prepend(bufferInfo.bufferName());
239
240   // TODO handle correct encoding for buffer modes (channelEncode())
241   emit putCmd("MODE", serverEncode(params));
242 }
243
244 // TODO: show privmsgs
245 void UserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
246   Q_UNUSED(bufferInfo);
247   if(!msg.contains(' '))
248     return;
249
250   QByteArray target = serverEncode(msg.section(' ', 0, 0));
251   putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
252 }
253
254 void UserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
255   Q_UNUSED(bufferInfo)
256   QString nick = msg.section(' ', 0, 0);
257   emit putCmd("NICK", serverEncode(nick));
258 }
259
260 void UserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
261   QString bufferName = msg.section(' ', 0, 0);
262   QString payload = msg.section(' ', 1);
263   QList<QByteArray> params;
264   params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
265   emit putCmd("NOTICE", params);
266   emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
267 }
268
269 void UserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
270   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
271   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
272   QStringList params;
273   params << bufferInfo.bufferName() << m << nicks;
274   emit putCmd("MODE", serverEncode(params));
275 }
276
277 void UserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
278   Q_UNUSED(bufferInfo)
279   emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
280 }
281
282 void UserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
283   QList<QByteArray> params;
284   QString partReason;
285
286   // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
287   QString channelName = msg.section(' ', 0, 0);
288   if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
289     channelName = bufferInfo.bufferName();
290     partReason = msg;
291   } else {
292     partReason = msg.mid(channelName.length() + 1);
293   }
294
295   if(partReason.isEmpty())
296     partReason = network()->identityPtr()->partReason();
297
298   params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
299   emit putCmd("PART", params);
300 }
301
302 void UserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
303   Q_UNUSED(bufferInfo)
304
305   QString param = msg;
306   if(param.isEmpty())
307     param = QTime::currentTime().toString("hh:mm:ss.zzz");
308
309   putCmd("PING", serverEncode(param));
310 }
311
312 // TODO: implement queries
313 void UserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
314   Q_UNUSED(bufferInfo)
315   QString target = msg.section(' ', 0, 0);
316   QString message = msg.section(' ', 1);
317   if(message.isEmpty())
318     emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, "Starting query with " + target, network()->myNick(), Message::Self);
319   else
320     emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
321   handleMsg(bufferInfo, msg);
322 }
323
324 void UserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
325   Q_UNUSED(bufferInfo)
326   network()->disconnectFromIrc(true, msg);
327 }
328
329 void UserInputHandler::issueQuit(const QString &reason) {
330   emit putCmd("QUIT", serverEncode(reason));
331 }
332
333 void UserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
334   Q_UNUSED(bufferInfo)
335   emit putRawLine(serverEncode(msg));
336 }
337
338 void UserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
339   if(bufferInfo.bufferName().isEmpty())
340     return;  // server buffer
341   putPrivmsg(serverEncode(bufferInfo.bufferName()), channelEncode(bufferInfo.bufferName(), msg));
342   emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
343 }
344
345 void UserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
346   if(bufferInfo.bufferName().isEmpty()) return;
347   QList<QByteArray> params;
348   params << serverEncode(bufferInfo.bufferName());
349   if(!msg.isEmpty())
350     params << channelEncode(bufferInfo.bufferName(), msg);
351   emit putCmd("TOPIC", params);
352 }
353
354 void UserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
355   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
356   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
357   QStringList params;
358   params << bufferInfo.bufferName() << m << nicks;
359   emit putCmd("MODE", serverEncode(params));
360 }
361
362 void UserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
363   int splitPos = msg.indexOf(';');
364   if(splitPos <= 0)
365     return;
366
367   bool ok;
368   int delay = msg.left(splitPos).trimmed().toInt(&ok);
369   if(!ok)
370     return;
371
372   delay *= 1000;
373
374   QString command = msg.mid(splitPos + 1).trimmed();
375   if(command.isEmpty())
376     return;
377
378   _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
379 }
380
381 void UserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
382   Q_UNUSED(bufferInfo)
383   emit putCmd("WHO", serverEncode(msg.split(' ')));
384 }
385
386 void UserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
387   Q_UNUSED(bufferInfo)
388   emit putCmd("WHOIS", serverEncode(msg.split(' ')));
389 }
390
391 void UserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
392   Q_UNUSED(bufferInfo)
393   emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
394 }
395
396 // FIXME: Remove alias handling as soon as core protocol >= v10
397 void UserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
398   for(int i = 0; i < coreSession()->aliasManager().count(); i++) {
399     if(coreSession()->aliasManager()[i].name.toLower() == cmd.toLower()) {
400       expand(coreSession()->aliasManager()[i].expansion, bufferInfo, msg);
401       return;
402     }
403   }
404   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: %1 %2").arg(cmd, msg));
405 }
406
407 void UserInputHandler::expand(const QString &alias, const BufferInfo &bufferInfo, const QString &msg) {
408   QRegExp paramRangeR("\\$(\\d+)\\.\\.(\\d*)");
409   QStringList commands = alias.split(QRegExp("; ?"));
410   QStringList params = msg.split(' ');
411   QStringList expandedCommands;
412   for(int i = 0; i < commands.count(); i++) {
413     QString command = commands[i];
414
415     // replace ranges like $1..3
416     if(!params.isEmpty()) {
417       int pos;
418       while((pos = paramRangeR.indexIn(command)) != -1) {
419         int start = paramRangeR.cap(1).toInt();
420         bool ok;
421         int end = paramRangeR.cap(2).toInt(&ok);
422         if(!ok) {
423           end = params.count();
424         }
425         if(end < start)
426           command = command.replace(pos, paramRangeR.matchedLength(), QString());
427         else {
428           command = command.replace(pos, paramRangeR.matchedLength(), QStringList(params.mid(start - 1, end - start + 1)).join(" "));
429         }
430       }
431     }
432
433     for(int j = params.count(); j > 0; j--) {
434       IrcUser *ircUser = network()->ircUser(params[j - 1]);
435       command = command.replace(QString("$%1:hostname").arg(j), ircUser ? ircUser->host() : QString("*"));
436       command = command.replace(QString("$%1").arg(j), params[j - 1]);
437     }
438     command = command.replace("$0", msg);
439     command = command.replace("$channelname", bufferInfo.bufferName());
440     command = command.replace("$currentnick", network()->myNick());
441     expandedCommands << command;
442   }
443
444   while(!expandedCommands.isEmpty()) {
445     QString command;
446     if(expandedCommands[0].trimmed().toLower().startsWith("/wait")) {
447       command = expandedCommands.join("; ");
448       expandedCommands.clear();
449     } else {
450       command = expandedCommands.takeFirst();
451     }
452     handleUserInput(bufferInfo, command);
453   }
454 }
455
456
457 void UserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
458   static const char *cmd = "PRIVMSG";
459   int overrun = lastParamOverrun(cmd, QList<QByteArray>() << message);
460   if(overrun) {
461     static const char *splitter = " .,-";
462     int maxSplitPos = message.count() - overrun;
463     int splitPos = -1;
464     for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
465       splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
466     }
467     if(splitPos <= 0) {
468       splitPos = maxSplitPos;
469     }
470     putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
471     putPrivmsg(target, message.mid(splitPos));
472     return;
473   } else {
474     putCmd(cmd, QList<QByteArray>() << target << message);
475   }
476 }
477
478 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
479 int UserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params) {
480   // the server will pass our message trunkated to 512 bytes including CRLF with the following format:
481   // ":prefix COMMAND param0 param1 :lastparam"
482   // where prefix = "nickname!user@host"
483   // that means that the last message can be as long as:
484   // 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)
485   IrcUser *me = network()->me();
486   int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
487
488   if(me)
489     maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
490
491   if(!params.isEmpty()) {
492     for(int i = 0; i < params.count() - 1; i++) {
493       maxLen -= (params[i].count() + 1);
494     }
495     maxLen -= 2; // " :" last param separator;
496
497     if(params.last().count() > maxLen) {
498       return params.last().count() - maxLen;
499     } else {
500       return 0;
501     }
502   } else {
503     return 0;
504   }
505 }
506
507
508 void UserInputHandler::timerEvent(QTimerEvent *event) {
509   if(!_delayedCommands.contains(event->timerId())) {
510     QObject::timerEvent(event);
511     return;
512   }
513   BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
514   QString rawCommand = _delayedCommands[event->timerId()].command;
515   _delayedCommands.remove(event->timerId());
516   event->accept();
517
518   // the stored command might be the result of an alias expansion, so we need to split it up again
519   QStringList commands = rawCommand.split(QRegExp("; ?"));
520   foreach(QString command, commands) {
521     handleUserInput(bufferInfo, command);
522   }
523 }