Преглед изворни кода

Server line parsing fixed. Added hello msg. Added mute unmute commands.
Broadcasting message taken out.

Mihawk пре 12 година
родитељ
комит
f3eb032503
6 измењених фајлова са 139 додато и 118 уклоњено
  1. 5 2
      ActiveClient.cpp
  2. 27 75
      App.cpp
  3. 1 4
      App.h
  4. 86 33
      Client.cpp
  5. 14 4
      Client.h
  6. 6 0
      ServerQuery.cpp

+ 5 - 2
ActiveClient.cpp

@@ -28,7 +28,7 @@ along with this program.  If not, see < http://www.gnu.org/licenses/ >.
 ActiveClient::ActiveClient(App *app, QObject *parent):
   QObject(parent),
   myApp(app),
-  myClient(new Client(app)),
+  myClient(new Client(app, this)),
   myQuery(new ServerQuery(this)),
   myDisconnectTime(new QTime()),
   myBroadcastReplyTimer(new QTimer(this)),
@@ -75,7 +75,10 @@ void ActiveClient::queryError(ServerQuery::Error)
 
 void ActiveClient::queryFinished()
 {
-  int playerCount = myQuery->playerList().size();
+
+  PlayerList playerList = myQuery->playerList();
+  int playerCount = playerList.size();
+  myClient->setPlayerList(playerList);
 
   myQueryTimer->start(myQueryInterval);
 

+ 27 - 75
App.cpp

@@ -64,23 +64,10 @@ void App::onNewConnection()
   connect(mySocket, SIGNAL(disconnected()), SLOT(onDisconnection()));
 
   print("Connected to CIMS's bot service.\n");
-
-  /* Set socket on clients for echoing */
-  ActiveClient* ac;
-  foreach(ac, myClients)
-	{
-    ac->client()->setSocket(mySocket);
-	}
 }
 
 void App::onDisconnection()
 {
-	/* set all sockets to null so it doenst echo anything on a dangling pointer */
-  ActiveClient* ac;
-  foreach(ac, myClients)
-	{
-    ac->client()->setSocket(NULL);
-	}
 	mySocketConnectedFlag = false;
 	mySocket->deleteLater();
 }
@@ -207,13 +194,7 @@ void App::onDataArrival()
 
 		if(cmd == "say")
 		{
-			say(args);
-			return;
-		}
-
-		if(cmd == "say_team")
-		{
-			sayTeam(args);
+      broadcast(args);
 			return;
 		}
 
@@ -266,7 +247,6 @@ void App::help()
 	print("connect server:port -> connects the bot on a server\n");
 	print("disconnect server:port -> removes the bot from a server\n");
 	print("say message -> says the message on all servers where the bot is connected\n");
-	print("say_team message -> says the message on all servers where the bot is connected\n");
 	print("servers -> lists all servers the bot is connected\n");
 	print("name nick -> changes the bot name to nick\n");
 	print("color x x -> changes the player color\n");
@@ -355,14 +335,7 @@ void App::addClient(const QString &host, quint16 port)
 		}
 	}
 
-  ac = new ActiveClient(this);
-  if(mySocketConnectedFlag)
-	{
-		if(mySocket->state() == QTcpSocket::ConnectedState)
-		{
-      ac->client()->setSocket(mySocket);
-		}
-	}
+  ac = new ActiveClient(this, this);
   ac->setAddress(ha, port);
   ac->client()->setQuakeFolder(Settings::globalInstance()->quakeFolder().toAscii().data());
   ac->client()->setName(Settings::globalInstance()->botName().toAscii().data());
@@ -398,49 +371,6 @@ void App::removeClient(const QString &host, quint16 port)
 	print("Client not found on the list.\n");
 }
 
