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