Client.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /*
  2. GNU General Public License version 3 notice
  3. Copyright (C) 2012 Mihawk <luiz@netdome.biz>. All rights reserved.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see < http://www.gnu.org/licenses/ >.
  14. */
  15. #include "Client.h"
  16. #include <QString>
  17. #include <stdio.h>
  18. #include <QTcpSocket>
  19. #include <QStringList>
  20. #include <QTime>
  21. #include <QTimer>
  22. #include <QFile>
  23. #include "App.h"
  24. #include "Settings.h"
  25. static QRegExp rxColoredPattern("&c[0-9a-fA-F]{3}");
  26. static QRegExp rxBrackets("\\{[^}]*\\}");
  27. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  28. Client::Client(App *app, ActiveClient* ac):
  29. QWClient(),
  30. myActiveClient(ac),
  31. myApp(app),
  32. myOnServerFlag(false),
  33. mySpamMutedFlag(false),
  34. myQWMutedFlag(false),
  35. myKeepNickTimer(new QTimer()),
  36. myFloodTimer(new QTimer()),
  37. myBroadcastFloodTimer(new QTimer()),
  38. mySPDetectionTimer(new QTimer()),
  39. mySPSupport(false),
  40. mySPAutoDetect(true),
  41. myMaxClients(0),
  42. myCmdScheduledTimer(new QTimer())
  43. {
  44. rxBrackets.setMinimal(true);
  45. myKeepNickTimer->setSingleShot(true);
  46. myFloodTimer->setSingleShot(true);
  47. myBroadcastFloodTimer->setSingleShot(true);
  48. mySPDetectionTimer->setSingleShot(true);
  49. myCmdScheduledTimer->setSingleShot(true);
  50. }
  51. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  52. Client::~Client()
  53. {
  54. delete myKeepNickTimer;
  55. delete myFloodTimer;
  56. delete myBroadcastFloodTimer;
  57. delete mySPDetectionTimer;
  58. delete myCmdScheduledTimer;
  59. }
  60. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  61. void Client::connect(const char *host, quint16 port)
  62. {
  63. setPing(13);
  64. QWClient::connect(host, port);
  65. }
  66. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  67. void Client::say(const QString &msg, const QString &nickName)
  68. {
  69. QString cmd("say ");
  70. if(!nickName.isEmpty() && mySPSupport)
  71. cmd.append("s-p \"" + nickName + "\" ");
  72. cmd.append(msg);
  73. sendCmd(cmd.toLatin1().data());
  74. }
  75. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  76. void Client::setTeam(const QString &msg)
  77. {
  78. sendCmd(QString("setinfo \"team\" \"" + msg + "\"").toLatin1().data());
  79. }
  80. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  81. void Client::disconnect()
  82. {
  83. QWClient::disconnect();
  84. myOnServerFlag = false;
  85. }
  86. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  87. void Client::print(const QString &msg)
  88. {
  89. QString str;
  90. str = "[" + QTime::currentTime().toString(Qt::ISODate) + "] " + QString(host()) + ":" + QString::number(port()) + "> " + msg;
  91. QByteArray b = str.toLatin1();
  92. Client::stripColor(b.data());
  93. str = QString::fromLatin1(b.data());
  94. myApp->print(str);
  95. }
  96. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  97. void Client::setPlayerList(PlayerList &playerList)
  98. {
  99. myPlayerList = playerList;
  100. }
  101. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  102. void Client::onDisconnect()
  103. {
  104. print("Disconnected..\n");
  105. myOnServerFlag = false;
  106. }
  107. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  108. bool Client::isQWMuted() const
  109. {
  110. return myQWMutedFlag;
  111. }
  112. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  113. bool Client::isSpamMuted() const
  114. {
  115. return mySpamMutedFlag;
  116. }
  117. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  118. void Client::parsePrintedLine()
  119. {
  120. // Deletes invalid map for redownloading next retry
  121. if(!myOnServerFlag)
  122. {
  123. QRegExp rx("^Map model file does not match \\((.+)\\),");
  124. if(rx.indexIn(myPrintLine) != -1)
  125. {
  126. print("Invalid map, deleting this map for redownload on next retry.\n");
  127. QFile::remove(quakeDir() + "/" + gameDir() + "/" + rx.cap(1));
  128. return;
  129. }
  130. }
  131. // Detects whether s-p command is supported
  132. if(mySPDetectionTimer->isActive())
  133. {
  134. if(myPrintLine.startsWith(Settings::globalInstance()->botName() + ": s-p"))
  135. {
  136. mySPSupport = false;
  137. mySPDetectionTimer->stop();
  138. setAutoDetectSP(false); // Don't try detecting again on next map
  139. }
  140. else if(myPrintLine.startsWith("usage: s-p id/name txt"))
  141. {
  142. mySPSupport = true;
  143. mySPDetectionTimer->stop();
  144. setAutoDetectSP(false); // Don't try detecting again on next map
  145. }
  146. }
  147. // Find the player that printed this line of text
  148. Player player, bestPlayer;
  149. quint16 lastMatchSize = 0;
  150. foreach(player, myPlayerList)
  151. {
  152. if(player.spectator && myPrintLine.startsWith("[SPEC] " + player.name))
  153. {
  154. if(lastMatchSize < (player.name.size() + 7))
  155. {
  156. lastMatchSize = (player.name.size() + 7);
  157. bestPlayer = player;
  158. }
  159. continue;
  160. }
  161. if(myPrintLine.startsWith(player.name))
  162. {
  163. if(lastMatchSize < player.name.size())
  164. {
  165. lastMatchSize = player.name.size();
  166. bestPlayer = player;
  167. }
  168. continue;
  169. }
  170. }
  171. if(!lastMatchSize)
  172. return;
  173. QString nick(bestPlayer.name);
  174. if(bestPlayer.spectator)
  175. nick.prepend("(spec) ");
  176. QString message(myPrintLine.right(myPrintLine.size() - lastMatchSize));
  177. QRegExp regex("^:\\s+\\.(spam|qw|help|qw_mute|qw_unmute|spam_mute|spam_unmute|lm|about|qw_local)\\s*(.+)$");
  178. if(regex.indexIn(message) == -1)
  179. return;
  180. /* Flood prot */
  181. QTime currentTime = QTime::currentTime();
  182. int floodProtTime = Settings::globalInstance()->floodProtTime();
  183. if(myFloodTimer->isActive())
  184. {
  185. if(!myFloodMsgPrinted)
  186. {
  187. say("FloodProt: Not so fast, wait " + QString::number(floodProtTime + currentTime.secsTo(myFloodTimerStart)) + " sec(s).", bestPlayer.name);
  188. myFloodMsgPrinted = true;
  189. }
  190. return;
  191. }
  192. myFloodTimerStart = currentTime;
  193. myFloodTimer->start(floodProtTime*1000);
  194. myFloodMsgPrinted = false;
  195. QString command = regex.capturedTexts().at(1);
  196. QString args = regex.capturedTexts().at(2);
  197. if(command == "help")
  198. {
  199. say("Broadcast a message: .qw <message> or .spam <message>", bestPlayer.name);
  200. say("Broadcast locally (only to the game servers this bot is connected to): .qw_local <message>", bestPlayer.name);
  201. say("(Un)Mute: .qw_mute .qw_unmute or .spam_mute .spam_unmute", bestPlayer.name);
  202. say("Last 5 messages: .lm", bestPlayer.name);
  203. say("About this bot: .about", bestPlayer.name);
  204. return;
  205. }
  206. if(command == "about")
  207. {
  208. say("ServeMe specbots by mihawk & Haudraufwienix, find us on #qwnet @ irc.quakenet.org", bestPlayer.name);
  209. return;
  210. }
  211. if(command == "qw" || command == "spam" || command == "qw_local")
  212. {
  213. if(!args.trimmed().size())
  214. {
  215. say("The format is ." + command + " <message>.", bestPlayer.name);
  216. return;
  217. }
  218. /* Floodprot for broadcasting commands */
  219. if(command == "qw" || command == "spam" || command == "qw_local")
  220. {
  221. if(myBroadcastFloodTimer->isActive())
  222. {
  223. say("FloodProt: Wait " + QString::number(myBroadcastFloodTimer->interval()/1000 + currentTime.secsTo(myBroadcastFloodTimerStart)) + " sec(s) before issuing a new " + command, bestPlayer.name);
  224. return;
  225. }
  226. int time = 0;
  227. if(command == "qw")
  228. time = Settings::globalInstance()->qwFloodProtTime();
  229. else if(command == "spam")
  230. time = Settings::globalInstance()->spamFloodProtTime();
  231. else if(command == "qw_local")
  232. time = 30;
  233. myBroadcastFloodTimerStart = currentTime;
  234. myBroadcastFloodTimer->start(time*1000);
  235. }
  236. // Prepare all strings to be broadcasted
  237. QString server(QString(host()) + ":" + QString::number(port()));
  238. // Tries to find the hostname for this ip in the cache
  239. QString resolvedServer(myApp->serverHostName(server));
  240. if(!resolvedServer.isEmpty())
  241. resolvedServer.append(":" + QString::number(port()));
  242. else
  243. resolvedServer = server;
  244. // Internal message to be broadcast within our network of bots (don't need to have namefun parsed)
  245. // The internal message uses the resolvedServer, because this message doesn't pass tru central, thus
  246. // the server ip isn't replaced by a hostname automatically
  247. QString internalMessage("-" + command + "- " + nick + " - " + resolvedServer + " " + QString::number(playerCount()) + "/" + QString::number(myMaxClients) + " : " + args.trimmed());
  248. myApp->broadcast(internalMessage, myActiveClient);
  249. // If this is a local message don't broadcast externally
  250. if (command == "qw_local") {
  251. say("Broadcasting within qw servers only..." , bestPlayer.name);
  252. return;
  253. }
  254. // Message that will be broadcast to other networks (needs namefun parsing)
  255. // this message passes tru central, thus the server ip will be replaced by a hostname
  256. // automatically
  257. nick = parseNameFun(nick);
  258. QString parsedMsg = parseNameFun(args.trimmed());
  259. server.append(" " + QString::number(playerCount()) + "/" + QString::number(myMaxClients)); // append player count to the server (central needs another parm for this!)
  260. if(!Settings::globalInstance()->developerMode())
  261. myApp->requestBroadcast(command, nick, server, parsedMsg);
  262. else
  263. myApp->requestBroadcast("dev", nick, server, parsedMsg);
  264. say("Broadcasting...", bestPlayer.name);
  265. return;
  266. }
  267. if(command == "qw_mute")
  268. {
  269. say("Qw frequency muted.", bestPlayer.name);
  270. myQWMutedFlag = true;
  271. return;
  272. }
  273. if(command == "qw_unmute")
  274. {
  275. say("Qw frequency unmuted.", bestPlayer.name);
  276. myQWMutedFlag = false;
  277. return;
  278. }
  279. if(command == "spam_mute")
  280. {
  281. say("Spam frequency muted.", bestPlayer.name);
  282. mySpamMutedFlag = true;
  283. return;
  284. }
  285. if(command == "spam_unmute")
  286. {
  287. say("Spam frequency unmuted.", bestPlayer.name);
  288. mySpamMutedFlag = false;
  289. return;
  290. }
  291. if(command == "lm")
  292. {
  293. QStringList messages = myApp->lastMessages();
  294. if(!messages.size())
  295. {
  296. say("None", bestPlayer.name);
  297. return;
  298. }
  299. QString msg;
  300. int i = 0;
  301. foreach(msg, messages)
  302. {
  303. if(++i > 5)
  304. break;
  305. say(msg, bestPlayer.name);
  306. }
  307. return;
  308. }
  309. }
  310. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  311. int Client::playerCount() const
  312. {
  313. Player c;
  314. int pc = 0;
  315. foreach(c, myPlayerList)
  316. {
  317. if(c.spectator)
  318. continue;
  319. pc++;
  320. }
  321. return pc;
  322. }
  323. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  324. void Client::setMaxClients(int maxClients)
  325. {
  326. myMaxClients = maxClients;
  327. }
  328. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  329. int Client::maxClients() const
  330. {
  331. return myMaxClients;
  332. }
  333. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  334. void Client::onPrint(int, const char *msg)
  335. {
  336. if(!strlen(msg))
  337. return;
  338. QString text(msg);
  339. if(text.endsWith('\n'))
  340. {
  341. myPrintLine.append(text);
  342. parsePrintedLine();
  343. myPrintLine.clear();
  344. }
  345. else
  346. {
  347. myPrintLine.append(text);
  348. }
  349. }
  350. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  351. bool Client::isOnServer() const
  352. {
  353. return myOnServerFlag;
  354. }
  355. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  356. void Client::onError(const char *description)
  357. {
  358. QString desc(description);
  359. if(desc == "Client Timed Out.")
  360. {
  361. print("Error (" + QString(description) + ")\n");
  362. }
  363. else
  364. {
  365. print("Error (" + QString(description) + ")\n");
  366. }
  367. myOnServerFlag = false;
  368. }
  369. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  370. void Client::onLevelChanged(int, const char *levelName, float, float, float, float, float, float, float, float, float, float)
  371. {
  372. print(QString(levelName) + "\n");
  373. myDownloadProgressPrintedFlag = false;
  374. mySpamMutedFlag = false;
  375. myQWMutedFlag = false;
  376. setPing(13);
  377. }
  378. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  379. void Client::onChallenge()
  380. {
  381. print("challenge\n");
  382. }
  383. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  384. void Client::onConnection()
  385. {
  386. print("connection\n");
  387. }
  388. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  389. void Client::onConnected()
  390. {
  391. print("connected\n");
  392. }
  393. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  394. void Client::onDownloadStarted(const char *fileName)
  395. {
  396. print("Download started " + QString(fileName) + "\n");
  397. }
  398. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  399. void Client::run()
  400. {
  401. // Keep nick... Simply set name again after 30 secs
  402. if(!myKeepNickTimer->isActive())
  403. {
  404. setName(Settings::globalInstance()->botName().toLatin1().data());
  405. myKeepNickTimer->start(30000);
  406. }
  407. // Scheduled commands
  408. if(!myCmdScheduled.isEmpty() && !myCmdScheduledTimer->isActive())
  409. {
  410. sendCmd(myCmdScheduled.toLatin1().data());
  411. myCmdScheduled.clear();
  412. }
  413. QWClient::run();
  414. }
  415. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  416. void Client::onOOBPrint(const char *msg)
  417. {
  418. print(QString(msg));
  419. }
  420. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  421. void Client::onStuffedCmd(const char *cmd)
  422. {
  423. QString strCmd(cmd);
  424. if(strCmd == "skins") //connection sequence complete
  425. {
  426. myOnServerFlag = true;
  427. setPing(Settings::globalInstance()->botPing());
  428. if(mySPAutoDetect)
  429. spDetection();
  430. }
  431. }
  432. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  433. void Client::onDownloadProgress(int percent)
  434. {
  435. if(!(percent % 10))
  436. {
  437. if(!myDownloadProgressPrintedFlag)
  438. {
  439. print("Download " + QString::number(percent) + "%\n");
  440. myDownloadProgressPrintedFlag = true;
  441. }
  442. }
  443. else
  444. {
  445. myDownloadProgressPrintedFlag = false;
  446. }
  447. }
  448. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  449. void Client::onDownloadFinished()
  450. {
  451. print("Download 100% finished.\n");
  452. }
  453. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  454. void Client::setAutoDetectSP(bool autoDetect)
  455. {
  456. mySPAutoDetect = autoDetect;
  457. }
  458. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  459. void Client::spDetection()
  460. {
  461. say("s-p");
  462. mySPDetectionTimer->start(2000);
  463. }
  464. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  465. QString Client::parseNameFun(const QString &string)
  466. {
  467. QByteArray b(string.toLatin1());
  468. // Remove normal QW colored text
  469. QWClient::stripColor(b.data());
  470. // Remove new QW colored text
  471. QString text = QString::fromLatin1(b);
  472. int pos = 0;
  473. int index_adj;
  474. while ((pos = rxBrackets.indexIn(text, pos)) != -1) {
  475. QString match = rxBrackets.cap(0);
  476. QString newtext = rxBrackets.cap(0).replace(rxColoredPattern, "");
  477. newtext = newtext.mid(1, newtext.size()-2);
  478. index_adj = match.length() - newtext.length();
  479. text.replace(match, newtext);
  480. pos += rxBrackets.matchedLength() - index_adj;
  481. }
  482. return text;
  483. }
  484. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  485. void Client::scheduleCmd(const QString &cmd, int time)
  486. {
  487. myCmdScheduled = cmd;
  488. myCmdScheduledTimer->start(time);
  489. }