Client.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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)\\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> and .spam <message>", bestPlayer.name);
  200. say("(Un)Mute: .qw_mute .qw_unmute or .spam_mute .spam_unmute", bestPlayer.name);
  201. say("Last 5 messages: .lm", bestPlayer.name);
  202. say("About this bot: .about", bestPlayer.name);
  203. return;
  204. }
  205. if(command == "about")
  206. {
  207. say("ServeMe specbots by mihawk & Haudraufwienix, find us on #qwnet @ irc.quakenet.org", bestPlayer.name);
  208. return;
  209. }
  210. if(command == "qw" || command == "spam")
  211. {
  212. if(!args.trimmed().size())
  213. {
  214. say("The format is ." + command + " <message>.", bestPlayer.name);
  215. return;
  216. }
  217. /* Floodprot for broadcasting commands */
  218. if(command == "qw" || command == "spam")
  219. {
  220. if(myBroadcastFloodTimer->isActive())
  221. {
  222. say("FloodProt: Wait " + QString::number(myBroadcastFloodTimer->interval()/1000 + currentTime.secsTo(myBroadcastFloodTimerStart)) + " sec(s) before issuing a new " + command, bestPlayer.name);
  223. return;
  224. }
  225. int time;
  226. if(command == "qw")
  227. time = Settings::globalInstance()->qwFloodProtTime();
  228. else
  229. time = Settings::globalInstance()->spamFloodProtTime();
  230. myBroadcastFloodTimerStart = currentTime;
  231. myBroadcastFloodTimer->start(time*1000);
  232. }
  233. // Prepare all strings to be broadcasted
  234. QString server(QString(host()) + ":" + QString::number(port()));
  235. // Tries to find the hostname for this ip in the cache
  236. QString resolvedServer(myApp->serverHostName(server));
  237. if(!resolvedServer.isEmpty())
  238. resolvedServer.append(":" + QString::number(port()));
  239. else
  240. resolvedServer = server;
  241. // Internal message to be broadcast within our network of bots (don't need to have namefun parsed)
  242. // The internal message uses the resolvedServer, because this message doesn't pass tru central, thus
  243. // the server ip isn't replaced by a hostname automatically
  244. QString internalMessage("-" + command + "- " + nick + " - " + resolvedServer + " " + QString::number(playerCount()) + "/" + QString::number(myMaxClients) + " : " + args.trimmed());
  245. myApp->broadcast(internalMessage, myActiveClient);
  246. // Message that will be broadcast to other networks (needs namefun parsing)
  247. // this message passes tru central, thus the server ip will be replaced by a hostname
  248. // automatically
  249. nick = parseNameFun(nick);
  250. QString parsedMsg = parseNameFun(args.trimmed());
  251. server.append(" " + QString::number(playerCount()) + "/" + QString::number(myMaxClients)); // append player count to the server (central needs another parm for this!)
  252. if(!Settings::globalInstance()->developerMode())
  253. myApp->requestBroadcast(command, nick, server, parsedMsg);
  254. else
  255. myApp->requestBroadcast("dev", nick, server, parsedMsg);
  256. say("Broadcasting...", bestPlayer.name);
  257. return;
  258. }
  259. if(command == "qw_mute")
  260. {
  261. say("Qw frequency muted.", bestPlayer.name);
  262. myQWMutedFlag = true;
  263. return;
  264. }
  265. if(command == "qw_unmute")
  266. {
  267. say("Qw frequency unmuted.", bestPlayer.name);
  268. myQWMutedFlag = false;
  269. return;
  270. }
  271. if(command == "spam_mute")
  272. {
  273. say("Spam frequency muted.", bestPlayer.name);
  274. mySpamMutedFlag = true;
  275. return;
  276. }
  277. if(command == "spam_unmute")
  278. {
  279. say("Spam frequency unmuted.", bestPlayer.name);
  280. mySpamMutedFlag = false;
  281. return;
  282. }
  283. if(command == "lm")
  284. {
  285. QStringList messages = myApp->lastMessages();
  286. if(!messages.size())
  287. {
  288. say("None", bestPlayer.name);
  289. return;
  290. }
  291. QString msg;
  292. int i = 0;
  293. foreach(msg, messages)
  294. {
  295. if(++i > 5)
  296. break;
  297. say(msg, bestPlayer.name);
  298. }
  299. return;
  300. }
  301. }
  302. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  303. int Client::playerCount() const
  304. {
  305. Player c;
  306. int pc = 0;
  307. foreach(c, myPlayerList)
  308. {
  309. if(c.spectator)
  310. continue;
  311. pc++;
  312. }
  313. return pc;
  314. }
  315. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  316. void Client::setMaxClients(int maxClients)
  317. {
  318. myMaxClients = maxClients;
  319. }
  320. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  321. int Client::maxClients() const
  322. {
  323. return myMaxClients;
  324. }
  325. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  326. void Client::onPrint(int, const char *msg)
  327. {
  328. if(!strlen(msg))
  329. return;
  330. QString text(msg);
  331. if(text.endsWith('\n'))
  332. {
  333. myPrintLine.append(text);
  334. parsePrintedLine();
  335. myPrintLine.clear();
  336. }
  337. else
  338. {
  339. myPrintLine.append(text);
  340. }
  341. }
  342. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  343. bool Client::isOnServer() const
  344. {
  345. return myOnServerFlag;
  346. }
  347. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  348. void Client::onError(const char *description)
  349. {
  350. QString desc(description);
  351. if(desc == "Client Timed Out.")
  352. {
  353. print("Error (" + QString(description) + ")\n");
  354. }
  355. else
  356. {
  357. print("Error (" + QString(description) + ")\n");
  358. }
  359. myOnServerFlag = false;
  360. }
  361. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  362. void Client::onLevelChanged(int, const char *levelName, float, float, float, float, float, float, float, float, float, float)
  363. {
  364. print(QString(levelName) + "\n");
  365. myDownloadProgressPrintedFlag = false;
  366. mySpamMutedFlag = false;
  367. myQWMutedFlag = false;
  368. setPing(13);
  369. }
  370. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  371. void Client::onChallenge()
  372. {
  373. print("challenge\n");
  374. }
  375. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  376. void Client::onConnection()
  377. {
  378. print("connection\n");
  379. }
  380. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  381. void Client::onConnected()
  382. {
  383. print("connected\n");
  384. }
  385. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  386. void Client::onDownloadStarted(const char *fileName)
  387. {
  388. print("Download started " + QString(fileName) + "\n");
  389. }
  390. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  391. void Client::run()
  392. {
  393. // Keep nick... Simply set name again after 30 secs
  394. if(!myKeepNickTimer->isActive())
  395. {
  396. setName(Settings::globalInstance()->botName().toLatin1().data());
  397. myKeepNickTimer->start(30000);
  398. }
  399. // Scheduled commands
  400. if(!myCmdScheduled.isEmpty() && !myCmdScheduledTimer->isActive())
  401. {
  402. sendCmd(myCmdScheduled.toLatin1().data());
  403. myCmdScheduled.clear();
  404. }
  405. QWClient::run();
  406. }
  407. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  408. void Client::onOOBPrint(const char *msg)
  409. {
  410. print(QString(msg));
  411. }
  412. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  413. void Client::onStuffedCmd(const char *cmd)
  414. {
  415. QString strCmd(cmd);
  416. if(strCmd == "skins") //connection sequence complete
  417. {
  418. myOnServerFlag = true;
  419. setPing(Settings::globalInstance()->botPing());
  420. if(mySPAutoDetect)
  421. spDetection();
  422. }
  423. }
  424. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  425. void Client::onDownloadProgress(int percent)
  426. {
  427. if(!(percent % 10))
  428. {
  429. if(!myDownloadProgressPrintedFlag)
  430. {
  431. print("Download " + QString::number(percent) + "%\n");
  432. myDownloadProgressPrintedFlag = true;
  433. }
  434. }
  435. else
  436. {
  437. myDownloadProgressPrintedFlag = false;
  438. }
  439. }
  440. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  441. void Client::onDownloadFinished()
  442. {
  443. print("Download 100% finished.\n");
  444. }
  445. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  446. void Client::setAutoDetectSP(bool autoDetect)
  447. {
  448. mySPAutoDetect = autoDetect;
  449. }
  450. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  451. void Client::spDetection()
  452. {
  453. say("s-p");
  454. mySPDetectionTimer->start(2000);
  455. }
  456. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  457. QString Client::parseNameFun(const QString &string)
  458. {
  459. QByteArray b(string.toLatin1());
  460. // Remove normal QW colored text
  461. QWClient::stripColor(b.data());
  462. // Remove new QW colored text
  463. QString text = QString::fromLatin1(b);
  464. int pos = 0;
  465. int index_adj;
  466. while ((pos = rxBrackets.indexIn(text, pos)) != -1) {
  467. QString match = rxBrackets.cap(0);
  468. QString newtext = rxBrackets.cap(0).replace(rxColoredPattern, "");
  469. newtext = newtext.mid(1, newtext.size()-2);
  470. index_adj = match.length() - newtext.length();
  471. text.replace(match, newtext);
  472. pos += rxBrackets.matchedLength() - index_adj;
  473. }
  474. return text;
  475. }
  476. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  477. void Client::scheduleCmd(const QString &cmd, int time)
  478. {
  479. myCmdScheduled = cmd;
  480. myCmdScheduledTimer->start(time);
  481. }