-void App::say(const QString &msg, int *serverCount, int *userCount)
-{
-  ActiveClient* ac;
-
-  *serverCount = 0;
-  *userCount = 0;
-
-  foreach(ac, myClients)
-	{
-    if(ac->client()->state() == Client::ConnectedState)
-    {
-      ac->client()->say(msg);
-      *userCount += ac->playerCount() - 1;
-      (*serverCount)++;
-    }
-	}
-	print("Say command sent to all clients\n");
-}
-
-void App::say(const QString &msg)
-{
-  ActiveClient* ac;
-
-  foreach(ac, myClients)
-  {
-    if(ac->client()->state() == Client::ConnectedState)
-    {
-      ac->client()->say(msg);
-    }
-  }
-  print("Say command sent to all clients\n");
-}
-
-void App::sayTeam(const QString &msg)
-{
-  ActiveClient* ac;
-  foreach(ac, myClients)
-	{
-    ac->client()->sayTeam(msg);
-	}
-	print("Say_team command sent to all clients\n");
-}
-
 void App::listClients()
 {
   ActiveClient* ac;
@@ -488,14 +418,36 @@ void App::requestBroadcast(const QString &type, const QString &user, const QStri
   myQWNETSshClient->write("REQ_BC QDEV,-" + type + "-,qw://" + server + ",'" + user + "','" + message + "'\n");
 }
 
-void App::broadcast(const QString &msg)
+void App::broadcast(const QString &msg, ActiveClient* ignoredClient)
 {
-  say(msg);
+  ActiveClient* ac;
+
+  foreach(ac, myClients)
+  {
+    if(ac == ignoredClient)
+      continue;
+
+    if(ac->client()->state() == Client::ConnectedState && !ac->client()->isMuted())
+      ac->client()->say(msg);
+  }
 }
 
 void App::broadcast(const QString &msg, int *serverCount, int *userCount)
 {
-  say(msg, serverCount, userCount);
+  ActiveClient* ac;
+
+  *serverCount = 0;
+  *userCount = 0;
+
+  foreach(ac, myClients)
+  {
+    if(ac->client()->state() == Client::ConnectedState && !ac->client()->isMuted())
+    {
+      ac->client()->say(msg);
+      *userCount += ac->playerCount() - 1;
+      (*serverCount)++;
+    }
+  }
 }
 
 void App::cleanup()

+ 1 - 4
App.h

@@ -21,7 +21,7 @@ public:
 
   void									print(const QString& msg);
   void									broadcast(const QString& msg, int *serverCount, int *userCount);
-  void                  broadcast(const QString& msg);
+  void                  broadcast(const QString& msg, ActiveClient* ignoredClient = 0);
   void                  requestBroadcast(const QString& type, const QString& user, const QString& server, const QString& message);
   void                  setReplyHash(const QString& serverAddress, const QString& hash);
   void                  incrementReplyCounters(const QString& hash, int userCount, int channelCount, int playerCount, int serverCount);
@@ -51,9 +51,6 @@ private:
 	void									removeClient(const QString& host, quint16 port);
   void									parseAddClientCommand(const QString& args);
   void									parseRemoveClientCommand(const QString& args);
-  void                  say(const QString& msg, int *serverCount, int *userCount);
-  void                  say(const QString& msg);
-	void									sayTeam(const QString& msg);
 	void									setTeam(const QString& team);
 	void									listClients();
 	void									setColor(const QString& args);

+ 86 - 33
Client.cpp

@@ -4,28 +4,29 @@
 #include <QTcpSocket>
 #include <QStringList>
 #include <QTime>
+#include <QTimer>
 #include "App.h"
 #include "Settings.h"
 
-Client::Client(App *app):
+Client::Client(App *app, ActiveClient* ac):
   QWClient(),
+  myActiveClient(ac),
   myApp(app),
-  mySocket(NULL),
-  myEndFloodTimer(new QTime()),
+  myEndFloodTime(new QTime()),
   myConnectionRetries(0),
-  myOnServerFlag(false)
+  myOnServerFlag(false),
+  myMutedFlag(false),
+  myJoinMessageTimer(new QTimer()),
+  myJoinMessagePrinted(false)
 {
-  *myEndFloodTimer = QTime::currentTime();
+  *myEndFloodTime = QTime::currentTime();
+  myJoinMessageTimer->setSingleShot(true);
 }
 
 Client::~Client()
 {
-  delete myEndFloodTimer;
-}
-
-void Client::setSocket(QTcpSocket *socket)
-{
-	mySocket = socket;
+  delete myEndFloodTime;
+  delete myJoinMessageTimer;
 }
 
 void Client::say(const QString &msg)
@@ -55,17 +56,17 @@ void Client::print(const QString &msg)
 {
 	QString str;
 
-	str = QString(host()) + ":" + QString::number(port()) + "> " + msg;
+  str = QString(host()) + ":" + QString::number(port()) + "> " + msg;
 	QByteArray b = str.toAscii();
 	Client::stripColor(b.data());
 	str = QString::fromAscii(b.data());
 
-	printf("%s", str.toAscii().data());
-	if(mySocket)
-	{
-		mySocket->write(str.toAscii());
-		mySocket->waitForBytesWritten();
-	}
+  myApp->print(str);
+}
+
+void Client::setPlayerList(PlayerList &playerList)
+{
+  myPlayerList = playerList;
 }
 
 void Client::onDisconnect()
@@ -89,15 +90,44 @@ void Client::retryConnection()
 	myConnectionRetries++;
 }
 
