Commit bee4f43b by Иван Кубота

logger with socket

parent 4305d5a4
#KUS_GENERATOR_BACKEND=https://api.new.local.vkusvill.testin.ru #KUS_GENERATOR_BACKEND=https://api.new.local.vkusvill.testin.ru
KUS_GENERATOR_BACKEND=https://api.vkusvill.flexlab.pro KUS_GENERATOR_BACKEND=https://api.vkusvill.flexlab.pro
KUS_GENERATOR_PORT=1001 KUS_GENERATOR_PORT=1001
\ No newline at end of file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=vkusvill
DB_USERNAME=u
DB_PASSWORD=p
WS_PORT=8080
\ No newline at end of file
...@@ -62,6 +62,8 @@ router.get('/api', async function(req, res) { ...@@ -62,6 +62,8 @@ router.get('/api', async function(req, res) {
res.end(fs.readFileSync('./public/API.html', 'utf-8').replace('$API$', api2html(api))); res.end(fs.readFileSync('./public/API.html', 'utf-8').replace('$API$', api2html(api)));
}); });
//router.use(App.static('public'))
router.all('/', function(req, res) { router.all('/', function(req, res) {
res.end(print(JSON.stringify(data))); res.end(print(JSON.stringify(data)));
...@@ -73,6 +75,7 @@ app.use(function(req, res, next) { ...@@ -73,6 +75,7 @@ app.use(function(req, res, next) {
next(); next();
}); });
app.use(router); app.use(router);
//router.use(App.static('public'))
app.use(App.static('public')) app.use(App.static('public'))
app.use(function(req, res, next) { app.use(function(req, res, next) {
...@@ -84,3 +87,38 @@ try{ ...@@ -84,3 +87,38 @@ try{
console.error(e.message); console.error(e.message);
} }
console.log(`LISTEN port :`+APP_PORT); console.log(`LISTEN port :`+APP_PORT);
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: env.WS_PORT,
perMessageDeflate: {
zlibDeflateOptions: {
// See zlib defaults.
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below which messages
// should not be compressed.
}
});
console.log('WS LISTEN port: '+env.WS_PORT)
global.log = function(type, data){
try{
wss.clients.forEach(function each(client) {
client.send(JSON.stringify({type, data}));
});
}catch (e) {
}
}
\ No newline at end of file
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
"mysql": "^2.18.1", "mysql": "^2.18.1",
"node-async-router": "^0.0.2", "node-async-router": "^0.0.2",
"request": "^2.88.2", "request": "^2.88.2",
"ws": "^7.3.1",
"yargs": "^15.1.0" "yargs": "^15.1.0"
}, },
"scripts": { "scripts": {
......
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Monitor</title>
<script>PCG = {};</script>
<script src="/js/csv.js"></script>
<script src="/js/pcg-dom-util.js"></script>
<script>D = PCG.D</script>
<style>
body {
margin: 0;
height: 100%;
font-family: Verdana;
font-size: 12px;
}
.h1 {
font-size:64px;
text-align: center;
}
#hh2 {
display: none;
height: 100%;
}
.flex {
display: flex;
height: 100%;
}
.log {
min-width: 420px;
max-width: 420px;
height: 100%;
}
.attempts {
width: 100%;
}
.msg {
padding: 2px 8px;
background: #bcdebe;
}
.msg-bold {
font-weight: bold;
margin: 8px;
}
.question {
width: 24px;
height: 24px;
background: #ccc;
margin: 2px;
margin-top: auto;
text-align: center;
}
.questions {
display: flex;
}
.quiz {
padding: 4px;
border-bottom: 1px solid #ccc;
}
.correct {
background: #62ac6e;
}
.incorrect {
background: #ac6862;
}
</style>
</head>
<body>
<div class="h1" id="hh1">404 <span id="s1">страница</span> не <span id="s2">найдена</span></div>
<div id="hh2">
<div class="flex">
<div class="attempts"></div>
<div class="log"><div class="msg">События</div></div>
</div>
</div>
<script>
var code = [0,0,0,0];
(function(w) {
var L = function() {
},
l = L.prototype = {
_plural: function(n) {
return (n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)
},
plural: function(num) {
return arguments[l._plural(num)+1];
}
};
window.Localizer = window.L = new L;
})(window);
var attempts = document.querySelectorAll('.attempts')[0],
log = document.querySelectorAll('.log')[0];
var attemptsHash = {},
questionsHashGlobal = {};
var actions = {
answerQuiz: function(data){
questionsHashGlobal[data.question.id].el.className = 'question '+(data.question.correct?'correct': 'incorrect')
/*
D.div({cls: 'msg', renderTo: log}, D.span({cls: 'msg-bold'}, data.user.name.join(' ')), 'начал тест из',
D.span({cls: 'msg-bold'}, data.question.length), L.plural(data.question.length, 'вопроса','вопросов','вопросов'));
debugger
attemptsHash
questionsHashGlobal*/
},
createQuiz: function (data) {
D.div({cls: 'msg', renderTo: log}, D.span({cls: 'msg-bold'}, data.user.name.join(' ')), 'начал тест из',
D.span({cls: 'msg-bold'}, data.question.length), L.plural(data.question.length, 'вопроса','вопросов','вопросов'));
var questionsHash = {},
questions = [];
data.question.forEach(function (q, i) {
var question = {
el: D.div({cls: 'question'}, i+1),
data: q
};
questionsHash[q.id] = question;
questionsHashGlobal[q.id] = question;
questions.push(question.el)
});
var el = D.div({cls: 'quiz', renderTo: attempts},
D.div({cls: 'attempt'}, data.attempt, ' ', data.user.name.join(' ')),
D.div({cls: 'questions'},
questions
)
);
attemptsHash[ data.attempt ] = {el: el, answers: questionsHash};
}
};
var checkCode = function(){
code = code.slice(1);
if(code.join('91') === '1391666911391666'){
hh1.style.display = 'none';
hh2.style.display = 'block';
let socket = new WebSocket('ws://'+location.hostname+':8080');
socket.onmessage = function(event) {
var data = JSON.parse(event.data);
actions[data.type](data.data);
};
}
};
code = [0,13,666,13,666];
checkCode();
s1.addEventListener('click', function () {
code.push(13);
checkCode();
});
s2.addEventListener('click', function () {
code.push(666);
checkCode();
});
</script>
</body>
</html>
\ No newline at end of file
...@@ -63,6 +63,9 @@ updated_at ...@@ -63,6 +63,9 @@ updated_at
created_at created_at
*/ */
var fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
var mysql = require('mysql'); var mysql = require('mysql');
var pool = mysql.createPool({ var pool = mysql.createPool({
...@@ -126,9 +129,10 @@ module.exports = { ...@@ -126,9 +129,10 @@ module.exports = {
]); ]);
})); }));
var q = await asyncPool('SELECT * from `quiz_question` WHERE id=?', [args.body.quizQuestion]);
if(args.body.currentQuestion === args.body.allQuestions - 1){ if(args.body.currentQuestion === args.body.allQuestions - 1){
// calculations // calculations
var q = await asyncPool('SELECT * from `quiz_question` WHERE id=?', [args.body.quizQuestion]);
if(q && q.length){ if(q && q.length){
var qs = await asyncPool('SELECT * from `quiz_question` WHERE attempt_id=?', [q[0].attempt_id]) var qs = await asyncPool('SELECT * from `quiz_question` WHERE attempt_id=?', [q[0].attempt_id])
var countCorrect = qs.filter(q=>q.user_choice_correct).length; var countCorrect = qs.filter(q=>q.user_choice_correct).length;
...@@ -153,6 +157,12 @@ module.exports = { ...@@ -153,6 +157,12 @@ module.exports = {
console.error('No such attempt'); console.error('No such attempt');
} }
} }
log('answerQuiz', {question: {
id: args.body.quizQuestion,
correct: args.body.user_choice_correct
}});
return {status: 'ok'}; return {status: 'ok'};
} }
}, },
...@@ -208,7 +218,7 @@ module.exports = { ...@@ -208,7 +218,7 @@ module.exports = {
var list = ('text,image,question_time_limit,type,' + var list = ('text,image,question_time_limit,type,' +
'attempt_id,number,card_id,created_at,updated_at').split(','); 'attempt_id,number,card_id,created_at,updated_at').split(',');
q.created_at = q.updated_at = new Date(); q.created_at = q.updated_at = new Date();
console.log('CREATE QUESTION'); //console.log('CREATE QUESTION');
var dbQ = await asyncPool(`INSERT INTO \`quiz_question\` (${list.map(l => '`' + l + '`').join(',')}) VALUES (${list.map(l => '?').join(',')});`, var dbQ = await asyncPool(`INSERT INTO \`quiz_question\` (${list.map(l => '`' + l + '`').join(',')}) VALUES (${list.map(l => '?').join(',')});`,
list.map(l => q[l])); list.map(l => q[l]));
q.id = dbQ.insertId; q.id = dbQ.insertId;
...@@ -218,7 +228,7 @@ module.exports = { ...@@ -218,7 +228,7 @@ module.exports = {
'text,correct,updated_at,created_at').split(','); 'text,correct,updated_at,created_at').split(',');
a.created_at = a.updated_at = new Date(); a.created_at = a.updated_at = new Date();
a.quiz_question_id = q.id; a.quiz_question_id = q.id;
console.log(`CREATE ANSWER ${j}`); //console.log(`CREATE ANSWER ${j}`);
var dbA = await asyncPool(`INSERT INTO \`quiz_answer\` (${list.map(l => '`' + l + '`').join(',')}) VALUES (${list.map(l => '?').join(',')});`, var dbA = await asyncPool(`INSERT INTO \`quiz_answer\` (${list.map(l => '`' + l + '`').join(',')}) VALUES (${list.map(l => '?').join(',')});`,
list.map(l => a[l])); list.map(l => a[l]));
a.id = dbA.insertId; a.id = dbA.insertId;
...@@ -226,6 +236,19 @@ module.exports = { ...@@ -226,6 +236,19 @@ module.exports = {
})) }))
var us = await asyncPool('SELECT * FROM users where id=?;', [
args.body.user_id,
]),
u = us[0];
log('createQuiz', {
user: {
id: args.body.user_id,
name: [u.lastname, u.firstname, u.middlename]
},
attempt: attemptID,
question: qS
});
} catch (e) { } catch (e) {
console.error(e); console.error(e);
throw e; throw e;
...@@ -240,5 +263,16 @@ module.exports = { ...@@ -240,5 +263,16 @@ module.exports = {
} }
},
'/api/quiz/monitor': {
method: 'GET',
options: {},
summary: 'monitor',
fn: async function(args, req, res){
res.header("Content-Type", "text/html; charset=utf-8");
return (await readFile('./public/monitor.html')).toString('utf-8');
}
} }
}; };
\ No newline at end of file
...@@ -1022,6 +1022,11 @@ wrap-ansi@^6.2.0: ...@@ -1022,6 +1022,11 @@ wrap-ansi@^6.2.0:
string-width "^4.1.0" string-width "^4.1.0"
strip-ansi "^6.0.0" strip-ansi "^6.0.0"
ws@^7.3.1:
version "7.3.1"
resolved "https://registry.yarnpkg.com/ws/-/ws-7.3.1.tgz#d0547bf67f7ce4f12a72dfe31262c68d7dc551c8"
integrity sha512-D3RuNkynyHmEJIpD2qrgVkc9DQ23OrN/moAwZX4L8DfvszsJxpjQuUq3LMx6HoYji9fbIOBY18XWBsAux1ZZUA==
xtend@~4.0.1: xtend@~4.0.1:
version "4.0.2" version "4.0.2"
resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment