warnings--
[quassel.git] / src / core / eventstringifier.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 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
21 #include "eventstringifier.h"
22
23 #include "coresession.h"
24 #include "ctcpevent.h"
25 #include "messageevent.h"
26
27 EventStringifier::EventStringifier(CoreSession *parent) : BasicHandler("handleCtcp", parent),
28   _coreSession(parent),
29   _whois(false)
30 {
31
32 }
33
34 void EventStringifier::displayMsg(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender,
35                                   const QString &target, Message::Flags msgFlags) {
36   if(event->flags().testFlag(EventManager::Silent))
37     return;
38
39   MessageEvent *msgEvent = createMessageEvent(event, msgType, msg, sender, target, msgFlags);
40   sendMessageEvent(msgEvent);
41 }
42
43 MessageEvent *EventStringifier::createMessageEvent(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender,
44                         const QString &target, Message::Flags msgFlags) {
45   MessageEvent *msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags);
46   msgEvent->setTimestamp(event->timestamp());
47   return msgEvent;
48 }
49
50 void EventStringifier::sendMessageEvent(MessageEvent *event) {
51   coreSession()->eventManager()->sendEvent(event);
52 }
53
54 bool EventStringifier::checkParamCount(IrcEvent *e, int minParams) {
55   if(e->params().count() < minParams) {
56     if(e->type() == EventManager::IrcEventNumeric) {
57       qWarning() << "Command " << static_cast<IrcEventNumeric *>(e)->number() << " requires " << minParams << "params, got: " << e->params();
58     } else {
59       QString name = coreSession()->eventManager()->enumName(e->type());
60       qWarning() << qPrintable(name) << "requires" << minParams << "params, got:" << e->params();
61     }
62     e->stop();
63     return false;
64   }
65   return true;
66 }
67
68 /* These are only for legacy reasons; remove as soon as we handle NetworkSplitEvents properly */
69 void EventStringifier::processNetworkSplitJoin(NetworkSplitEvent *e) {
70   QString msg = e->users().join("#:#") + "#:#" + e->quitMessage();
71   displayMsg(e, Message::NetsplitJoin, msg, QString(), e->channel());
72 }
73
74 void EventStringifier::processNetworkSplitQuit(NetworkSplitEvent *e) {
75   QString msg = e->users().join("#:#") + "#:#" + e->quitMessage();
76   displayMsg(e, Message::NetsplitQuit, msg, QString(), e->channel());
77 }
78
79 /* End legacy */
80
81 void EventStringifier::processIrcEventNumeric(IrcEventNumeric *e) {
82   //qDebug() << e->number();
83   switch(e->number()) {
84   // Welcome, status, info messages. Just display these.
85   case 1: case 2: case 3: case 4: case 5:
86   case 221: case 250: case 251: case 252: case 253: case 254: case 255: case 265: case 266:
87   case 372: case 375:
88     displayMsg(e, Message::Server, e->params().join(" "), e->prefix());
89     break;
90
91   // Server error messages without param, just display them
92   case 409: case 411: case 412: case 422: case 424: case 445: case 446: case 451: case 462:
93   case 463: case 464: case 465: case 466: case 472: case 481: case 483: case 485: case 491: case 501: case 502:
94   case 431: // ERR_NONICKNAMEGIVEN
95     displayMsg(e, Message::Error, e->params().join(" "), e->prefix());
96     break;
97
98   // Server error messages, display them in red. First param will be appended.
99   case 401: {
100     QString target = e->params().takeFirst();
101     displayMsg(e, Message::Error, e->params().join(" ") + " " + target, e->prefix(), target, Message::Redirected);
102     break;
103   }
104
105   case 402: case 403: case 404: case 406: case 408: case 415: case 421: case 442: {
106     QString channelName = e->params().takeFirst();
107     displayMsg(e, Message::Error, e->params().join(" ") + " " + channelName, e->prefix());
108     break;
109   }
110
111   // Server error messages which will be displayed with a colon between the first param and the rest
112   case 413: case 414: case 423: case 441: case 444: case 461:  // FIXME see below for the 47x codes
113   case 467: case 471: case 473: case 474: case 475: case 476: case 477: case 478: case 482:
114   case 436: // ERR_NICKCOLLISION
115   {
116     QString p = e->params().takeFirst();
117     displayMsg(e, Message::Error, p + ": " + e->params().join(" "));
118     break;
119   }
120
121   // Ignore these commands.
122   case 321: case 353: case 366: case 376:
123     break;
124
125   // CAP stuff
126   case 900: case 903: case 904: case 905: case 906: case 907:
127   {
128     displayMsg(e, Message::Info, "CAP: " + e->params().join(""));
129     break;
130   }
131
132   // Everything else will be marked in red, so we can add them somewhere.
133   default:
134     if(_whois) {
135       // many nets define their own WHOIS fields. we fetch those not in need of special attention here:
136       displayMsg(e, Message::Server, tr("[Whois] ") + e->params().join(" "), e->prefix());
137     } else {
138       // FIXME figure out how/where to do this in the future
139       //if(coreSession()->ircListHelper()->requestInProgress(network()->networkId()))
140       //  coreSession()->ircListHelper()->reportError(params.join(" "));
141       //else
142         displayMsg(e, Message::Error, QString("%1 %2").arg(e->number(), 3, 10, QLatin1Char('0')).arg(e->params().join(" ")), e->prefix());
143     }
144   }
145 }
146
147 void EventStringifier::processIrcEventInvite(IrcEvent *e) {
148   displayMsg(e, Message::Invite, tr("%1 invited you to channel %2").arg(e->nick(), e->params().at(1)));
149 }
150
151 void EventStringifier::processIrcEventJoin(IrcEvent *e) {
152   if(e->testFlag(EventManager::Netsplit))
153     return;
154
155   displayMsg(e, Message::Join, e->params()[0], e->prefix(), e->params()[0]);
156 }
157
158 void EventStringifier::processIrcEventKick(IrcEvent *e) {
159   if(!checkParamCount(e, 2))
160     return;
161
162   IrcUser *victim = e->network()->ircUser(e->params().at(1));
163   if(victim) {
164     QString channel = e->params().at(0);
165     QString msg = victim->nick();
166     if(e->params().count() > 2)
167       msg += " " + e->params().at(2);
168
169     displayMsg(e, Message::Kick, msg, e->prefix(), channel);
170   }
171 }
172
173 void EventStringifier::processIrcEventMode(IrcEvent *e) {
174   if(e->network()->isChannelName(e->params().first())) {
175     // Channel Modes
176     displayMsg(e, Message::Mode, e->params().join(" "), e->prefix(), e->params().first());
177   } else {
178     // User Modes
179     // FIXME: redirect
180     displayMsg(e, Message::Mode, e->params().join(" "), e->prefix());
181   }
182 }
183
184 // this needs to be called before the ircuser is renamed!
185 void EventStringifier::processIrcEventNick(IrcEvent *e) {
186   if(!checkParamCount(e, 1))
187     return;
188
189   IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
190   if(!ircuser) {
191     qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
192     return;
193   }
194
195   QString newnick = e->params().at(0);
196   QString oldnick = ircuser->nick();
197
198   QString sender = e->network()->isMyNick(oldnick) ? newnick : e->prefix();
199   foreach(const QString &channel, ircuser->channels())
200     displayMsg(e, Message::Nick, newnick, sender, channel);
201 }
202
203 void EventStringifier::processIrcEventPart(IrcEvent *e) {
204   if(!checkParamCount(e, 1))
205     return;
206
207   QString channel = e->params().at(0);
208   QString msg = e->params().count() > 1? e->params().at(1) : QString();
209
210   displayMsg(e, Message::Part, msg, e->prefix(), channel);
211 }
212
213 void EventStringifier::processIrcEventPong(IrcEvent *e) {
214   QString timestamp = e->params().at(1);
215   QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
216   if(!sendTime.isValid())
217     displayMsg(e, Message::Server, "PONG " + e->params().join(" "), e->prefix());
218 }
219
220 void EventStringifier::processIrcEventQuit(IrcEvent *e) {
221   if(e->testFlag(EventManager::Netsplit))
222     return;
223
224   IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
225   if(!ircuser)
226     return;
227
228   foreach(const QString &channel, ircuser->channels())
229     displayMsg(e, Message::Quit, e->params().count()? e->params().first() : QString(), e->prefix(), channel);
230 }
231
232 void EventStringifier::processIrcEventTopic(IrcEvent *e) {
233   displayMsg(e, Message::Topic, tr("%1 has changed topic for %2 to: \"%3\"")
234              .arg(e->nick(), e->params().at(0), e->params().at(1)), QString(), e->params().at(0));
235 }
236
237 /* RPL_ISUPPORT */
238 void EventStringifier::processIrcEvent005(IrcEvent *e) {
239   if(!e->params().last().contains(QRegExp("are supported (by|on) this server")))
240     displayMsg(e, Message::Error, tr("Received non-RFC-compliant RPL_ISUPPORT: this can lead to unexpected behavior!"), e->prefix());
241   displayMsg(e, Message::Server, e->params().join(" "), e->prefix());
242 }
243
244 /* RPL_AWAY - "<nick> :<away message>" */
245 void EventStringifier::processIrcEvent301(IrcEvent *e) {
246   QString nick = e->params().at(0);
247   QString awayMsg = e->params().at(1);
248   QString msg, target;
249   bool send = true;
250
251   // FIXME: proper redirection needed
252   if(_whois) {
253     msg = tr("[Whois] ");
254   } else {
255     target = nick;
256     IrcUser *ircuser = e->network()->ircUser(nick);
257     if(ircuser) {
258       int now = QDateTime::currentDateTime().toTime_t();
259       const int silenceTime = 60;
260       if(ircuser->lastAwayMessage() + silenceTime >= now)
261         send = false;
262       ircuser->setLastAwayMessage(now);
263     }
264   }
265   if(send)
266     displayMsg(e, Message::Server, msg + tr("%1 is away: \"%2\"").arg(nick, awayMsg), QString(), target);
267 }
268
269 /* RPL_UNAWAY - ":You are no longer marked as being away" */
270 void EventStringifier::processIrcEvent305(IrcEvent *e) {
271   displayMsg(e, Message::Server, tr("You are no longer marked as being away"));
272 }
273
274 /* RPL_NOWAWAY - ":You have been marked as being away" */
275 void EventStringifier::processIrcEvent306(IrcEvent *e) {
276   if(!e->network()->autoAwayActive())
277     displayMsg(e, Message::Server, tr("You have been marked as being away"));
278 }
279
280 /*
281 WHOIS-Message:
282    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
283   and 301 (RPL_AWAY)
284               "<nick> :<away message>"
285 WHO-Message:
286    Replies 352 and 315 paired are used to answer a WHO message.
287
288 WHOWAS-Message:
289    Replies 314 and 369 are responses to a WHOWAS message.
290
291 */
292
293 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
294 void EventStringifier::processIrcEvent311(IrcEvent *e) {
295   _whois = true;
296
297   const QString whoisUserString = tr("[Whois] %1 is %2 (%3)");
298
299   IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
300   if(ircuser)
301     displayMsg(e, Message::Server, whoisUserString.arg(ircuser->nick(), ircuser->hostmask(), ircuser->realName()));
302   else {
303     QString host = QString("%1!%2@%3").arg(e->params().at(0), e->params().at(1), e->params().at(2));
304     displayMsg(e, Message::Server, whoisUserString.arg(e->params().at(0), host, e->params().last()));
305   }
306 }
307
308 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
309 void EventStringifier::processIrcEvent312(IrcEvent *e) {
310   if(_whois)
311     displayMsg(e, Message::Server, tr("[Whois] %1 is online via %2 (%3)").arg(e->params().at(0), e->params().at(1), e->params().last()));
312   else
313     displayMsg(e, Message::Server, tr("[Whowas] %1 was online via %2 (%3)").arg(e->params().at(0), e->params().at(1), e->params().last()));
314 }
315
316 /*  RPL_WHOWASUSER - "<nick> <user> <host> * :<real name>" */
317 void EventStringifier::processIrcEvent314(IrcEvent *e) {
318   if(!checkParamCount(e, 3))
319     return;
320
321   displayMsg(e, Message::Server, tr("[Whowas] %1 was %2@%3 (%4)").arg(e->params()[0], e->params()[1], e->params()[2], e->params().last()));
322 }
323
324 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
325 void EventStringifier::processIrcEvent315(IrcEvent *e) {
326   QStringList p = e->params();
327   p.takeLast(); // should be "End of WHO list"
328   displayMsg(e, Message::Server, tr("[Who] End of /WHO list for %1").arg(p.join(" ")));
329 }
330
331 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
332    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
333 void EventStringifier::processIrcEvent317(IrcEvent *e) {
334   int idleSecs = e->params()[1].toInt();
335
336   if(e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
337     QDateTime loginTime = QDateTime::fromTime_t(e->params()[2].toInt());
338     displayMsg(e, Message::Server, tr("[Whois] %1 is logged in since %2").arg(e->params()[0], loginTime.toString()));
339   }
340   displayMsg(e, Message::Server, tr("[Whois] %1 is idling for %2 (since %3)")
341              .arg(e->params()[0], secondsToString(idleSecs), e->timestamp().toLocalTime().addSecs(-idleSecs).toString()));
342 }
343
344 /*  RPL_ENDOFWHOIS - "<nick> :End of WHOIS list" */
345 void EventStringifier::processIrcEvent318(IrcEvent *e) {
346   _whois = false;
347   displayMsg(e, Message::Server, tr("[Whois] End of /WHOIS list"));
348 }
349
350 /*  RPL_WHOISCHANNELS - "<nick> :*( ( "@" / "+" ) <channel> " " )" */
351 void EventStringifier::processIrcEvent319(IrcEvent *e) {
352   if(!checkParamCount(e, 2))
353     return;
354
355   QString nick = e->params().first();
356   QStringList op;
357   QStringList voice;
358   QStringList user;
359   foreach(QString channel, e->params().last().split(" ")) {
360     if(channel.startsWith("@"))
361        op.append(channel.remove(0,1));
362     else if(channel.startsWith("+"))
363       voice.append(channel.remove(0,1));
364     else
365       user.append(channel);
366   }
367   if(!user.isEmpty())
368     displayMsg(e, Message::Server, tr("[Whois] %1 is a user on channels: %2").arg(nick, user.join(" ")));
369   if(!voice.isEmpty())
370     displayMsg(e, Message::Server, tr("[Whois] %1 has voice on channels: %2").arg(nick, voice.join(" ")));
371   if(!op.isEmpty())
372     displayMsg(e, Message::Server, tr("[Whois] %1 is an operator on channels: %2").arg(nick, op.join(" ")));
373 }
374
375 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
376 void EventStringifier::processIrcEvent322(IrcEvent *e) {
377   QString channelName;
378   quint32 userCount = 0;
379   QString topic;
380
381   switch(e->params().count()) {
382   case 3:
383     topic = e->params()[2];
384   case 2:
385     userCount = e->params()[1].toUInt();
386   case 1:
387     channelName = e->params()[0];
388   default:
389     break;
390   }
391   displayMsg(e, Message::Server, tr("Channel %1 has %2 users. Topic is: \"%3\"")
392              .arg(channelName).arg(userCount).arg(topic));
393 }
394
395 /* RPL_LISTEND ":End of LIST" */
396 void EventStringifier::processIrcEvent323(IrcEvent *e) {
397   displayMsg(e, Message::Server, tr("End of channel list"));
398 }
399
400 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
401 void EventStringifier::processIrcEvent324(IrcEvent *e) {
402   processIrcEventMode(e);
403 }
404
405 /* RPL_??? - "<channel> <homepage> */
406 void EventStringifier::processIrcEvent328(IrcEvent *e) {
407   if(!checkParamCount(e, 2))
408     return;
409
410   QString channel = e->params()[0];
411   displayMsg(e, Message::Topic, tr("Homepage for %1 is %2").arg(channel, e->params()[1]), QString(), channel);
412 }
413
414 /* RPL_??? - "<channel> <creation time (unix)>" */
415 void EventStringifier::processIrcEvent329(IrcEvent *e) {
416   if(!checkParamCount(e, 2))
417     return;
418
419   QString channel = e->params()[0];
420   uint unixtime = e->params()[1].toUInt();
421   if(!unixtime) {
422     qWarning() << Q_FUNC_INFO << "received invalid timestamp:" << e->params()[1];
423     return;
424   }
425   QDateTime time = QDateTime::fromTime_t(unixtime);
426   displayMsg(e, Message::Topic, tr("Channel %1 created on %2").arg(channel, time.toString()), QString(), channel);
427 }
428
429 /*  RPL_WHOISACCOUNT: "<nick> <account> :is authed as */
430 void EventStringifier::processIrcEvent330(IrcEvent *e) {
431   if(e->params().count() < 3)
432     return;
433
434   displayMsg(e, Message::Server, tr("[Whois] %1 is authed as %2").arg(e->params()[0], e->params()[1]));
435 }
436
437 /* RPL_NOTOPIC */
438 void EventStringifier::processIrcEvent331(IrcEvent *e) {
439   QString channel = e->params().first();
440   displayMsg(e, Message::Topic, tr("No topic is set for %1.").arg(channel), QString(), channel);
441 }
442
443 /* RPL_TOPIC */
444 void EventStringifier::processIrcEvent332(IrcEvent *e) {
445   QString channel = e->params().first();
446   displayMsg(e, Message::Topic, tr("Topic for %1 is \"%2\"").arg(channel, e->params()[1]), QString(), channel);
447 }
448
449 /* Topic set by... */
450 void EventStringifier::processIrcEvent333(IrcEvent *e) {
451   if(!checkParamCount(e, 3))
452     return;
453
454   QString channel = e->params().first();
455   displayMsg(e, Message::Topic, tr("Topic set by %1 on %2")
456              .arg(e->params()[1], QDateTime::fromTime_t(e->params()[2].toInt()).toString()), QString(), channel);
457 }
458
459 /* RPL_INVITING - "<nick> <channel>*/
460 void EventStringifier::processIrcEvent341(IrcEvent *e) {
461   if(!checkParamCount(e, 2))
462     return;
463
464   QString channel = e->params()[1];
465   displayMsg(e, Message::Server, tr("%1 has been invited to %2").arg(e->params().first(), channel), QString(), channel);
466 }
467
468 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
469               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
470 void EventStringifier::processIrcEvent352(IrcEvent *e) {
471   displayMsg(e, Message::Server, tr("[Who] %1").arg(e->params().join(" ")));
472 }
473
474 /*  RPL_ENDOFWHOWAS - "<nick> :End of WHOWAS" */
475 void EventStringifier::processIrcEvent369(IrcEvent *e) {
476   displayMsg(e, Message::Server, tr("End of /WHOWAS"));
477 }
478
479 /* ERR_ERRONEUSNICKNAME */
480 void EventStringifier::processIrcEvent432(IrcEvent *e) {
481   displayMsg(e, Message::Error, tr("Nick %1 contains illegal characters").arg(e->params()[0]));
482 }
483
484 /* ERR_NICKNAMEINUSE */
485 void EventStringifier::processIrcEvent433(IrcEvent *e) {
486   displayMsg(e, Message::Error, tr("Nick already in use: %1").arg(e->params()[0]));
487 }
488
489 /* ERR_UNAVAILRESOURCE */
490 void EventStringifier::processIrcEvent437(IrcEvent *e) {
491   displayMsg(e, Message::Error, tr("Nick/channel is temporarily unavailable: %1").arg(e->params()[0]));
492 }
493
494 // template
495 /*
496
497 void EventStringifier::processIrcEvent(IrcEvent *e) {
498
499 }
500
501 */
502
503 /*******************************/
504 /******** CTCP HANDLING ********/
505 /*******************************/
506
507 void EventStringifier::processCtcpEvent(CtcpEvent *e) {
508   if(e->type() != EventManager::CtcpEvent)
509     return;
510
511   if(e->testFlag(EventManager::Self)) {
512     displayMsg(e, Message::Action, tr("sending CTCP-%1 request to %2").arg(e->ctcpCmd(), e->target()), e->network()->myNick());
513     return;
514   }
515
516   handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
517 }
518
519 void EventStringifier::defaultHandler(const QString &ctcpCmd, CtcpEvent *e) {
520   Q_UNUSED(ctcpCmd);
521   if(e->ctcpType() == CtcpEvent::Query) {
522     QString unknown;
523     if(e->reply().isNull()) // all known core-side handlers (except for ACTION) set a reply!
524       //: Optional "unknown" in "Received unknown CTCP-FOO request by bar"
525       unknown = tr("unknown") + ' ';
526     displayMsg(e, Message::Server, tr("Received %1CTCP-%2 request by %3").arg(unknown, e->ctcpCmd(), e->prefix()));
527     return;
528   }
529   displayMsg(e, Message::Server, tr("Received CTCP-%1 answer from %2: %3").arg(e->ctcpCmd(), nickFromMask(e->prefix()), e->param()));
530 }
531
532 void EventStringifier::handleCtcpAction(CtcpEvent *e) {
533   displayMsg(e, Message::Action, e->param(), e->prefix(), e->target());
534 }
535
536 void EventStringifier::handleCtcpPing(CtcpEvent *e) {
537   if(e->ctcpType() == CtcpEvent::Query)
538     defaultHandler(e->ctcpCmd(), e);
539   else {
540     displayMsg(e, Message::Server, tr("Received CTCP-PING answer from %1 with %2 seconds round trip time")
541                .arg(nickFromMask(e->prefix())).arg(QDateTime::fromTime_t(e->param().toInt()).secsTo(e->timestamp())));
542   }
543 }