quizz.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. if (this.currentQuestion)
  161. this.bot.sendNotice(nick, this.currentQuestion.question);
  162. }
  163. QuizzBot.prototype.onNameList = function(nicks) {
  164. this.activeUsers = {};
  165. for (var i in nicks) {
  166. var u = this.users[i.toLowerCase()] = (this.users[i.toLowerCase()] || this.bot.createUser(i));
  167. u.setModeChar(nicks[i]);
  168. this.activeUsers[i.toLowerCase()] = true;
  169. }
  170. }
  171. QuizzBot.prototype.onNickPart = function(nick) {
  172. delete this.activeUsers[nick.toLowerCase()];
  173. }
  174. QuizzBot.prototype.onRename = function(oldNick, newNick) {
  175. this.users[newNick.toLowerCase()] = this.users[newNick.toLowerCase()] || this.bot.createUser(newNick);
  176. this.users[newNick.toLowerCase()].isAdmin = this.users[oldNick.toLowerCase()] && this.users[oldNick.toLowerCase()].isAdmin;
  177. this.activeUsers[newNick.toLowerCase()] = true;
  178. delete this.activeUsers[oldNick.toLowerCase()];
  179. }
  180. QuizzBot.prototype.onMessage = function(user, text) {
  181. this.users[user.toLowerCase()] && this.onMessageInternal(user, this.users[user.toLowerCase()], text.trimEnd().replace(/\s+/, ' '));
  182. }
  183. QuizzBot.prototype.onRemMode = function(user, mode) {
  184. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].unsetMode(mode);
  185. }
  186. QuizzBot.prototype.onAddMode = function(user, mode) {
  187. if (user === this.name) {
  188. usersToVoice = [];
  189. for (var i in this.users) {
  190. if (this.users[i].score && this.activeUsers[i])
  191. usersToVoice.push(i);
  192. }
  193. this.bot.voice(this.room, usersToVoice);
  194. } else {
  195. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].setMode(mode);
  196. }
  197. }
  198. QuizzBot.prototype.stop = function() {
  199. this.timer && clearTimeout(this.timer);
  200. this.timer = null;
  201. this.currentQuestion = null;
  202. this.currentHint = 0;
  203. }
  204. QuizzBot.prototype.onTick = function() {
  205. if (!this.currentQuestion)
  206. return;
  207. if (this.currentHint < 3)
  208. this.sendNextHint(false);
  209. else {
  210. var response = Array.isArray(this.currentQuestion.response) ?
  211. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  212. this.currentQuestion.response;
  213. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +response);
  214. this.nextQuestionWrapper();
  215. }
  216. }
  217. QuizzBot.prototype.resetTimer = function() {
  218. this.timer && clearTimeout(this.timer);
  219. this.timer = setInterval(this.onTick.bind(this), this.config.AUTO_HINT_DELAY);
  220. }
  221. QuizzBot.prototype.sendNextHint = function(resetTimer) {
  222. this.bot.sendMsg(this.room, this.currentQuestion.getHint(this.currentHint));
  223. ++this.currentHint;
  224. this.lastHint = Date.now();
  225. resetTimer !== false && this.resetTimer();
  226. }
  227. QuizzBot.prototype.nextQuestionWrapper = function() {
  228. this.currentQuestion.end();
  229. this.currentQuestion = null;
  230. setTimeout(this.nextQuestion.bind(this), this.config.NEXT_QUESTION_DELAY);
  231. }
  232. QuizzBot.prototype.nextQuestion = function() {
  233. this.currentQuestion = this.questions[Math.floor(Math.random() * this.questions.length)];
  234. console.log(this.currentQuestion);
  235. this.currentHint = 0;
  236. this.questionDate = Date.now();
  237. this.bot.sendMsg(this.room, "#" +this.currentQuestion.id +" " +this.currentQuestion.question);
  238. this.sendNextHint();
  239. }
  240. QuizzBot.prototype.start = function() {
  241. if (this.reloading) {
  242. this.bot.sendMsg(this.room, "Error: database still reloading");
  243. return;
  244. }
  245. if (!this.currentQuestion) {
  246. this.nextQuestion();
  247. }
  248. }
  249. QuizzBot.prototype.reloadDb = function() {
  250. var _this = this;
  251. this.stop();
  252. this.reloading = true;
  253. initQuestionList(this.config.QUESTIONS_PATH).then(questions => {
  254. _this.reloading = false;
  255. _this.questions = questions;
  256. _this.bot.sendMsg(this.room, questions.length +" questions loaded from database");
  257. _this.start();
  258. }).catch(err => {
  259. console.error(err);
  260. _this.bot.sendMsg(this.room, err);
  261. });
  262. }
  263. QuizzBot.prototype.delScore = function(user) {
  264. var data = this.users[user.toLowerCase()];
  265. if (!data) {
  266. this.bot.sendMsg(this.room, "User not found...");
  267. return;
  268. }
  269. if (!data.score) {
  270. this.bot.sendMsg(this.room, "Score for user already null");
  271. return;
  272. }
  273. data.score = 0;
  274. this.bot.sendMsg(this.room, "Removed score");
  275. Cache.SetScores(this.users);
  276. }
  277. QuizzBot.prototype.sumScores = function(onlyPresent) {
  278. var score = 0;
  279. for (var i in this.users)
  280. score += (this.users[i].score && (this.activeUsers[i] || !onlyPresent)) ? this.users[i].score : 0;
  281. return score;
  282. }
  283. QuizzBot.prototype.sendScore = function(onlyPresent) {
  284. var scores = [];
  285. for (var i in this.users)
  286. this.users[i].score && (this.activeUsers[i] || !onlyPresent) && scores.push({name: this.users[i].name, score: this.users[i].score});
  287. if (scores.length == 0) {
  288. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  289. return;
  290. }
  291. scores = scores.sort((a, b) => b.score - a.score).slice(0, 10);
  292. var index = 0;
  293. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  294. if (scoreLines[0].length < 30) {
  295. // merge score lines 2 by 2
  296. var tmp = [];
  297. for (var i =0, len = scoreLines.length; i < len; i += 2)
  298. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  299. scoreLines = tmp;
  300. }
  301. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  302. }
  303. QuizzBot.prototype.computeScore = function(username) {
  304. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response,
  305. responseMsg = "Réponse `" +rep +"` trouvée en " +Math.floor((Date.now() -this.questionDate) / 1000) +" secondes ";
  306. if (this.currentHint <= 1)
  307. responseMsg += "sans indice";
  308. else if (this.currentHint === 2)
  309. responseMsg += "avec 1 seul indice";
  310. else
  311. responseMsg += "avec " +this.currentHint +" indices";
  312. var score = 4 - this.currentHint;
  313. this.bot.sendMsg(this.room, responseMsg);
  314. return score;
  315. }
  316. QuizzBot.prototype.findQuestionById = function(qId) {
  317. for (var i =0, len = this.questions.length; i < len; ++i) {
  318. if (this.questions[i].id === qId)
  319. return this.questions[i];
  320. if (this.questions[i].id > qId)
  321. break;
  322. }
  323. }
  324. QuizzBot.prototype.resetScores = function() {
  325. if (this.sumScores(false) > 0) {
  326. this.bot.sendMsg(this.room, "Fin de la manche ! Voici les scores finaux:");
  327. this.sendScore(false);
  328. }
  329. for (var i in this.users)
  330. this.users[i].score = 0;
  331. Cache.SetScores({});
  332. }
  333. QuizzBot.prototype.onMessageInternal = function(username, user, msg) {
  334. const lmsg = msg.toLowerCase();
  335. if (lmsg.startsWith("!reload")) {
  336. if (user.admin)
  337. this.reloadDb();
  338. else
  339. this.bot.sendMsg(this.room, "Must be channel operator");
  340. }
  341. else if (lmsg.startsWith("!help")) {
  342. 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");
  343. }
  344. else if (lmsg === "!indice" || lmsg === "!conseil") {
  345. if (this.currentQuestion) {
  346. if (this.currentHint < 3) {
  347. if (Date.now() -this.lastHint > this.config.MIN_HINT_DELAY)
  348. this.sendNextHint();
  349. }
  350. else
  351. this.bot.sendMsg(this.room, "Pas plus d'indice...");
  352. }
  353. }
  354. else if (lmsg === "!next") {
  355. if (user.admin) {
  356. if (!this.currentQuestion)
  357. return;
  358. var response = Array.isArray(this.currentQuestion.response) ?
  359. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  360. this.currentQuestion.response;
  361. this.bot.sendMsg(this.room, "La réponse était: " +response);
  362. this.nextQuestionWrapper();
  363. } else {
  364. this.bot.sendMsg(this.room, "Must be channel operator");
  365. }
  366. }
  367. else if (lmsg.startsWith("!report list")) {
  368. if (user.admin) {
  369. var questions = Cache.getReportedQuestions();
  370. for (var i in questions)
  371. for (var j in questions[i])
  372. questions[i][j] = (new Date(questions[i][j])).toLocaleString();
  373. this.bot.sendNotice(username, JSON.stringify(questions));
  374. }
  375. else
  376. this.bot.sendMsg(this.room, "Must be channel operator");
  377. }
  378. else if (lmsg == ("!report clear")) {
  379. if (user.admin) {
  380. Cache.clearReports();
  381. this.bot.sendMsg(this.room, "Toutes les questions sont marquées comme restaurées");
  382. }
  383. else
  384. this.bot.sendMsg(this.room, "Must be channel operator");
  385. }
  386. else if (lmsg.startsWith("!report del ")) {
  387. var questionId = msg.substr("!report del ".length).trim();
  388. if (questionId.startsWith('#'))
  389. questionId = questionId.substr(1);
  390. questionId = Number(questionId);
  391. if (isNaN(questionId)) {
  392. this.bot.sendMsg(this.room, "Erreur: Usage: !report del #1234");
  393. return;
  394. }
  395. if (user.admin) {
  396. Cache.unreportQuestion(questionId);
  397. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme restaurée");
  398. } else if (Cache.isReportedBy(questionId, username)) {
  399. Cache.unreportQuestion(questionId, username);
  400. this.bot.sendMsg(this.room, "Question #" +questionId +" n'est plus marquée comme défectueuse par " +username);
  401. } else {
  402. this.bot.sendMsg(this.room, "Must be channel operator");
  403. }
  404. }
  405. else if (lmsg.startsWith("!report ")) {
  406. var questionId = msg.substr("!report ".length).trim();
  407. if (questionId.startsWith('#'))
  408. questionId = questionId.substr(1);
  409. questionId = Number(questionId);
  410. if (isNaN(questionId)) {
  411. this.bot.sendMsg(this.room, "Erreur: Usage: !report #1234");
  412. return;
  413. }
  414. if (!this.findQuestionById(questionId))
  415. this.bot.sendMsg(this.room, "Erreur: question non trouvée");
  416. else {
  417. Cache.reportQuestion(questionId, username);
  418. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme défectueuse par " +username);
  419. }
  420. }
  421. else if (lmsg.startsWith("!rename ")) {
  422. if (!user.admin) {
  423. this.bot.sendMsg(this.room, "Must be channel operator");
  424. return;
  425. }
  426. var args = (msg.split(/\s+/)).splice(1);
  427. if (args.length < 2) {
  428. this.bot.sendNotice(username, "Usage: !rename nouveau_pseudo ancien_pseudo [ancien_pseudo...]");
  429. return;
  430. }
  431. var sum = 0,
  432. users = [],
  433. target = args[0];
  434. args = args.map(username => username.toLowerCase());
  435. var userToMod = null;
  436. for (var i in this.users) {
  437. var userIndex = args.indexOf(i.toLowerCase());
  438. if (userIndex > 0) {
  439. sum += this.users[i].score;
  440. this.users[i].score = 0;
  441. if (!this.activeUsers[i])
  442. delete this.users[i];
  443. }
  444. else if (userIndex == 0)
  445. userToMod = this.users[i];
  446. }
  447. if (!userToMod) {
  448. userToMod = this.users[target] = this.bot.createUser(target);
  449. this.bot.sendMsg(this.room, "Created user " +target +" with " +sum +" points");
  450. } else if (sum) {
  451. this.bot.sendMsg(this.room, "Added " +sum +" points to " +target);
  452. }
  453. userToMod.score += sum;
  454. Cache.SetScores(this.users);
  455. }
  456. else if (lmsg === "!score all") {
  457. if (!user.admin) {
  458. this.bot.sendMsg(this.room, "Must be channel operator");
  459. return;
  460. }
  461. var scores = [];
  462. for (var i in this.users)
  463. this.users[i].score && scores.push({name: this.users[i].name, score: this.users[i].score});
  464. if (scores.length == 0) {
  465. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  466. return;
  467. }
  468. scores = scores.sort((a, b) => b.score - a.score);
  469. this.bot.sendNotice(username, scores.map(i => i.name+":"+i.score).join(", "));
  470. }
  471. else if (lmsg === "!score") {
  472. this.sendScore(true);
  473. }
  474. else if (lmsg === "!top") {
  475. this.sendScore(false);
  476. }
  477. else if (this.currentQuestion) {
  478. var dieOnFailure = this.currentQuestion.isBoolean() && this.currentQuestion.isBoolean(Question.normalize(msg));
  479. if (this.currentQuestion.check(msg)) {
  480. const nbPts = this.computeScore(username);
  481. user.score += nbPts;
  482. Cache.SetScores(this.users);
  483. this.bot.sendMsg(this.room, nbPts +" points pour " +username +", qui cumule un total de " +user.score +" points !");
  484. this.bot.voice(this.room, username);
  485. this.nextQuestionWrapper();
  486. }
  487. else if (dieOnFailure) {
  488. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response;
  489. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +rep);
  490. this.nextQuestionWrapper();
  491. }
  492. }
  493. };
  494. QuizzBot.prototype.mySQLExportWrapper = function() {
  495. if (!USE_MYSQL)
  496. return;
  497. var msRemaining = 0,
  498. lastMySQLExport = Cache.getLastMysqlSave();
  499. if (lastMySQLExport)
  500. msRemaining = this.config.GAME_DURATION -(Date.now() -lastMySQLExport);
  501. if (msRemaining <= 0)
  502. this.mySQLExport();
  503. else
  504. this.exportScoresTimer = setTimeout(this.mySQLExportWrapper.bind(this), Math.min(2147483000, msRemaining));
  505. }
  506. QuizzBot.prototype.mySQLExport = function() {
  507. this.exportScores().then(() => {
  508. Cache.setExportTs();
  509. this.resetScores();
  510. console.log("Successfully exported scores to MySQL");
  511. this.mySQLExportWrapper();
  512. }).catch((errString) => {
  513. console.error("mySQL Export error saving to database: ", errString);
  514. });
  515. }
  516. QuizzBot.prototype.exportScores = function() {
  517. console.log("Start exporting scores");
  518. return new Promise((ok, ko) => {
  519. if (!MySQL)
  520. return ko();
  521. var ts = Cache.getLastMysqlSave() || this.config.START_TIME;
  522. mySQL = MySQL();
  523. ts = Math.floor(ts / 1000) *1000;
  524. ts = mySQL.escape(new Date(ts));
  525. ts = ts.substr(1, ts.length -2);
  526. var sep = ts.lastIndexOf('.');
  527. if (sep > 12) ts = ts.substr(0, sep);
  528. var toSave = [];
  529. for (var i in this.users)
  530. if (this.users[i].score) {
  531. toSave.push(this.users[i].name);
  532. toSave.push(this.users[i].score);
  533. }
  534. if (toSave.length == 0) {
  535. mySQL.end();
  536. return ok();
  537. }
  538. mySQL.execute("INSERT INTO " +this.config.MySQL_PERIOD_TABLE +" (start, host) VALUES(?, ?)", [ts, HOSTNAME], (err, result) => {
  539. if (err || !result.insertId) {
  540. mySQL.end();
  541. return ko(err || "Cannot get last inserted id");
  542. }
  543. mySQL.execute("INSERT INTO " +this.config.MySQL_SCORES_TABLE +"(period_id, pseudo, score) VALUES " +(",("+result.insertId+",?,?)").repeat(toSave.length /2).substr(1), toSave, (err) => {
  544. mySQL.end();
  545. if (err)
  546. ko(err);
  547. else
  548. ok();
  549. });
  550. });
  551. });
  552. }
  553. module.exports = QuizzBot;