+bool Client::isMuted() const
+{
+  return myMutedFlag;
+}
+
 void Client::parsePrintedLine()
 {
-  QRegExp regex("^(.+):\\s+\\.([A-Za-z]+)\\s*(.*)$");
+  Player  player;
+  bool    parsed = false;
+  quint16 lastMatchSize = 0;
 
-	if(regex.indexIn(myPrintLine) == -1)
+  QByteArray playerName;
+  QByteArray printLine(myPrintLine.toAscii());
+
+  QWClient::stripColor(printLine.data());
+
+  foreach(player, myPlayerList)
+  {
+    playerName = player.name.toAscii();
+    QWClient::stripColor(playerName.data());
+    if(printLine.startsWith(playerName))
+    {
+      if(lastMatchSize < playerName.size())
+        lastMatchSize = playerName.size();
+      parsed = true;
+    }
+  }
+  if(!parsed)
 		return;
 
+  QString nick(myPrintLine.left(lastMatchSize));
+  QString message(myPrintLine.right(myPrintLine.size() - lastMatchSize));
+  QRegExp regex("^:\\s+\\.([A-Za-z]+)\\s*(.+)$");
+  if(regex.indexIn(message) == -1)
+    return;
+
 	/* Flood prot */
-  int timeLeft = QTime::currentTime().secsTo(*myEndFloodTimer);
+  int timeLeft = QTime::currentTime().secsTo(*myEndFloodTime);
   if(timeLeft > 0)
 	{
 		if(!myFloodMsgPrinted)
@@ -107,19 +137,17 @@ void Client::parsePrintedLine()
 		}
 		return;
 	}
-  *myEndFloodTimer = QTime::currentTime().addSecs(Settings::globalInstance()->floodProtTime());
-
-	QString nick = regex.capturedTexts().at(1);
-	QString command = regex.capturedTexts().at(2);
-	QString args = regex.capturedTexts().at(3);
+  *myEndFloodTime = QTime::currentTime().addSecs(Settings::globalInstance()->floodProtTime());
+  myFloodMsgPrinted = false;
 
-	myFloodMsgPrinted = false;
+  QString command = regex.capturedTexts().at(1);
+  QString args = regex.capturedTexts().at(2);
 
 	if(command == "help")
 	{
-    say("> commands:");
-    say("> .qw <message>");
-    say("> .spam <message>");
+    say("> Commands:");
+    say("> Broadcast message: .qw <message> and .spam <message>");
+    say("> Mute/Unmute the bot: .mute and .unmute");
     say("> .help to show this help message.");
 		return;
 	}
@@ -132,13 +160,11 @@ void Client::parsePrintedLine()
       return;
     }
 
-    say("> Broadcasting...");
-
     QString server(QString(host()) + ":" + QString::number(port()));
     QString message("-" + command + "- " + nick + " - " + server + " : " + args.trimmed());
 
     //-qw- Skillah - #crazy88 : 4on4 MIX qw.foppa.dk:27503 7/8
