fixing BR #297 - the core now really loads the default aliases if the list is empty
[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 "networkconnection.h"
25 #include "network.h"
26 #include "ctcphandler.h"
27 #include "ircuser.h"
28
29 #include <QDebug>
30 #include <QRegExp>
31
32 UserInputHandler::UserInputHandler(NetworkConnection *parent) : BasicHandler(parent) {
33 }
34
35 void UserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg_) {
36   try {
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   } catch(Exception e) {
54     emit displayMsg(Message::Error, bufferInfo.type(), "", e.msg());
55   }
56 }
57
58 // ====================
59 //  Public Slots
60 // ====================
61
62 void UserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) {
63   Q_UNUSED(bufferInfo)
64
65   QString awayMsg = msg;
66   IrcUser *me = network()->me();
67
68   // if there is no message supplied we have to check if we are already away or not
69   if(msg.isEmpty()) {
70     if(me && !me->isAway())
71       awayMsg = networkConnection()->identity()->awayReason();
72   }
73   if(me)
74     me->setAwayMessage(awayMsg);
75
76   putCmd("AWAY", serverEncode(awayMsg));
77 }
78
79 void UserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
80   banOrUnban(bufferInfo, msg, true);
81 }
82
83 void UserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
84   banOrUnban(bufferInfo, msg, false);
85 }
86
87 void UserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
88   QString banChannel;
89   QString banUser;
90
91   QStringList params = msg.split(" ");
92
93   if(!params.isEmpty() && isChannelName(params[0])) {
94     banChannel = params.takeFirst();
95   } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
96     banChannel = bufferInfo.bufferName();
97   } else {
98     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
99     return;
100   }
101
102   if(!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
103     IrcUser *ircuser = network()->ircUser(params[0]);
104     // generalizedHost changes <nick> to  *!ident@*.sld.tld.
105     QString generalizedHost = ircuser->host();
106     if(generalizedHost.isEmpty()) {
107       emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
108       return;
109     }
110
111     if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
112       int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
113       generalizedHost.replace(0, secondLastPeriodPosition, "*");
114     }
115     banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
116   } else {
117     banUser = params.join(" ");
118   }
119
120   QString banMode = ban ? "+b" : "-b";
121   QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
122   emit putRawLine(serverEncode(banMsg));
123 }
124
125 void UserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
126   Q_UNUSED(bufferInfo)
127   QString nick = msg.section(' ', 0, 0);
128   QString ctcpTag = msg.section(' ', 1, 1).toUpper();
129   if (ctcpTag.isEmpty()) return;
130   QString message = "";
131   QString verboseMessage = tr("sending CTCP-%1 request").arg(ctcpTag);
132
133   if(ctcpTag == "PING") {
134     uint now = QDateTime::currentDateTime().toTime_t();
135     message = QString::number(now);
136   }
137
138   networkConnection()->ctcpHandler()->query(nick, ctcpTag, message);
139   emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
140 }
141
142 void UserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg) {
143   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
144   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
145   QStringList params;
146   params << bufferInfo.bufferName() << m << nicks;
147   emit putCmd("MODE", serverEncode(params));
148 }
149
150 void UserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg) {
151   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
152   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
153   QStringList params;
154   params << bufferInfo.bufferName() << m << nicks;
155   emit putCmd("MODE", serverEncode(params));
156 }
157
158 void UserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
159   QStringList params;
160   params << msg << bufferInfo.bufferName();
161   emit putCmd("INVITE", serverEncode(params));
162 }
163
164 void UserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
165   Q_UNUSED(bufferInfo);
166
167   // trim spaces before chans or keys
168   QString sane_msg = msg;
169   sane_msg.replace(QRegExp(", +"), ",");
170   QStringList params = sane_msg.trimmed().split(" ");
171   QStringList chans = params[0].split(",");
172   QStringList keys;
173   int i;
174   for(i = 0; i < chans.count(); i++) {
175     if(!network()->isChannelName(chans[i]))
176       chans[i].prepend('#');
177   }
178   params[0] = chans.join(",");
179   if(params.count() > 1) keys = params[1].split(",");
180   emit putCmd("JOIN", serverEncode(params)); // FIXME handle messages longer than 512 bytes!
181   i = 0;
182   for(; i < keys.count(); i++) {
183     if(i >= chans.count()) break;
184     networkConnection()->addChannelKey(chans[i], keys[i]);
185   }
186   for(; i < chans.count(); i++) {
187     networkConnection()->removeChannelKey(chans[i]);
188   }
189 }
190
191 void UserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
192   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
193   QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
194   if(reason.isEmpty())
195     reason = networkConnection()->identity()->kickReason();
196
197   QList<QByteArray> params;
198   params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
199   emit putCmd("KICK", params);
200 }
201
202 void UserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
203   Q_UNUSED(bufferInfo)
204   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
205   QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
206   QList<QByteArray> params;
207   params << serverEncode(nick) << serverEncode(pass);
208   emit putCmd("KILL", params);
209 }
210
211
212 void UserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
213   Q_UNUSED(bufferInfo)
214   emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
215 }
216
217 void UserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
218   if(bufferInfo.bufferName().isEmpty()) return; // server buffer
219   networkConnection()->ctcpHandler()->query(bufferInfo.bufferName(), "ACTION", msg);
220   emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
221 }
222
223 void UserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
224   Q_UNUSED(bufferInfo)
225
226   QStringList params = msg.split(' ', QString::SkipEmptyParts);
227   // 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
228   if(!params.isEmpty() && !network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
229     params.prepend(bufferInfo.bufferName());
230
231   // TODO handle correct encoding for buffer modes (channelEncode())
232   emit putCmd("MODE", serverEncode(params));
233 }
234
235 // TODO: show privmsgs
236 void UserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
237   Q_UNUSED(bufferInfo);
238   if(!msg.contains(' '))
239     return;
240
241   QList<QByteArray> params;
242   params << serverEncode(msg.section(' ', 0, 0));
243   params << userEncode(params[0], msg.section(' ', 1));
244
245   emit putCmd("PRIVMSG", params);
246 }
247
248 void UserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
249   Q_UNUSED(bufferInfo)
250   QString nick = msg.section(' ', 0, 0);
251   emit putCmd("NICK", serverEncode(nick));
252 }
253
254 void UserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
255   QString bufferName = msg.section(' ', 0, 0);
256   QString payload = msg.section(' ', 1);
257   QList<QByteArray> params;
258   params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
259   emit putCmd("NOTICE", params);
260   emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
261 }
262
263 void UserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
264   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
265   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
266   QStringList params;
267   params << bufferInfo.bufferName() << m << nicks;
268   emit putCmd("MODE", serverEncode(params));
269 }
270
271 void UserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
272   Q_UNUSED(bufferInfo)
273   emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
274 }
275
276 void UserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
277   QList<QByteArray> params;
278   QString partReason;
279
280   // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
281   QString channelName = msg.section(' ', 0, 0);
282   if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
283     channelName = bufferInfo.bufferName();
284     partReason = msg;
285   } else {
286     partReason = msg.mid(channelName.length() + 1);
287   }
288
289   if(partReason.isEmpty())
290     partReason = networkConnection()->identity()->partReason();
291
292   params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
293   emit putCmd("PART", params);
294 }
295
296 void UserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
297   Q_UNUSED(bufferInfo)
298
299   QString param = msg;
300   if(param.isEmpty())
301     param = QTime::currentTime().toString("hh:mm:ss.zzz");
302
303   putCmd("PING", serverEncode(param));
304 }
305
306 // TODO: implement queries
307 void UserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
308   Q_UNUSED(bufferInfo)
309   QString target = msg.section(' ', 0, 0);
310   QString message = msg.section(' ', 1);
311   if(message.isEmpty())
312     emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, "Starting query with " + target, network()->myNick(), Message::Self);
313   else
314     emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
315   handleMsg(bufferInfo, msg);
316 }
317
318 void UserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
319   Q_UNUSED(bufferInfo)
320
321   QString quitReason;
322   if(msg.isEmpty())
323     quitReason = networkConnection()->identity()->quitReason();
324   else
325     quitReason = msg;
326
327   emit putCmd("QUIT", serverEncode(quitReason));
328   networkConnection()->disconnectFromIrc();
329 }
330
331 void UserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
332   Q_UNUSED(bufferInfo)
333   emit putRawLine(serverEncode(msg));
334 }
335
336 void UserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
337   if(bufferInfo.bufferName().isEmpty()) return;  // server buffer
338   QList<QByteArray> params;
339   params << serverEncode(bufferInfo.bufferName()) << channelEncode(bufferInfo.bufferName(), msg);
340   emit putCmd("PRIVMSG", params);
341   emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
342 }
343
344 void UserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
345   if(bufferInfo.bufferName().isEmpty()) return;
346   if(!msg.isEmpty()) {
347     QList<QByteArray> params;
348     params << serverEncode(bufferInfo.bufferName()) << channelEncode(bufferInfo.bufferName(), msg);
349     emit putCmd("TOPIC", params);
350   } else {
351     emit networkConnection()->putRawLine("TOPIC " + serverEncode(bufferInfo.bufferName()) + " :");
352   }
353 }
354
355 void UserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
356   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
357   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
358   QStringList params;
359   params << bufferInfo.bufferName() << m << nicks;
360   emit putCmd("MODE", serverEncode(params));
361 }
362
363 void UserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
364   Q_UNUSED(bufferInfo)
365   emit putCmd("WHO", serverEncode(msg.split(' ')));
366 }
367
368 void UserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
369   Q_UNUSED(bufferInfo)
370   emit putCmd("WHOIS", serverEncode(msg.split(' ')));
371 }
372
373 void UserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
374   Q_UNUSED(bufferInfo)
375   emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
376 }
377
378 void UserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
379   for(int i = 0; i < coreSession()->aliasManager().count(); i++) {
380     if(coreSession()->aliasManager()[i].name.toLower() == cmd.toLower()) {
381       expand(coreSession()->aliasManager()[i].expansion, bufferInfo, msg);
382       return;
383     }
384   }
385   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: %1 %2").arg(cmd, msg));
386 }
387
388 void UserInputHandler::expand(const QString &alias, const BufferInfo &bufferInfo, const QString &msg) {
389   QRegExp paramRangeR("\\$(\\d+)\\.\\.(\\d*)");
390   QStringList commands = alias.split(QRegExp("; ?"));
391   QStringList params = msg.split(' ');
392   for(int i = 0; i < commands.count(); i++) {
393     QString command = commands[i];
394
395     // replace ranges like $1..3
396     if(!params.isEmpty()) {
397       int pos;
398       while((pos = paramRangeR.indexIn(command)) != -1) {
399         int start = paramRangeR.cap(1).toInt();
400         bool ok;
401         int end = paramRangeR.cap(2).toInt(&ok);
402         if(!ok) {
403           end = params.count();
404         }
405         if(end < start)
406           command = command.replace(pos, paramRangeR.matchedLength(), QString());
407         else {
408           command = command.replace(pos, paramRangeR.matchedLength(), QStringList(params.mid(start - 1, end - start + 1)).join(" "));
409         }
410       }
411     }
412
413     for(int j = params.count(); j > 0; j--) {
414       IrcUser *ircUser = network()->ircUser(params[j - 1]);
415       command = command.replace(QString("$%1:hostname").arg(j), ircUser ? ircUser->host() : QString("*"));
416       command = command.replace(QString("$%1").arg(j), params[j - 1]);
417     }
418     command = command.replace("$0", msg);
419     command = command.replace("$channelname", bufferInfo.bufferName());
420     command = command.replace("$currentnick", network()->myNick());
421     handleUserInput(bufferInfo, command);
422   }
423 }
424
425
426