quizz.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. const
  2. fs = require("fs"),
  3. readline = require("readline"),
  4. arrayPad = require('./strpad.js').arrayPad,
  5. Cache = require('./cache.js');
  6. Object.assign(global, require("./config.js"));
  7. const MySQL = USE_MYSQL ? (function() { return require("mysql2").createConnection({host: MySQL_HOST, user: MySQL_USER, database: MySQL_DB, password: MySQL_PASS}); }) : null;
  8. const HOSTNAME = require('os').hostname(); // For Mysql bot identification
  9. function Question(id, obj) {
  10. this.id = id;
  11. this.question = obj.question;
  12. this.response = obj.response;
  13. this.normalizedResponse = "";
  14. if (Array.isArray(obj.response))
  15. this.normalizedResponse = this.response.map(i => Question.normalize(i));
  16. else
  17. this.normalizedResponse = Question.normalize(this.response);
  18. }
  19. Question.normalize = function(str) {
  20. return str.normalize('NFD').replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
  21. }
  22. const QuestionType = { bool: {}, number: {}, string: {} };
  23. Question.prototype.booleanValue = function(str) {
  24. str = str || (Array.isArray(this.normalizedResponse) ? this.normalizedResponse[0] : this.normalizedResponse);
  25. var index = ["non", "oui", "faux", "vrai"].indexOf(str);
  26. if (index >= 0)
  27. return index % 2 === 1;
  28. return undefined;
  29. }
  30. Question.prototype.isBoolean = function(str) {
  31. return this.booleanValue(str) !== undefined;
  32. }
  33. String.prototype.isWord = function() {
  34. return (/\W/).exec(this) === null;
  35. }
  36. Question.prototype.getQuestionType = function() {
  37. if (this.isBoolean())
  38. return QuestionType.bool;
  39. if ((/^[0-9]+$/).exec(this.response))
  40. return QuestionType.number;
  41. return QuestionType.string;
  42. }
  43. Question.toHint = function(response, normalizedResponse, boundaries, responseIndex, questionType, hintLevel) {
  44. if (questionType === QuestionType.string) {
  45. if (hintLevel == 0)
  46. return normalizedResponse.replace(/[\w]/g, '*');
  47. else if (hintLevel == 1)
  48. return normalizedResponse.replace(/[\w]/g, (a, b) => b ? '*' : response.charAt(b));
  49. else if (normalizedResponse.isWord() && !responseIndex) {
  50. var displayed = [];
  51. const revealPercent = 0.1;
  52. displayed[normalizedResponse.length -2] = 1;
  53. displayed.fill(1, 0, normalizedResponse.length-1).fill(0, Math.ceil(normalizedResponse.length * revealPercent), normalizedResponse.length);
  54. displayed.sort(()=>Math.random() > 0.5?-1:1)
  55. return normalizedResponse.replace(/./g, (a, b) => b && !displayed[b -1] ? '*':response.charAt(b));
  56. }
  57. else
  58. return normalizedResponse.replace(/[\w]+/g, (a, wordIndex) => a.replace(/./g, (a, b) => b ? '*':response.charAt(wordIndex)));
  59. }
  60. else if (questionType === QuestionType.number) {
  61. const responseInt = Number(normalizedResponse),
  62. randomMin = ([ 30, 10, 3 ])[hintLevel],
  63. randomSpread = 5 * (5 -hintLevel);
  64. boundaries[0] = Math.max(
  65. Math.floor(responseInt -(Math.random() *randomSpread) -randomMin),
  66. boundaries[0]);
  67. boundaries[1] = Math.min(
  68. Math.ceil(responseInt +(Math.random() *randomSpread) +randomMin),
  69. boundaries[1]);
  70. return "Un nombre entre " +boundaries[0] +" et " +boundaries[1];
  71. }
  72. else
  73. console.error("Unknown response type !");
  74. };
  75. Question.prototype.getHint = function(hintLevel) {
  76. var type = this.getQuestionType();
  77. if (type === QuestionType.bool)
  78. return "Vrai / Faux ?";
  79. else if (type === QuestionType.number && !this.boundaries)
  80. this.boundaries = (Number(this.response) >= 0 ? [ 0, Infinity] : [ -Infinity, 0 ]);
  81. if (!Array.isArray(this.response))
  82. return Question.toHint(this.response, this.normalizedResponse, this.boundaries, 0, type, hintLevel);
  83. var hints = [];
  84. for (var i =0, len = this.response.length; i < len; ++i)
  85. hints.push(Question.toHint(this.response[i], this.normalizedResponse[i], this.boundaries, i, type, hintLevel));
  86. return hints.length > 1 ? ("Plusieures reponses acceptees: " +hints.join(" ou ")) : hints[0];
  87. return hints.join(" ou ");
  88. }
  89. Question.prototype.check = function(response) {
  90. response = Question.normalize(response);
  91. var boolValue = this.booleanValue();
  92. if (boolValue !== undefined)
  93. return boolValue === this.booleanValue(response);
  94. if (Array.isArray(this.normalizedResponse))
  95. return this.normalizedResponse.indexOf(response) >= 0;
  96. return response === this.normalizedResponse;
  97. }
  98. Question.prototype.end = function() {
  99. if (this.boundaries)
  100. delete this.boundaries;
  101. }
  102. function initQuestionList(filename) {
  103. return new Promise((ok, ko) => {
  104. console.log("Reloading question db");
  105. var stream = fs.createReadStream(filename),
  106. reader = readline.createInterface({input: stream}),
  107. questions = [],
  108. lineNo = 0,
  109. borken = false;
  110. reader.on("line", line => {
  111. if (borken) return;
  112. try {
  113. const firstChar = line.charAt(0);
  114. if ([';', '#'].indexOf(firstChar) >= 0) {
  115. ++lineNo;
  116. return;
  117. }
  118. var question = new Question(++lineNo, JSON.parse(line));
  119. if (question.question && question.response)
  120. questions.push(question);
  121. } catch (e) {
  122. console.error("Failed to load Database: ", e, "on line", lineNo);
  123. borken = true;
  124. reader.close();
  125. stream.destroy();
  126. ko("Failed to load database: syntax error on question #" +lineNo);
  127. }
  128. });
  129. reader.on("close", () => {
  130. if (!borken)
  131. ok(questions);
  132. });
  133. });
  134. }
  135. function QuizzBot(config) {
  136. this.config = config;
  137. }
  138. QuizzBot.prototype.init = function(bot, chanName) {
  139. const previousData = Cache.GetData();
  140. this.room = chanName;
  141. this.bot = bot;
  142. this.init = false;
  143. this.users = {};
  144. this.activeUsers = {};
  145. if (previousData) {
  146. for (var i in previousData.scores) {
  147. this.users[i.toLowerCase()] = bot.createUser(i);
  148. this.users[i.toLowerCase()].score = previousData.scores[i];
  149. }
  150. }
  151. this.mySQLExportWrapper();
  152. }
  153. QuizzBot.prototype.onSelfJoin = function() {
  154. this.init = true;
  155. this.reloadDb();
  156. }
  157. QuizzBot.prototype.onJoin = function(nick) {
  158. this.users[nick.toLowerCase()] = this.users[nick.toLowerCase()] || this.bot.createUser(nick);
  159. this.activeUsers[nick.toLowerCase()] = true;
  160. }
  161. QuizzBot.prototype.onNameList = function(nicks) {
  162. this.activeUsers = {};
  163. for (var i in nicks) {
  164. var u = this.users[i.toLowerCase()] = (this.users[i.toLowerCase()] || this.bot.createUser(i));
  165. u.setModeChar(nicks[i]);
  166. this.activeUsers[i.toLowerCase()] = true;
  167. }
  168. }
  169. QuizzBot.prototype.onNickPart = function(nick) {
  170. delete this.activeUsers[nick.toLowerCase()];
  171. }
  172. QuizzBot.prototype.onRename = function(oldNick, newNick) {
  173. this.users[newNick.toLowerCase()] = this.users[newNick.toLowerCase()] || this.bot.createUser(newNick);
  174. this.users[newNick.toLowerCase()].isAdmin = this.users[oldNick.toLowerCase()] && this.users[oldNick.toLowerCase()].isAdmin;
  175. this.activeUsers[newNick.toLowerCase()] = true;
  176. delete this.activeUsers[oldNick.toLowerCase()];
  177. }
  178. QuizzBot.prototype.onMessage = function(user, text) {
  179. this.users[user.toLowerCase()] && this.onMessageInternal(user, this.users[user.toLowerCase()], text.trimEnd().replace(/\s+/, ' '));
  180. }
  181. QuizzBot.prototype.onRemMode = function(user, mode) {
  182. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].unsetMode(mode);
  183. }
  184. QuizzBot.prototype.onAddMode = function(user, mode) {
  185. if (user === this.name) {
  186. usersToVoice = [];
  187. for (var i in this.users) {
  188. if (this.users[i].score && this.activeUsers[i])
  189. usersToVoice.push(i);
  190. }
  191. this.bot.voice(this.room, usersToVoice);
  192. } else {
  193. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].setMode(mode);
  194. }
  195. }
  196. QuizzBot.prototype.stop = function() {
  197. this.timer && clearTimeout(this.timer);
  198. this.timer = null;
  199. this.currentQuestion = null;
  200. this.currentHint = 0;
  201. }
  202. QuizzBot.prototype.onTick = function() {
  203. if (!this.currentQuestion)
  204. return;
  205. if (this.currentHint < 3)
  206. this.sendNextHint(false);
  207. else {
  208. var response = Array.isArray(this.currentQuestion.response) ?
  209. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  210. this.currentQuestion.response;
  211. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +response);
  212. this.nextQuestionWrapper();
  213. }
  214. }
  215. QuizzBot.prototype.resetTimer = function() {
  216. this.timer && clearTimeout(this.timer);
  217. this.timer = setInterval(this.onTick.bind(this), this.config.AUTO_HINT_DELAY);
  218. }
  219. QuizzBot.prototype.sendNextHint = function(resetTimer) {
  220. this.bot.sendMsg(this.room, this.currentQuestion.getHint(this.currentHint));
  221. ++this.currentHint;
  222. this.lastHint = Date.now();
  223. resetTimer !== false && this.resetTimer();
  224. }
  225. QuizzBot.prototype.nextQuestionWrapper = function() {
  226. this.currentQuestion.end();
  227. this.currentQuestion = null;
  228. setTimeout(this.nextQuestion.bind(this), this.config.NEXT_QUESTION_DELAY);
  229. }
  230. QuizzBot.prototype.nextQuestion = function() {
  231. this.currentQuestion = this.questions[Math.floor(Math.random() * this.questions.length)];
  232. console.log(this.currentQuestion);
  233. this.currentHint = 0;
  234. this.questionDate = Date.now();
  235. this.bot.sendMsg(this.room, "#" +this.currentQuestion.id +" " +this.currentQuestion.question);
  236. this.sendNextHint();
  237. }
  238. QuizzBot.prototype.start = function() {
  239. if (this.reloading) {
  240. this.bot.sendMsg(this.room, "Error: database still reloading");
  241. return;
  242. }
  243. if (!this.currentQuestion) {
  244. this.nextQuestion();
  245. }
  246. }
  247. QuizzBot.prototype.reloadDb = function() {
  248. var _this = this;
  249. this.stop();
  250. this.reloading = true;
  251. initQuestionList(this.config.QUESTIONS_PATH).then(questions => {
  252. _this.reloading = false;
  253. _this.questions = questions;
  254. _this.bot.sendMsg(this.room, questions.length +" questions loaded from database");
  255. _this.start();
  256. }).catch(err => {
  257. console.error(err);
  258. _this.bot.sendMsg(this.room, err);
  259. });
  260. }
  261. QuizzBot.prototype.delScore = function(user) {
  262. var data = this.users[user.toLowerCase()];
  263. if (!data) {
  264. this.bot.sendMsg(this.room, "User not found...");
  265. return;
  266. }
  267. if (!data.score) {
  268. this.bot.sendMsg(this.room, "Score for user already null");
  269. return;
  270. }
  271. data.score = 0;
  272. this.bot.sendMsg(this.room, "Removed score");
  273. Cache.SetScores(this.users);
  274. }
  275. QuizzBot.prototype.sumScores = function(onlyPresent) {
  276. var score = 0;
  277. for (var i in this.users)
  278. score += (this.users[i].score && (this.activeUsers[i] || !onlyPresent)) ? this.users[i].score : 0;
  279. return score;
  280. }
  281. QuizzBot.prototype.sendScore = function(onlyPresent) {
  282. var scores = [];
  283. for (var i in this.users)
  284. this.users[i].score && (this.activeUsers[i] || !onlyPresent) && scores.push({name: this.users[i].name, score: this.users[i].score});
  285. if (scores.length == 0) {
  286. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  287. return;
  288. }
  289. scores = scores.sort((a, b) => b.score - a.score).slice(0, 10);
  290. var index = 0;
  291. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  292. if (scoreLines[0].length < 30) {
  293. // merge score lines 2 by 2
  294. var tmp = [];
  295. for (var i =0, len = scoreLines.length; i < len; i += 2)
  296. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  297. scoreLines = tmp;
  298. }
  299. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  300. }
  301. QuizzBot.prototype.computeScore = function(username) {
  302. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response,
  303. responseMsg = "Réponse `" +rep +"` trouvée en " +Math.floor((Date.now() -this.questionDate) / 1000) +" secondes ";
  304. if (this.currentHint <= 1)
  305. responseMsg += "sans indice";
  306. else if (this.currentHint === 2)
  307. responseMsg += "avec 1 seul indice";
  308. else
  309. responseMsg += "avec " +this.currentHint +" indices";
  310. var score = 4 - this.currentHint;
  311. this.bot.sendMsg(this.room, responseMsg);
  312. return score;
  313. }
  314. QuizzBot.prototype.findQuestionById = function(qId) {
  315. for (var i =0, len = this.questions.length; i < len; ++i) {
  316. if (this.questions[i].id === qId)
  317. return this.questions[i];
  318. if (this.questions[i].id > qId)
  319. break;
  320. }
  321. }
  322. QuizzBot.prototype.resetScores = function() {
  323. if (this.sumScores(false) > 0) {
  324. this.bot.sendMsg(this.room, "Fin de la manche ! Voici les scores finaux:");
  325. this.sendScore(false);
  326. }
  327. for (var i in this.users)
  328. this.users[i].score = 0;
  329. Cache.SetScores({});
  330. }
  331. QuizzBot.prototype.onMessageInternal = function(username, user, msg) {
  332. const lmsg = msg.toLowerCase();
  333. if (lmsg.startsWith("!reload")) {
  334. if (user.admin)
  335. this.reloadDb();
  336. else
  337. this.bot.sendMsg(this.room, "Must be channel operator");
  338. }
  339. else if (lmsg.startsWith("!help")) {
  340. this.bot.sendMsg(this.room, "Besoin d'aide ? La liste des commandes utiles est sur ce site : https://git.knacki.info/irc.knacki.info/ircbot-quizz/src/master/quizz.md");
  341. }
  342. else if (lmsg === "!indice" || lmsg === "!conseil") {
  343. if (this.currentQuestion) {
  344. if (this.currentHint < 3) {
  345. if (Date.now() -this.lastHint > this.config.MIN_HINT_DELAY)
  346. this.sendNextHint();
  347. }
  348. else
  349. this.bot.sendMsg(this.room, "Pas plus d'indice...");
  350. }
  351. }
  352. else if (lmsg === "!next") {
  353. if (user.admin) {
  354. if (!this.currentQuestion)
  355. return;
  356. var response = Array.isArray(this.currentQuestion.response) ?
  357. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  358. this.currentQuestion.response;
  359. this.bot.sendMsg(this.room, "La réponse était: " +response);
  360. this.nextQuestionWrapper();
  361. } else {
  362. this.bot.sendMsg(this.room, "Must be channel operator");
  363. }
  364. }
  365. else if (lmsg.startsWith("!report list")) {
  366. if (user.admin) {
  367. var questions = Cache.getReportedQuestions();
  368. for (var i in questions)
  369. for (var j in questions[i])
  370. questions[i][j] = (new Date(questions[i][j])).toLocaleString();
  371. this.bot.sendNotice(username, JSON.stringify(questions));
  372. }
  373. else
  374. this.bot.sendMsg(this.room, "Must be channel operator");
  375. }
  376. else if (lmsg == ("!report clear")) {
  377. if (user.admin) {
  378. Cache.clearReports();
  379. this.bot.sendMsg(this.room, "Toutes les questions sont marquées comme restaurées");
  380. }
  381. else
  382. this.bot.sendMsg(this.room, "Must be channel operator");
  383. }
  384. else if (lmsg.startsWith("!report del ")) {
  385. var questionId = msg.substr("!report del ".length).trim();
  386. if (questionId.startsWith('#'))
  387. questionId = questionId.substr(1);
  388. questionId = Number(questionId);
  389. if (isNaN(questionId)) {
  390. this.bot.sendMsg(this.room, "Erreur: Usage: !report del #1234");
  391. return;
  392. }
  393. if (user.admin) {
  394. Cache.unreportQuestion(questionId);
  395. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme restaurée");
  396. } else if (Cache.isReportedBy(questionId, username)) {
  397. Cache.unreportQuestion(questionId, username);
  398. this.bot.sendMsg(this.room, "Question #" +questionId +" n'est plus marquée comme défectueuse par " +username);
  399. } else {
  400. this.bot.sendMsg(this.room, "Must be channel operator");
  401. }
  402. }
  403. else if (lmsg.startsWith("!report ")) {
  404. var questionId = msg.substr("!report ".length).trim();
  405. if (questionId.startsWith('#'))
  406. questionId = questionId.substr(1);
  407. questionId = Number(questionId);
  408. if (isNaN(questionId)) {
  409. this.bot.sendMsg(this.room, "Erreur: Usage: !report #1234");
  410. return;
  411. }
  412. if (!this.findQuestionById(questionId))
  413. this.bot.sendMsg(this.room, "Erreur: question non trouvée");
  414. else {
  415. Cache.reportQuestion(questionId, username);
  416. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme défectueuse par " +username);
  417. }
  418. }
  419. else if (lmsg.startsWith("!rename ")) {
  420. if (!user.admin) {
  421. this.bot.sendMsg(this.room, "Must be channel operator");
  422. return;
  423. }
  424. var args = (msg.split(/\s+/)).splice(1);
  425. if (args.length < 2) {
  426. this.bot.sendNotice(username, "Usage: !rename nouveau_pseudo ancien_pseudo [ancien_pseudo...]");
  427. return;
  428. }
  429. var sum = 0,
  430. users = [],
  431. target = args[0];
  432. args = args.map(username => username.toLowerCase());
  433. var userToMod = null;
  434. for (var i in this.users) {
  435. var userIndex = args.indexOf(i.toLowerCase());
  436. if (userIndex > 0) {
  437. sum += this.users[i].score;
  438. this.users[i].score = 0;
  439. if (!this.activeUsers[i])
  440. delete this.users[i];
  441. }
  442. else if (userIndex == 0)
  443. userToMod = this.users[i];
  444. }
  445. if (!userToMod) {
  446. userToMod = this.users[target] = this.bot.createUser(target);
  447. this.bot.sendMsg(this.room, "Created user " +target +" with " +sum +" points");
  448. } else if (sum) {
  449. this.bot.sendMsg(this.room, "Added " +sum +" points to " +target);
  450. }
  451. userToMod.score += sum;
  452. Cache.SetScores(this.users);
  453. }
  454. else if (lmsg === "!score all") {
  455. if (!user.admin) {
  456. this.bot.sendMsg(this.room, "Must be channel operator");
  457. return;
  458. }
  459. var scores = [];
  460. for (var i in this.users)
  461. this.users[i].score && scores.push({name: this.users[i].name, score: this.users[i].score});
  462. if (scores.length == 0) {
  463. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  464. return;
  465. }
  466. scores = scores.sort((a, b) => b.score - a.score);
  467. this.bot.sendNotice(username, scores.map(i => i.name+":"+i.score).join(", "));
  468. }
  469. else if (lmsg === "!score") {
  470. this.sendScore(true);
  471. }
  472. else if (lmsg === "!top") {
  473. this.sendScore(false);
  474. }
  475. else if (this.currentQuestion) {
  476. var dieOnFailure = this.currentQuestion.isBoolean() && this.currentQuestion.isBoolean(Question.normalize(msg));
  477. if (this.currentQuestion.check(msg)) {
  478. const nbPts = this.computeScore(username);
  479. user.score += nbPts;
  480. Cache.SetScores(this.users);
  481. this.bot.sendMsg(this.room, nbPts +" points pour " +username +", qui cumule un total de " +user.score +" points !");
  482. this.bot.voice(this.room, username);
  483. this.nextQuestionWrapper();
  484. }
  485. else if (dieOnFailure) {
  486. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response;
  487. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +rep);
  488. this.nextQuestionWrapper();
  489. }
  490. }
  491. };
  492. QuizzBot.prototype.mySQLExportWrapper = function() {
  493. if (!USE_MYSQL)
  494. return;
  495. var msRemaining = 0,
  496. lastMySQLExport = Cache.getLastMysqlSave();
  497. if (lastMySQLExport)
  498. msRemaining = this.config.GAME_DURATION -(Date.now() -lastMySQLExport);
  499. if (msRemaining <= 0)
  500. this.mySQLExport();
  501. else
  502. this.exportScoresTimer = setTimeout(this.mySQLExportWrapper.bind(this), Math.min(2147483000, msRemaining));
  503. }
  504. QuizzBot.prototype.mySQLExport = function() {
  505. this.exportScores().then(() => {
  506. Cache.setExportTs();
  507. this.resetScores();
  508. console.log("Successfully exported scores to MySQL");
  509. this.mySQLExportWrapper();
  510. }).catch((errString) => {
  511. console.error("mySQL Export error saving to database: ", errString);
  512. });
  513. }
  514. QuizzBot.prototype.exportScores = function() {
  515. console.log("Start exporting scores");
  516. return new Promise((ok, ko) => {
  517. if (!MySQL)
  518. return ko();
  519. var ts = Cache.getLastMysqlSave() || this.config.START_TIME;
  520. mySQL = MySQL();
  521. ts = Math.floor(ts / 1000) *1000;
  522. ts = mySQL.escape(new Date(ts));
  523. ts = ts.substr(1, ts.length -2);
  524. var sep = ts.lastIndexOf('.');
  525. if (sep > 12) ts = ts.substr(0, sep);
  526. var toSave = [];
  527. for (var i in this.users)
  528. if (this.users[i].score) {
  529. toSave.push(this.users[i].name);
  530. toSave.push(this.users[i].score);
  531. }
  532. if (toSave.length == 0) {
  533. mySQL.end();
  534. return ok();
  535. }
  536. mySQL.execute("INSERT INTO " +this.config.MySQL_PERIOD_TABLE +" (start, host) VALUES(?, ?)", [ts, HOSTNAME], (err, result) => {
  537. if (err || !result.insertId) {
  538. mySQL.end();
  539. return ko(err || "Cannot get last inserted id");
  540. }
  541. mySQL.execute("INSERT INTO " +this.config.MySQL_SCORES_TABLE +"(period_id, pseudo, score) VALUES " +(",("+result.insertId+",?,?)").repeat(toSave.length /2).substr(1), toSave, (err) => {
  542. mySQL.end();
  543. if (err)
  544. ko(err);
  545. else
  546. ok();
  547. });
  548. });
  549. });
  550. }
  551. module.exports = QuizzBot;