예제 #1
0
파일: IrcBot.cpp 프로젝트: banyudu/robot
IrcBot::IrcBot(const QString &server, unsigned int port, const QString &nick, const QString &password, const QStringList &autoJoinChannels): m_server(server), m_port(port), m_nick(nick), m_password(password), m_autoJoinChannels(autoJoinChannels)
{
    m_socket = std::move(unique_ptr<QTcpSocket>(new QTcpSocket()));
    m_socket->abort();
    connect(m_socket.get(), &QTcpSocket::readyRead, this, &IrcBot::onMessageReady);
	connect(m_socket.get(), static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>
			(&QAbstractSocket::error), [this](QAbstractSocket::SocketError) {
				qCritical() << tr("socket error on server [%1] with port [%2]").arg(m_server).arg(m_port)
							<< ", Reason: " << m_socket->errorString();
			});
	connect(m_socket.get(), &QTcpSocket::connected, [this, nick, password] () {
			qDebug() << "Connected!";
			sendMessage("NICK " + nick);
			sendMessage(QString("USER  %1 8 *  : Irc bot").arg(nick));
			if (!password.isEmpty())
				sendMessage(QString("identify %1 %2").arg(nick, password), "nickserv");
			for (auto &channel: m_autoJoinChannels)
			{
                joinChannel(channel);
			}
		});

    // init chat object
    Factory fac;
    unique_ptr<AbstractChatFactory> chatFactory = std::move(fac.makeChatFactory());
    m_chat = std::move(chatFactory->makeChatObject());
}
예제 #2
0
/*!
  Creates a new private conference and invites additional attendees.
  The conference will get a random password.

  JSON Parameters:
  - participants (Array with fingerprints)
*/
bool ConferenceModule::Private::processJsonConferenceCreate(TcpSocketHandler &socket, const TcpProtocol::RequestHeader &header, const QVariant &data)
{
    auto json = data.toMap();
    auto participants = json.value("participants").toList();

    auto server = _pOwner->_serverBase;
    auto selfInfo = socket.getClientInfo();

    // Create invisible channel with random password.
    auto channel = server->createChannel();
    if (!server->joinChannel(selfInfo->id, channel->id)) {
        QVariantMap m;
        m["status"] = 500;
        m["error_message"] = "Can not create channel.";
        return socket.sendJsonResponse(header, m);
    }

    // Invite participants.
    foreach (auto o, participants) {
        auto fingerprint = o.toByteArray();
        auto sock = server->findSocket(fingerprint);
        if (sock) {
            QVariantMap m;
            m["method"] = "/conference/notify/invite";
            m["initiator"] = socket._key.fingerprint();
            m["channel"] = channel->toVariant();
            sock->sendJsonPackage(m);
        }
    }
예제 #3
0
void CIRCService::onAuthSucceeed(void)
{
    CChatServiceBase::onAuthSucceeed();
    vector<wxString>::iterator it = savedChannels.begin();
    while (it != savedChannels.end()){
        joinChannel(*it);
        it++;
    }
}
예제 #4
0
파일: bufferview.cpp 프로젝트: AlD/quassel
void BufferView::init()
{
    header()->setContextMenuPolicy(Qt::ActionsContextMenu);
    hideColumn(1);
    hideColumn(2);
    setIndentation(10);

    // New entries will be expanded automatically when added; no need to call expandAll()

    header()->hide(); // nobody seems to use this anyway

    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // breaks with Qt 4.8
    if (QString("4.8.0") > qVersion()) // FIXME breaks with Qt versions >= 4.10!
        setAnimated(true);

    // FIXME This is to workaround bug #663
    setUniformRowHeights(true);

#ifndef QT_NO_DRAGANDDROP
    setDragEnabled(true);
    setAcceptDrops(true);
    setDropIndicatorShown(true);
#endif

    setSortingEnabled(true);
    sortByColumn(0, Qt::AscendingOrder);

#if defined Q_OS_MACOS || defined Q_OS_WIN
    // afaik this is better on Mac and Windows
    disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
    connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
#else
    disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
    connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
#endif
}
예제 #5
0
void IRC::sendCommand(const std::string &message)
{
	char command[IRC_MESSAGE_SIZE];
	if (message[0]=='/')
	{
		char tempMessage[IRC_MESSAGE_SIZE];
		strncpy(tempMessage, message.c_str(), IRC_MESSAGE_SIZE);
		tempMessage[IRC_MESSAGE_SIZE - 1] = 0;
		char *cmd = strtok(tempMessage, " \t");
		char *arg1 = strtok(NULL, " \t");
		char *arg2 = strtok(NULL, "\0");
		if (verbose)
			printf ("c = [%s] a1 = [%s] a2 = [%s]\n", cmd, arg1, arg2);
		if ((strcasecmp(cmd, "/msg")==0) && arg1 && arg2)
		{
			snprintf(command, IRC_MESSAGE_SIZE, "PRIVMSG %s :%s", arg1, arg2);
			sendString(command);
		}
		else if ((strcasecmp(cmd, "/whois")==0) && arg1)
		{
			snprintf(command, IRC_MESSAGE_SIZE, "WHOIS %s", arg1);
			sendString(command);
		}
		else if ((strcasecmp(cmd, "/join")==0) && arg1)
		{
			joinChannel(arg1);
		}
		else if ((strcasecmp(cmd, "/part")==0) && arg1)
		{
			leaveChannel(arg1);
		}
		else if ((strcasecmp(cmd, "/leave")==0) && arg1)
		{
			leaveChannel(arg1);
		}
	}
	else
	{
		std::string command = "PRIVMSG " + chatChan + " :" + message;
		if (verbose)
			std::cout << "YOG::sendString(" << command << ")." << std::endl;
		sendString(command);
	}
}
예제 #6
0
ChannelListDlg::ChannelListDlg(QWidget *parent)
    : QDialog(parent),
    _listFinished(true),
    _ircListModel(this),
    _sortFilter(this),
    _simpleModeSpacer(0),
    _advancedMode(false)
{
    _sortFilter.setSourceModel(&_ircListModel);
    _sortFilter.setFilterCaseSensitivity(Qt::CaseInsensitive);
    _sortFilter.setFilterKeyColumn(-1);

    ui.setupUi(this);
    ui.advancedModeLabel->setPixmap(QIcon::fromTheme("edit-rename").pixmap(22));

    ui.channelListView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.channelListView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.channelListView->setAlternatingRowColors(true);
    ui.channelListView->setTabKeyNavigation(false);
    ui.channelListView->setModel(&_sortFilter);
    ui.channelListView->setSortingEnabled(true);
    ui.channelListView->verticalHeader()->hide();
    ui.channelListView->horizontalHeader()->setStretchLastSection(true);

    ui.searchChannelsButton->setAutoDefault(false);

    setWindowIcon(QIcon::fromTheme("format-list-unordered"));

    connect(ui.advancedModeLabel, SIGNAL(clicked()), this, SLOT(toggleMode()));
    connect(ui.searchChannelsButton, SIGNAL(clicked()), this, SLOT(requestSearch()));
    connect(ui.channelNameLineEdit, SIGNAL(returnPressed()), this, SLOT(requestSearch()));
    connect(ui.filterLineEdit, SIGNAL(textChanged(QString)), &_sortFilter, SLOT(setFilterFixedString(QString)));
    connect(Client::ircListHelper(), SIGNAL(channelListReceived(const NetworkId &, const QStringList &, QList<IrcListHelper::ChannelDescription> )),
        this, SLOT(receiveChannelList(NetworkId, QStringList, QList<IrcListHelper::ChannelDescription> )));
    connect(Client::ircListHelper(), SIGNAL(finishedListReported(const NetworkId &)), this, SLOT(reportFinishedList()));
    connect(Client::ircListHelper(), SIGNAL(errorReported(const QString &)), this, SLOT(showError(const QString &)));
    connect(ui.channelListView, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));

    setAdvancedMode(false);
    enableQuery(true);
    showFilterLine(false);
    showErrors(false);
}
void FLogTextBrowser::contextMenuEvent(QContextMenuEvent *event)
{
	flist_copylink = anchorAt(event->pos());
	QTextCursor cursor = textCursor();
	QMenu *menu = new QMenu;
	QAction *action;
	if(flist_copylink.isEmpty()) {
		//Plain text selected
	} else if(flist_copylink.startsWith("https://www.f-list.net/c/")) {
		flist_copyname = flist_copylink.mid(QString("https://www.f-list.net/c/").length());
		if(flist_copyname.endsWith("/")) {
			flist_copyname = flist_copyname.left(flist_copyname.length() - 1);
		}
		menu->addAction(QString("Open Profile"), this, SLOT(openProfile()));
		//todo: Get the list of available sessions. Create a submenu with all available characters if there is more than one (or this session isn't vlaid).
		menu->addAction(QString("Open PM"), this, SLOT(openPrivateMessage()));
		menu->addAction(QString("Copy Profile Link"), this, SLOT(copyLink()));
		menu->addAction(QString("Copy Name"), this, SLOT(copyName()));
		menu->addSeparator();
	} else if(flist_copylink.startsWith("#AHI-")) {
		flist_copyname = flist_copylink.mid(5);
		//todo: Get the list of available sessions. Create a submenu with all available characters if there is more than one (or this session isn't vlaid).
		menu->addAction(QString("Join Channel"), this, SLOT(joinChannel()));
		//todo: Maybe get the name the plain text of the link and make that available for copying?
		menu->addAction(QString("Copy Channel ID"), this, SLOT(copyName()));
		menu->addSeparator();
	} else if(flist_copylink.startsWith("#CSA-")) {
		flist_copyname = flist_copylink.mid(5);
		//todo: If possible, get which session this actually came from and use that.
		menu->addAction(QString("Confirm Staff Report"), this, SLOT(confirmReport()));
		menu->addAction(QString("Copy Call ID"), this, SLOT(copyName()));
		menu->addSeparator();
	} else {
		menu->addAction(QString("Copy Link"), this, SLOT(copyLink()));
		menu->addSeparator();
	}
	action = menu->addAction(QString("Copy Selection"), this, SLOT(copy()));
	action->setEnabled(cursor.hasSelection());
	menu->addAction(QString("Select All"), this, SLOT(selectAll()));

	menu->exec(event->globalPos());
	delete menu;
}
// Overloading () operator. The function takes in an EXPRESSION
//   as parameter and then calls the function associated with the
//   COMMAND specified by the EXPRESSION. The function returns
//   the output of calling those functions, which usually is an informative
//   message about the status of performing the specific action.
//   Expressions are strings, and need to be parsed in order to retrieve
//   the COMMAND to be excuted. Essentially a functor
std::string IRCCommandHandler::operator()(std::string exp) {
  expression = exp;

  parse();    //  Parsing function that gets the command from the EXPRESSION
  FILE_LOG(logDEBUG) << "Command = " << command;
  FILE_LOG(logDEBUG) << "Attempting to run COMMAND...";

  std::string result;
  // Calling functions associated with an EXPRESSION's COMMAND
  if      (command == "MSG")           result = message();
  else if (command == "CONNECT")       result = connect();
  else if (command == "CONNECT")       result = disconnect();
  else if (command == "CREATECHANNEL") result = createChannel();
  else if (command == "GETCHANNELS")   result = getChannels();
  else if (command == "JOINCHANNEL")   result = joinChannel();
  else if (command == "PING")          result = ping();
  else if (command == "CHANGENAME")    result = changeName();
  else result = "Invalid IRC Command '" + command + "'";

  return result;
}
예제 #9
0
void BotIrcDiceParser::setRegisterName()
{
    m_socket->write(QLatin1String("msg NickServ identify  \r\n").data());
    joinChannel();
}
예제 #10
0
void IRCServer::ProcessLine(QString line, QString channel) {

    QStringList validCommands;
    QRegExp linematch;
    QRegExp actionmatch;

    linematch.setPattern("^(:?([A-Za-z0-9_\\-\\\\\\[\\]{}^`|.]+)?!?(\\S+)? )?([A-Z0-9]+) ?([A-Za-z0-9_\\-\\\\\\[\\]{}^`|.*#]+)?( [@=] ([#&][^\\x07\\x2C\\s]{0,200}))?([ :]+)?([\\S ]+)?$");
    
    validCommands << "353" << "376" << "JOIN" << "KICK" << "MODE";
    validCommands << "NICK" << "NOTICE" << "PART" << "PING" << "PRIVMSG";
    validCommands  << "QUIT" << "TOPIC" << "372" << "432" << "433";
    validCommands  << "332";
    
    actionmatch.setPattern("\\001ACTION(.+)\\001");

    linematch.isMinimal();
    actionmatch.isMinimal();

    int pos = linematch.indexIn(line);

    if (pos > -1) {

        writeToLog("[RCV] " + line);

        QStringList list;
        QStringList splitted;
        
        QString sender = linematch.cap(2);
        QString userhost = linematch.cap(3);
        QString command = linematch.cap(4);
        QString receiver = linematch.cap(5);
        QString destination = linematch.cap(7);
        QString content = linematch.cap(9);

        QString response;
        QString username;
        QString reason;
        QString channel;
        QString topic;

        switch (validCommands.indexOf(command)) {
            case 0:
                // 353 (Names)
                if (delist == true) users.clear();
                list = content.split(" ");

                for (int i = 0; i < list.count(); i++) {
                    users.append(list.at(i));
                }

                if (list.count() < 53) delist = true;
                else delist = false;

                updateUserModel();
                break;
            case 1:
                // 376 (End of MOTD)
                joinChannel();
                break;
            case 2:
                // JOIN
                response = GUIUtil::HtmlEscape("Join: " + sender + " (" + userhost + ")");
                addUser(sender);
                writeToUI(response, receiver);
                break;
            case 3:
                // KICK
                splitted = content.split(" :");
                username = splitted.at(0);
                reason = splitted.at(1);

                removeUser(username);

                response = GUIUtil::HtmlEscape(sender + " kicked " + username + ". Reason: " + reason);
                writeToUI(response, receiver);
                break;
            case 4:
                // MODE
                response = GUIUtil::HtmlEscape(sender + " sets mode: " + content);
                if (receiver.startsWith("#")) {
                    updateUsersList(receiver);
                    writeToUI(response, receiver);
                } else {
                    writeToUI(response);
                }
                break;
            case 5:
                // NICK
                response = GUIUtil::HtmlEscape(sender + " is now known as `" + content);
                removeUser(sender);
                addUser(content);
                writeToUI(response);
                break;
            case 6:
                // NOTICE
                writeToUI(GUIUtil::HtmlEscape(content));
                break;
            case 7:
                // PART
                response = GUIUtil::HtmlEscape("Parts: " + sender + " (" + userhost + ")");
                removeUser(sender);
                writeToUI(response, receiver);
                break;
            case 8:
                // PING
                response = "PONG " + content;
                sendData(response);
                break;
            case 9:
                // PRIVMSG
                int posact;
                posact = actionmatch.indexIn(content);
                if (posact > -1) {
                    QString actionmsg = actionmatch.cap(1);
                    response = GUIUtil::HtmlEscape(sender + " " + actionmsg.trimmed());
                } else {
                    if (receiver == nickname) {
                        response = GUIUtil::HtmlEscape(sender + " -> you: " + content);
                    } else {
                        response = GUIUtil::HtmlEscape("<" + sender + "> " + content);
                    }
                }                
                if (receiver.startsWith("#") || receiver == nickname) {
                    writeToUI(response, receiver);
                } else {            
                    writeToUI(response);
                }
                break;
            case 10:
                // QUIT
                response = GUIUtil::HtmlEscape("Quit: " + sender + " (" + userhost + ")");
                removeUser(sender);
                writeToUI(response);
                break;
            case 11:
                // TOPIC
                response = GUIUtil::HtmlEscape(sender + " changes topic to '" + content + "'");
                writeToUI(response, receiver);
                break;
            case 12:
                // 372 (MOTD)
                writeToUI(GUIUtil::HtmlEscape(content));
                break;
            case 13:
                // 432 (Invalid nickname)
                response = "ERROR: " + content;
                writeToUI(GUIUtil::HtmlEscape(response));
                break;
            case 14:
                // 433 (Nick already in use)
                response = "Nickname is already in use, please choose another. Type /nick YOURNEWNAME";
                writeToUI(GUIUtil::HtmlEscape(response));
                break;  
            case 15:
                // 332 (Topic on join)
                splitted = content.split(" :");
                channel = splitted.at(0);
                topic = splitted.at(1);
                
                response = GUIUtil::HtmlEscape("Topic for " + channel + " is '" + topic + "'");
                writeToUI(response, channel);
                break;
            default:
                // Do nothing
                break;
        }

    } else {
        writeToLog("[ERR] " + line);
    }
}
예제 #11
0
void parseMessage(char *line, clientNode *thisClient) {
    char *message[256];
    char *lineCopy = malloc(sizeof(char) * (strlen(line) + 1));
    char replie[256];
    char dia[3], mes[4], nMes[3], ano[5];
    int sendReplie = 1;
    int temp;

    //Quebra a linha em palavras
    strcpy(lineCopy, line);
    getStringArray(lineCopy, message, " ");

    replie[0] = '\0';
    for(int i = 0; message[0][i]; i++)
        message[0][i] = toupper(message[0][i]);
    if(strcmp(message[0], "NICK") == 0) {
        if(message[1] == NULL)
            sprintf(replie, ":%s %d * :Nickname não foi passado!\n", SERVER_NAME, ERR_NONICKNAMEGIVEN);

        pthread_mutex_lock(&clientMutex);
        if(clientWithNick(message[1], thisClient->head) != NULL)
            sprintf(replie, ":%s %d * %s :Nickname já está sendo usado!\n", SERVER_NAME, ERR_NICKNAMEINUSE, message[1]);
        else {
            strcpy(thisClient->nick, message[1]);
            sendReplie = 0;
        }

        pthread_mutex_unlock(&clientMutex);
    } else if(strcmp(message[0], "LIST") == 0) {
        listChannels(thisClient->socket);
        sendReplie = 0;
    } else if(strcmp(message[0], "JOIN") == 0) {
        if(message[1] == NULL)
            sprintf(replie, ":%s %d * JOIN :Parâmetros insuficientes!\n", SERVER_NAME, ERR_NEEDMOREPARAMS);
        else if(thisClient->nick[0] == '\0')
            sprintf(replie, ":%s %d * :Você não registrou seu NICK!\n", SERVER_NAME, ERR_NOTREGISTERED);
        else {
            sprintf(replie, ":%s JOIN %s\n", thisClient->nick, message[1]);
            printf("[Cliente %d entrou no canal %s]\n", thisClient->socket, message[1]);
            joinChannel(message[1], thisClient);
        }
    } else if(strcmp(message[0], "PRIVMSG") == 0) {
        if(thisClient->nick[0] == '\0')
            sprintf(replie, ":%s %d * :Você não registrou seu NICK!\n", SERVER_NAME, ERR_NOTREGISTERED);
        else {
            if(message[1][0] == '#')
                broadcastMessage(line, thisClient->nick, message[1]);
            else
                sendMessage(line, thisClient, message[1]);
            sendReplie = 0;
        }
    } else if(strcmp(message[0], "PART") == 0) {
        sprintf(replie, ":%s PART %s\n", thisClient->nick, message[1]);
        printf("[Cliente %d saiu do canal %s]\n", thisClient->socket, message[1]);
        delRef(thisClient->socket, message[1]);
    } else if(strcmp(message[0], "QUIT") == 0) {
        sprintf(replie, ":%s QUIT\n", thisClient->nick);
        close(thisClient->socket);
    } else if(strcmp(message[0], "MACDATA") == 0) {
        strncat(dia, __DATE__ +4, 2);
        strncat(mes, __DATE__, 3);
        strncat(ano, __DATE__ +7, 4);

        if(strcmp(mes, "Jan") == 0)
            strncpy(nMes, "01", 2);
        else if(strcmp(mes, "Feb") == 0)
            strncpy(nMes, "02", 2);
        else if(strcmp(mes, "Mar") == 0)
            strncpy(nMes, "03", 2);
        else if(strcmp(mes, "Apr") == 0)
            strncpy(nMes, "04", 2);
        else if(strcmp(mes, "May") == 0)
            strncpy(nMes, "05", 2);
        else if(strcmp(mes, "Jun") == 0)
            strncpy(nMes, "06", 2);
        else if(strcmp(mes, "Jul") == 0)
            strncpy(nMes, "07", 2);
        else if(strcmp(mes, "Aug") == 0)
            strncpy(nMes, "08", 2);
        else if(strcmp(mes, "Sep") == 0)
            strncpy(nMes, "09", 2);
        else if(strcmp(mes, "Oct") == 0)
            strncpy(nMes, "10", 2);
        else if(strcmp(mes, "Nov") == 0)
            strncpy(nMes, "11", 2);
        else
            strncpy(nMes, "12", 2);

        sprintf(replie, "%s/%s/%s\n", dia, nMes, ano);
    } else if(strcmp(message[0], "MACHORA") == 0) {
        sprintf(replie, "%s\n", __TIME__);
    } else if(strcmp(message[0], "MACTEMPERATURA") == 0) {
        temp = getTemp();

        sprintf(replie, "Temperatura atual: %dºC\nObitido de http://developers.agenciaideias.com.br/tempo/xml/saopaulo-sp\n", temp);
    }
   
    if(sendReplie) {
        if(replie[0] == '\0') {
            sprintf(replie, "%s\n", line);
        }

        printf("[Resposta para cliente %d] %s", thisClient->socket, replie);
        write(thisClient->socket, replie, strlen(replie));
    }

    replie[0] = '\0';
    free(lineCopy);
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    readSettings();
    ui->actionSound->setChecked(settings.soundsenabled);

    irc = new QIrc();
    if (!irc->createSession())
    {
        QMessageBox::critical(this, tr("Error"), tr("Can't create session"));
        close();
        return;
    }
    connect(irc, SIGNAL(sigConnected()), this, SLOT(sltConnected()));
    connect(irc, SIGNAL(sigMessage(QString,QString)), this, SLOT(sltMessage(QString,QString)));
    connect(irc, SIGNAL(sigChannelJoined(QString,QString)), this, SLOT(sltChannelJoined(QString,QString)));
    connect(irc, SIGNAL(sigChannelParted(QString,QString,QString)), this, SLOT(sltChannelParted(QString,QString,QString)));
    connect(irc, SIGNAL(sigChannelNames(QString,QString,QStringList)), this, SLOT(sltChannelNames(QString,QString,QStringList)));
    connect(irc, SIGNAL(sigChannelMessage(QString,QString,QString)), this, SLOT(sltChannelMessage(QString,QString,QString)));
    connect(irc, SIGNAL(sigPrivateMessage(QString,QString,QString)), this, SLOT(sltPrivateMessage(QString,QString,QString)));
    connect(irc, SIGNAL(sigNick(QString,QString)), this, SLOT(sltNick(QString,QString)));
    connect(irc, SIGNAL(sigNotice(QString,QString,QString)), this, SLOT(sltNotice(QString,QString,QString)));
    connect(irc, SIGNAL(sigTopic(QString,QString,QString)), this, SLOT(sltTopic(QString,QString,QString)));
    connect(irc, SIGNAL(sigTopicSet(QString,QString,QString,QString)), this, SLOT(sltTopicSet(QString,QString,QString,QString)));
    connect(irc, SIGNAL(sigKick(QString,QString,QString)), this, SLOT(sltKick(QString,QString,QString)));
    connect(irc, SIGNAL(sigQuit(QString,QString)), this, SLOT(sltQuit(QString,QString)));
    connect(irc, SIGNAL(sigChannelModeChanged(QString,QString,QStringList)), this, SLOT(sltChannelModeChanged(QString,QString,QStringList)));
    connect(irc, SIGNAL(sigUmode(QString,QString)), this, SLOT(sltUmode(QString,QString)));
    connect(irc, SIGNAL(sigInvite(QString,QString,QString)), this, SLOT(sltInvite(QString,QString,QString)));
    connect(irc, SIGNAL(sigCtcpAction(QString,QString,QString)), this, SLOT(sltCtcpAction(QString,QString,QString)));
    connect(irc, SIGNAL(sigErrorOccured(QString)), this, SLOT(sltErrorOccured(QString)));

    consolebrowser = new QTextEdit();
    consolebrowser->setReadOnly(true);
    QFont consolefont;
    if (consolefont.fromString(settings.consolefont))
        consolebrowser->setFont(consolefont);

    if (!settings.hideconsole)
        consoleindex =ui->tabWidget->insertTab(0, consolebrowser, tr("Console"));

    setsdlg = 0;

    usercontextmenu = new QMenu(this);
    usercontextmenu->addAction(ui->actionPrivateChat);
    usercontextmenu->addAction(ui->actionInsert_to_editor);
    QMenu *managementmenu = usercontextmenu->addMenu(tr("Management"));
    managementmenu->addAction(ui->actionKick);
    managementmenu->addAction(ui->actionBan);
    managementmenu->addAction(ui->actionKickBan);
    managementmenu->addSeparator();
    managementmenu->addAction(ui->actionOp);
    managementmenu->addAction(ui->actionDeOp);
    managementmenu->addSeparator();
    managementmenu->addAction(ui->actionVoice);
    managementmenu->addAction(ui->actiondeVoice);
    connect(ui->treeWidget, SIGNAL(userContextMenu(QPoint)), this, SLOT(userContextMenuRequested(QPoint)));

    channelcontextmenu = new QMenu(this);
    channelcontextmenu->addAction(ui->actionLeave_channel);
    channelcontextmenu->addAction(ui->actionChannel_settings);
    connect(ui->treeWidget, SIGNAL(channelContextMenu(QPoint)), this, SLOT(channelContextMenuRequested(QPoint)));

    channelsettingsdialog = 0;
    trayicon = 0;
    traymenu = 0;
    setTrayIcon(settings.trayicon);
    connect(ui->actionChannel_settings, SIGNAL(triggered()), this, SLOT(channelSettingsPressed()));

    //smile menu
    smilemenu = new QMenu(this);
    smilewidgetaction = new QWidgetAction(smilemenu);
    smilebar = new SmileBar();
    smilewidgetaction->setDefaultWidget(smilebar);
    smilemenu->addAction(smilewidgetaction);
    connect(smilebar, SIGNAL(smileClicked(QString)), ui->plainTextEditMessage, SLOT(insertPlainText(QString)));
    connect(smilebar, SIGNAL(smileClicked(QString)), ui->plainTextEditMessage, SLOT(setFocus()));
    ui->actionEmoticons->setMenu(smilemenu);
    smilebutton = new QToolButton();
    smilebutton->setDefaultAction(ui->actionEmoticons);
    smilebutton->setPopupMode(QToolButton::InstantPopup);
    ui->mainToolBar->addWidget(smilebutton);

    channellistdialog = new ChannelListDialog();
    connect(irc, SIGNAL(sigChannelListStart()), channellistdialog, SLOT(showAndClear()));
    connect(irc, SIGNAL(sigChannelListAddItem(QString,QString,QString)), channellistdialog,
            SLOT(addListItem(QString,QString,QString)));
    connect(irc, SIGNAL(sigChannelListEnd()), channellistdialog, SLOT(endOfList()));
    connect(channellistdialog, SIGNAL(channelDoubleClicked(QString)), irc, SLOT(joinChannel(QString)));

    connect(ui->pushButtonSend, SIGNAL(clicked()), ui->plainTextEditMessage, SIGNAL(sendKeyPressed()));
    connect(ui->plainTextEditMessage, SIGNAL(sendKeyPressed()), this, SLOT(sendPressed()));
    connect(ui->actionConnect, SIGNAL(triggered()), this, SLOT(connectPressed()));
    connect(ui->actionDisconnect, SIGNAL(triggered()), this, SLOT(disconnectPressed()));
    connect(ui->actionSettings, SIGNAL(triggered()), this, SLOT(settingsPressed()));
    connect(ui->actionJoin, SIGNAL(triggered()), this, SLOT(joinPressed()));
    connect(ui->treeWidget, SIGNAL(userDoubleClicked(QString)), this, SLOT(userDoubleClicked(QString)));
    connect(ui->actionPrivateChat, SIGNAL(triggered()), this, SLOT(privateChatPressed()));
    connect(ui->actionLeave_channel, SIGNAL(triggered()), this, SLOT(leaveChannelPressed()));
    connect(ui->actionKick, SIGNAL(triggered()), this, SLOT(kickPressed()));
    connect(ui->actionBan, SIGNAL(triggered()), this, SLOT(BanPressed()));
    connect(ui->actionKickBan, SIGNAL(triggered()), this, SLOT(kickBanPressed()));
    connect(ui->actionOp, SIGNAL(triggered()), this, SLOT(opPressed()));
    connect(ui->actionDeOp, SIGNAL(triggered()), this, SLOT(deOpPressed()));
    connect(ui->actionVoice, SIGNAL(triggered()), this, SLOT(voicePressed()));
    connect(ui->actiondeVoice, SIGNAL(triggered()), this, SLOT(devoicePressed()));
    connect(ui->pushButtonNick, SIGNAL(clicked()), this, SLOT(nickButtonPressed()));
    connect(ui->actionList_of_channels, SIGNAL(triggered()), irc, SLOT(getChannelsList()));
    connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int)));
    connect(ui->actionInsert_to_editor, SIGNAL(triggered()), this, SLOT(insertUserToEditorPressed()));
    connect(ui->actionShowHide, SIGNAL(triggered()), this, SLOT(trayIconActivated()));
    connect(ui->actionQuit_program, SIGNAL(triggered()), this, SLOT(quitProgram()));
    connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(aboutPressed()));
    connect(ui->actionSound, SIGNAL(toggled(bool)), this, SLOT(soundActionToogled(bool)));
}
예제 #13
0
void IRC::interpreteIRCMessage(const std::string &message)
{
	char tempMessage[IRC_MESSAGE_SIZE];
	char *prefix;
	char *cmd;
	char *source;

	strncpy(tempMessage, message.c_str(), IRC_MESSAGE_SIZE);
	tempMessage[IRC_MESSAGE_SIZE - 1] = 0;

	// get informations about packet, homemade parser
	if (tempMessage[0]==':')
	{
		int i=1;
		while ((tempMessage[i]!=' ') && (tempMessage[i]!='!') && (tempMessage[i]!=0))
			i++;
		if (tempMessage[i]=='!')
		{
			tempMessage[i]=0;
			source=tempMessage+1;
			prefix=strtok(&tempMessage[i+1], " ");
			cmd=strtok(NULL, " ");
		}
		else if (tempMessage[i]==' ')
		{
			tempMessage[i]=0;
			source=tempMessage+1;
			cmd=strtok(&tempMessage[i+1], " ");
			prefix=NULL;
		}
		else
		{
			source=NULL;
			prefix=NULL;
			cmd=NULL;
			return;
		}
	}
	else
	{
		source=NULL;
		prefix=NULL;
		cmd=strtok(tempMessage, " ");
	}

	// this is a debug printf to reverse engineer IRC protocol
	if (verbose)
		printf("IRC command is : [%s] Source is [%s] Prefix is [%s]\n", cmd, source, prefix);
	if (strcasecmp(cmd, "PING")==0)
	{
		char *argument=strtok(NULL, " \0");
		if (verbose)
			printf("IRC got PING, responding PONG with argument [%s]\n", argument);
		std::string answer("PONG ");
		answer += argument;
		sendString(answer.c_str());
	}
	if (strcasecmp(cmd, "PRIVMSG")==0)
	{
		char *diffusion=strtok(NULL, " :");
		char *message=strtok(NULL, "\0");
		
		// normal chat message
		ChatMessage msg;
		
		if (strstr(source, "[YOG]")==0)
		{
			if (message && (*(++message)))
			{
				msg.source = source;
				msg.diffusion = diffusion;
				msg.message = message;	
				messages.push_back(msg);
			}
		}
	}
	else if (strcasecmp(cmd, "JOIN")==0)
	{
		char *diffusion=strtok(NULL, " :\0");
		InfoMessage msg(IRC_MSG_JOIN);
		
		msg.source = source;
		msg.diffusion = diffusion;

		infoMessages.push_back(msg);
		
		usersOnChannels[std::string(diffusion)].insert(std::string(source));
		usersOnChannelsModified = true;
	}
	else if (strcasecmp(cmd, "PART")==0)
	{
		char *diffusion=strtok(NULL, " :");
		char *message = strtok(NULL, "\0");
		InfoMessage msg(IRC_MSG_PART);

		msg.source = source;
		msg.diffusion = diffusion;
		
		if (message && (*(++message)))
		{
			msg.message = message;
		}

		infoMessages.push_back(msg);
		
		// if we leave the chan, erase all list
		if (source == nick)
			usersOnChannels[std::string(diffusion)].clear();
		else
			usersOnChannels[std::string(diffusion)].erase(std::string(source));
		usersOnChannelsModified = true;
	}
	else if (strcasecmp(cmd, "QUIT")==0)
	{
		char *message = strtok(NULL, "\0");
		InfoMessage msg(IRC_MSG_QUIT);

		msg.source = source;
		if (message && (*(++message)))
		{
			msg.message = message;
		}
		
		// erase this nick from all chans
		std::string user(source);
		for (std::map<std::string, std::set<std::string> >::iterator it = usersOnChannels.begin(); it!=usersOnChannels.end(); ++it)
		{
			if (it->second.find(user) != it->second.end())
			{
				it->second.erase(user);
				usersOnChannelsModified = true;
			}
		}

		infoMessages.push_back(msg);
	}
	else if (strcasecmp(cmd, "NOTICE")==0)
	{
		char *diffusion = strtok(NULL, " :");
		char *message = strtok(NULL, "\0");
	
		if ((diffusion != NULL) && (message != NULL))
		{
			InfoMessage msg(IRC_MSG_NOTICE);
			
			if (source)
			{
				msg.source = source;
				msg.diffusion = diffusion;
				msg.message = message;
				infoMessages.push_back(msg);
			}
		}
	}
	else if (strcasecmp(cmd, "353")==0)
	{
		// strtok is used here for its side effects
		strtok(NULL, " =");
		strtok(NULL, " =");
		char *chan = strtok(NULL, " :=");
		char *user;
		while ((user = strtok(NULL, " :")) != NULL)
		{
			usersOnChannels[std::string(chan)].insert(std::string(user));
			usersOnChannelsModified = true;
		}
	}

	else if (strcasecmp(cmd, "433")==0)
	{
		if (nick.size() < IRC_NICK_SIZE)
		{
			nick += "_";
			sendString("NICK " + nick);
			joinChannel("#glob2");
		}
		
		else
		{
			const std::string &nicktaken = Toolkit::getStringTable()->getString("[nick taken]");
			const std::string &ok = Toolkit::getStringTable()->getString("[ok]");
			int res = (int)MessageBox(globalContainer->gfx, "standard", MB_ONEBUTTON, nicktaken.c_str(), ok.c_str());
		
			if (res != 0 )
			{
				assert(false);
			}
		}
	}
}