-    myApp->broadcast(message);
+    myApp->broadcast(message, myActiveClient);
 
     //myApp->requestBroadcast(command, nick, server, args.trimmed());
 
@@ -148,6 +174,20 @@ void Client::parsePrintedLine()
 
 		return;
 	}
+
+  if(command == "mute")
+  {
+    say("> Muted!");
+    myMutedFlag = true;
+    return;
+  }
+
+  if(command == "unmute")
+  {
+    say("> Unmuted!");
+    myMutedFlag = false;
+    return;
+  }
 }
 
 void Client::onPrint(int, const char *msg)
@@ -192,6 +232,7 @@ void Client::onLevelChanged(int, const char *levelName, float, float, float, flo
 {
 	print(QString(levelName) + "\n");
 	myDownloadProgressPrintedFlag = false;
+  myMutedFlag = false;
 }
 
 void Client::onChallenge()
@@ -214,6 +255,16 @@ void Client::onDownloadStarted(const char *fileName)
 	print("Download started " + QString(fileName) + "\n");
 }
 
+void Client::run()
+{
+  if(!myJoinMessageTimer->isActive() && !myJoinMessagePrinted)
+  {
+    say("Hi, I am QWNET's bot, type .help to see my commands.");
+    myJoinMessagePrinted = true;
+  }
+  QWClient::run();
+}
+
 void Client::onOOBPrint(const char *msg)
 {
 	print(QString(msg));
@@ -226,6 +277,8 @@ void Client::onStuffedCmd(const char *cmd)
 	{
 		myConnectionRetries = 0;
     myOnServerFlag = true;
+    myJoinMessageTimer->start(10000);
+    myJoinMessagePrinted = false;
 	}
 }
 

+ 14 - 4
Client.h

@@ -3,17 +3,21 @@
 
 #include "QWClient.h"
 #include <QString>
+#include <QStringList>
 #include <QList>
+#include "ServerQuery.h"
 
 class App;
-class QTcpSocket;
 class QTime;
+class QTimer;
+class ActiveClient;
 
 class Client : public QWClient
 {
 public:
-  Client(App* app);
+  Client(App* app, ActiveClient* ac);
   ~Client();
+  void run();
   void disconnect();
   void say(const QString& msg);
 	void sayTeam(const QString& msg);
@@ -21,6 +25,8 @@ public:
 	void setSocket(class QTcpSocket* socket);
   void retryConnection(); //unused
   bool isOnServer() const;
+  bool isMuted() const;
+  void setPlayerList(PlayerList &playerList);
 
 protected:
 	void onLevelChanged(int playerNum, const char *levelName, float gravity, float stopSpeed, float maxSpeed, float spectatorMaxSpeed, float accelerate, float airAccelerate, float waterAccelerate, float friction, float waterFriction, float entGravity);
@@ -37,15 +43,19 @@ protected:
 	void onOOBPrint(const char *msg);
 
 private:
+  ActiveClient*     myActiveClient;
 	App*							myApp;
-  QTcpSocket*       mySocket;
-  QTime*            myEndFloodTimer;
+  QTime*            myEndFloodTime;
 	bool							myFloodMsgPrinted;
 	int								myConnectionRetries;
 	static const int	ConnectionRetries = 10;
 	QString						myPrintLine;
 	bool							myDownloadProgressPrintedFlag;
   bool              myOnServerFlag;
+  bool              myMutedFlag;
+  QTimer*           myJoinMessageTimer;
+  bool              myJoinMessagePrinted;
+  PlayerList        myPlayerList;
 
   void print(const QString& msg);
 	void parsePrintedLine();

+ 6 - 0
ServerQuery.cpp

@@ -74,6 +74,12 @@ bool ServerQuery::query(bool pingServer)
     myActiveFlag = false;
 		return false;
 	}
+  if(!mySocket->waitForBytesWritten(300))
+  {
+    emit error(SendError);
+    myActiveFlag = false;
+    return false;
+  }
 
   if(pingServer)
     myPing = ping(10); //avg ping