quizz.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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 ? 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.join (" ou ");
  87. }
  88. Question.prototype.check = function(response) {
  89. response = Question.normalize(response);
  90. var boolValue = this.booleanValue();
  91. if (boolValue !== undefined)
  92. return boolValue === this.booleanValue(response);
  93. if (Array.isArray(this.normalizedResponse))
  94. return this.normalizedResponse.indexOf(response) >= 0;
  95. return response === this.normalizedResponse;
  96. }
  97. Question.prototype.end = function() {
  98. if (this.boundaries)
  99. delete this.boundaries;
  100. }
  101. function initQuestionList(filename) {
  102. return new Promise((ok, ko) => {
  103. console.log("Reloading question db");
  104. var stream = fs.createReadStream(filename),
  105. reader = readline.createInterface({input: stream}),
  106. questions = [],
  107. lineNo = 0,
  108. borken = false;
  109. reader.on("line", line => {
  110. if (borken) return;
  111. try {
  112. const firstChar = line.charAt(0);
  113. if ([';', '#'].indexOf(firstChar) >= 0) {
  114. ++lineNo;
  115. return;
  116. }
  117. var question = new Question(++lineNo, JSON.parse(line));
  118. if (question.question && question.response)
  119. questions.push(question);
  120. } catch (e) {
  121. console.error("Failed to load Database: ", e, "on line", lineNo);
  122. borken = true;
  123. reader.close();
  124. stream.destroy();
  125. ko("Failed to load database: syntax error on question #" +lineNo);
  126. }
  127. });
  128. reader.on("close", () => {
  129. if (!borken)
  130. ok(questions);
  131. });
  132. });
  133. }
  134. function QuizzBot(config) {
  135. this.config = config;
  136. }
  137. QuizzBot.prototype.init = function(bot, chanName) {
  138. const previousData = Cache.GetData();
  139. this.room = chanName;
  140. this.bot = bot;
  141. this.init = false;
  142. this.users = {};
  143. this.activeUsers = {};
  144. if (previousData) {
  145. for (var i in previousData.scores) {
  146. this.users[i.toLowerCase()] = bot.createUser(i);
  147. this.users[i.toLowerCase()].score = previousData.scores[i];
  148. }
  149. }
  150. this.mySQLExportWrapper();
  151. }
  152. QuizzBot.prototype.onSelfJoin = function() {
  153. this.init = true;
  154. this.reloadDb();
  155. }
  156. QuizzBot.prototype.onJoin = function(nick) {
  157. this.users[nick.toLowerCase()] = this.users[nick.toLowerCase()] || this.bot.createUser(nick);
  158. this.activeUsers[nick.toLowerCase()] = true;
  159. }
  160. QuizzBot.prototype.onNameList = function(nicks) {
  161. this.activeUsers = {};
  162. for (var i in nicks) {
  163. var u = this.users[i.toLowerCase()] = (this.users[i.toLowerCase()] || this.bot.createUser(i));
  164. u.setModeChar(nicks[i]);
  165. this.activeUsers[i.toLowerCase()] = true;
  166. }
  167. }
  168. QuizzBot.prototype.onNickPart = function(nick) {
  169. delete this.activeUsers[nick.toLowerCase()];
  170. }
  171. QuizzBot.prototype.onRename = function(oldNick, newNick) {
  172. this.users[newNick.toLowerCase()] = this.users[newNick.toLowerCase()] || this.bot.createUser(newNick);
  173. this.users[newNick.toLowerCase()].isAdmin = this.users[oldNick.toLowerCase()] && this.users[oldNick.toLowerCase()].isAdmin;
  174. this.activeUsers[newNick.toLowerCase()] = true;
  175. delete this.activeUsers[oldNick.toLowerCase()];
  176. }
  177. QuizzBot.prototype.onMessage = function(user, text) {
  178. this.users[user.toLowerCase()] && this.onMessageInternal(user, this.users[user.toLowerCase()], text.trimEnd().replace(/\s+/, ' '));
  179. }
  180. QuizzBot.prototype.onRemMode = function(user, mode) {
  181. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].unsetMode(mode);
  182. }
  183. QuizzBot.prototype.onAddMode = function(user, mode) {
  184. if (user === this.name) {
  185. usersToVoice = [];
  186. for (var i in this.users) {
  187. if (this.users[i].score && this.activeUsers[i])
  188. usersToVoice.push(i);
  189. }
  190. this.bot.voice(this.room, usersToVoice);
  191. } else {
  192. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].setMode(mode);
  193. }
  194. }
  195. QuizzBot.prototype.stop = function() {
  196. this.timer && clearTimeout(this.timer);
  197. this.timer = null;
  198. this.currentQuestion = null;
  199. this.currentHint = 0;
  200. }
  201. QuizzBot.prototype.onTick = function() {
  202. if (!this.currentQuestion)
  203. return;
  204. if (this.currentHint < 3)
  205. this.sendNextHint(false);
  206. else {
  207. var response = Array.isArray(this.currentQuestion.response) ?
  208. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  209. this.currentQuestion.response;
  210. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +response);
  211. this.nextQuestionWrapper();
  212. }
  213. }
  214. QuizzBot.prototype.resetTimer = function() {
  215. this.timer && clearTimeout(this.timer);
  216. this.timer = setInterval(this.onTick.bind(this), this.config.AUTO_HINT_DELAY);
  217. }
  218. QuizzBot.prototype.sendNextHint = function(resetTimer) {
  219. this.bot.sendMsg(this.room, this.currentQuestion.getHint(this.currentHint));
  220. ++this.currentHint;
  221. this.lastHint = Date.now();
  222. resetTimer !== false && this.resetTimer();
  223. }
  224. QuizzBot.prototype.nextQuestionWrapper = function() {
  225. this.currentQuestion.end();
  226. this.currentQuestion = null;
  227. setTimeout(this.nextQuestion.bind(this), this.config.NEXT_QUESTION_DELAY);
  228. }
  229. QuizzBot.prototype.nextQuestion = function() {
  230. this.currentQuestion = this.questions[Math.floor(Math.random() * this.questions.length)];
  231. console.log(this.currentQuestion);
  232. this.currentHint = 0;
  233. this.questionDate = Date.now();
  234. this.bot.sendMsg(this.room, "#" +this.currentQuestion.id +" " +this.currentQuestion.question);
  235. this.sendNextHint();
  236. }
  237. QuizzBot.prototype.start = function() {
  238. if (this.reloading) {
  239. this.bot.sendMsg(this.room, "Error: database still reloading");
  240. return;
  241. }
  242. if (!this.currentQuestion) {
  243. this.nextQuestion();
  244. }
  245. }
  246. QuizzBot.prototype.reloadDb = function() {
  247. var _this = this;
  248. this.stop();
  249. this.reloading = true;
  250. initQuestionList(this.config.QUESTIONS_PATH).then(questions => {
  251. _this.reloading = false;
  252. _this.questions = questions;
  253. _this.bot.sendMsg(this.room, questions.length +" questions loaded from database");
  254. _this.start();
  255. }).catch(err => {
  256. console.error(err);
  257. _this.bot.sendMsg(this.room, err);
  258. });
  259. }
  260. QuizzBot.prototype.delScore = function(user) {
  261. var data = this.users[user.toLowerCase()];
  262. if (!data) {
  263. this.bot.sendMsg(this.room, "User not found...");
  264. return;
  265. }
  266. if (!data.score) {
  267. this.bot.sendMsg(this.room, "Score for user already null");
  268. return;
  269. }
  270. data.score = 0;
  271. this.bot.sendMsg(this.room, "Removed score");
  272. Cache.SetScores(this.users);
  273. }
  274. QuizzBot.prototype.sumScores = function(onlyPresent) {
  275. var score = 0;
  276. for (var i in this.users)
  277. score += (this.users[i].score && (this.activeUsers[i] || !onlyPresent)) ? this.users[i].score : 0;
  278. return score;
  279. }
  280. QuizzBot.prototype.sendScore = function(onlyPresent) {
  281. var scores = [];
  282. for (var i in this.users)
  283. this.users[i].score && (this.activeUsers[i] || !onlyPresent) && scores.push({name: this.users[i].name, score: this.users[i].score});
  284. if (scores.length == 0) {
  285. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  286. return;
  287. }
  288. scores = scores.sort((a, b) => b.score - a.score).slice(0, 10);
  289. var index = 0;
  290. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  291. if (scoreLines[0].length < 30) {
  292. // merge score lines 2 by 2
  293. var tmp = [];
  294. for (var i =0, len = scoreLines.length; i < len; i += 2)
  295. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  296. scoreLines = tmp;
  297. }
  298. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  299. }
  300. QuizzBot.prototype.computeScore = function(username) {
  301. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response,
  302. responseMsg = "Réponse `" +rep +"` trouvée en " +Math.floor((Date.now() -this.questionDate) / 1000) +" secondes ";
  303. if (this.currentHint <= 1)
  304. responseMsg += "sans indice";
  305. else if (this.currentHint === 2)
  306. responseMsg += "avec 1 seul indice";
  307. else
  308. responseMsg += "avec " +this.currentHint +" indices";
  309. var score = 4 - this.currentHint;
  310. this.bot.sendMsg(this.room, responseMsg);
  311. return score;
  312. }
  313. QuizzBot.prototype.findQuestionById = function(qId) {
  314. for (var i =0, len = this.questions.length; i < len; ++i) {
  315. if (this.questions[i].id === qId)
  316. return this.questions[i];
  317. if (this.questions[i].id > qId)
  318. break;
  319. }
  320. }
  321. QuizzBot.prototype.resetScores = function() {
  322. if (this.sumScores(false) > 0) {
  323. this.bot.sendMsg(this.room, "Fin de la manche ! Voici les scores finaux:");
  324. this.sendScore(false);
  325. }
  326. for (var i in this.users)
  327. this.users[i].score = 0;
  328. Cache.SetScores({});
  329. }
  330. QuizzBot.prototype.onMessageInternal = function(username, user, msg) {
  331. const lmsg = msg.toLowerCase();
  332. if (lmsg.startsWith("!reload")) {
  333. if (user.admin)
  334. this.reloadDb();
  335. else
  336. this.bot.sendMsg(this.room, "Must be channel operator");
  337. }
  338. else if (lmsg.startsWith("!aide")) {
  339. this.bot.sendMsg(this.room, "Usage: !aide | !indice | !reload | !next | !rename | !score [del pseudo] || !top");
  340. }
  341. else if (lmsg === "!indice" || lmsg === "!conseil") {
  342. if (this.currentQuestion) {
  343. if (this.currentHint < 3) {
  344. if (Date.now() -this.lastHint > this.config.MIN_HINT_DELAY)
  345. this.sendNextHint();
  346. }
  347. else
  348. this.bot.sendMsg(this.room, "Pas plus d'indice...");
  349. }
  350. }
  351. else if (lmsg === "!next") {
  352. if (user.admin) {
  353. if (!this.currentQuestion)
  354. return;
  355. var response = Array.isArray(this.currentQuestion.response) ?
  356. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  357. this.currentQuestion.response;
  358. this.bot.sendMsg(this.room, "La réponse était: " +response);
  359. this.nextQuestionWrapper();
  360. } else {
  361. this.bot.sendMsg(this.room, "Must be channel operator");
  362. }
  363. }
  364. else if (lmsg.startsWith("!report list")) {
  365. if (user.admin) {
  366. var questions = Cache.getReportedQuestions();
  367. for (var i in questions)
  368. for (var j in questions[i])
  369. questions[i][j] = (new Date(questions[i][j])).toLocaleString();
  370. this.bot.sendNotice(username, JSON.stringify(questions));
  371. }
  372. else
  373. this.bot.sendMsg(this.room, "Must be channel operator");
  374. }
  375. else if (lmsg == ("!report clear")) {
  376. if (user.admin) {
  377. Cache.clearReports();
  378. this.bot.sendMsg(this.room, "Toutes les questions sont marquées comme restaurées");
  379. }
  380. else
  381. this.bot.sendMsg(this.room, "Must be channel operator");
  382. }
  383. else if (lmsg.startsWith("!report del ")) {
  384. var questionId = msg.substr("!report del ".length).trim();
  385. if (questionId.startsWith('#'))
  386. questionId = questionId.substr(1);
  387. questionId = Number(questionId);
  388. if (isNaN(questionId)) {
  389. this.bot.sendMsg(this.room, "Erreur: Usage: !report del #1234");
  390. return;
  391. }
  392. if (user.admin) {
  393. Cache.unreportQuestion(questionId);
  394. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme restaurée");
  395. } else if (Cache.isReportedBy(questionId, username)) {
  396. Cache.unreportQuestion(questionId, username);
  397. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme restaurée");
  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("!score del ")) {
  420. if (user.admin)
  421. this.delScore(msg.substr("!score del ".length).trim());
  422. else
  423. this.bot.sendMsg(this.room, "Must be channel operator");
  424. }
  425. else if (lmsg.startsWith("!rename")) {
  426. if (!user.admin) {
  427. this.bot.sendMsg(this.room, "Must be channel operator");
  428. return;
  429. }
  430. var args = (msg.split(/\s+/)).splice(1);
  431. if (args.length < 2) {
  432. this.bot.sendNotice(username, "Usage: !rename nouveau_pseudo ancien_pseudo [ancien_pseudo...]");
  433. return;
  434. }
  435. var sum = 0,
  436. users = [],
  437. target = args[0];
  438. args = args.map(username => username.toLowerCase());
  439. var userToMod = null;
  440. for (var i in this.users) {
  441. var userIndex = args.indexOf(i.toLowerCase());
  442. if (userIndex > 0) {
  443. sum += this.users[i].score;
  444. this.users[i].score = 0;
  445. if (!this.activeUsers[i])
  446. delete this.users[i];
  447. }
  448. else if (userIndex == 0)
  449. userToMod = this.users[i];
  450. }
  451. if (!userToMod) {
  452. userToMod = this.users[target] = this.bot.createUser(target);
  453. this.bot.sendMsg(this.room, "Created user " +target);
  454. }
  455. userToMod.score += sum;
  456. Cache.SetScores(this.users);
  457. }
  458. else if (lmsg.startsWith("!score all")) {
  459. if (!user.admin) {
  460. this.bot.sendMsg(this.room, "Must be channel operator");
  461. return;
  462. }
  463. var scores = [];
  464. for (var i in this.users)
  465. this.users[i].score && scores.push({name: this.users[i].name, score: this.users[i].score});
  466. if (scores.length == 0) {
  467. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  468. return;
  469. }
  470. scores = scores.sort((a, b) => b.score - a.score).slice(0, 10);
  471. this.bot.sendNotice(username, scores.map(i => i.name+":"+i.score).join(", "));
  472. }
  473. else if (lmsg.startsWith("!score")) {
  474. this.sendScore(true);
  475. }
  476. else if (lmsg.startsWith("!top")) {
  477. this.sendScore(false);
  478. }
  479. else if (this.currentQuestion) {
  480. var dieOnFailure = this.currentQuestion.isBoolean() && this.currentQuestion.isBoolean(Question.normalize(msg));
  481. if (this.currentQuestion.check(msg)) {
  482. const nbPts = this.computeScore(username);
  483. user.score += nbPts;
  484. Cache.SetScores(this.users);
  485. this.bot.sendMsg(this.room, nbPts +" points pour " +username +", qui cumule un total de " +user.score +" points !");
  486. this.bot.voice(this.room, username);
  487. this.nextQuestionWrapper();
  488. }
  489. else if (dieOnFailure) {
  490. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response;
  491. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +rep);
  492. this.nextQuestionWrapper();
  493. }
  494. }
  495. };
  496. QuizzBot.prototype.mySQLExportWrapper = function() {
  497. if (!USE_MYSQL)
  498. return;
  499. var msRemaining = 0,
  500. lastMySQLExport = Cache.getLastMysqlSave();
  501. if (lastMySQLExport)
  502. msRemaining = this.config.GAME_DURATION -(Date.now() -lastMySQLExport);
  503. if (msRemaining <= 0)
  504. this.mySQLExport();
  505. else
  506. this.exportScoresTimer = setTimeout(this.mySQLExportWrapper.bind(this), Math.min(2147483000, msRemaining));
  507. }
  508. QuizzBot.prototype.mySQLExport = function() {
  509. this.exportScores().then(() => {
  510. Cache.setExportTs();
  511. this.resetScores();
  512. console.log("Successfully exported scores to MySQL");
  513. this.mySQLExportWrapper();
  514. }).catch((errString) => {
  515. console.error("mySQL Export error saving to database: ", errString);
  516. });
  517. }
  518. QuizzBot.prototype.exportScores = function() {
  519. return new Promise((ok, ko) => {
  520. var ts = Cache.getLastMysqlSave() || this.config.START_TIME;
  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. return ok();
  534. MySQL.execute("INSERT INTO " +this.config.MySQL_PERIOD_TABLE +" (start, host) VALUES(?, ?)", [ts, HOSTNAME], (err, result) => {
  535. if (err || !result.insertId)
  536. return ko(err || "Cannot get last inserted id");
  537. MySQL.execute("INSERT INTO " +this.config.MySQL_SCORES_TABLE +"(period_id, pseudo, score) VALUES " +(",("+result.insertId+",?,?)").repeat(toSave.length /2).substr(1), toSave, (err) => {
  538. if (err)
  539. ko(err);
  540. else
  541. ok();
  542. });
  543. });
  544. });
  545. }
  546. module.exports = QuizzBot;