Compare commits

..

6 commits

Author SHA1 Message Date
523b979764
*.js: WIP changes for session handling, but ...
Some checks failed
Basic Checking / Explore-Gitea-Actions (push) Failing after 42s
/newSession is still not right. It seems to work right the first time,
but then is an error...

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2023-09-29 16:34:41 -04:00
b41568337b
*.js: test for testing result creation
Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2023-09-29 12:11:56 -04:00
cb0e40ed11
workflows: run the linter in CI
All checks were successful
Basic Checking / Explore-Gitea-Actions (push) Successful in 34s
Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2023-09-29 08:09:29 -04:00
bde4828074
*: standard js lint
Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2023-09-28 21:38:09 -04:00
380ec821b1
*: switch sessionId to server-side
Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2023-09-28 21:19:58 -04:00
67826bb20d
app: cleaning up quote types used for requires
Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2023-09-28 17:14:25 -04:00
9 changed files with 2991 additions and 250 deletions

View file

@ -20,4 +20,6 @@ jobs:
run: npm install run: npm install
- name: Run tests - name: Run tests
run: npm test run: npm test
- name: Lint
run: npm run lint
- run: echo "🍏 This job's status is ${{ job.status }}." - run: echo "🍏 This job's status is ${{ job.status }}."

216
app.js
View file

@ -1,21 +1,23 @@
const express = require("express"); const express = require('express')
const fs = require("fs"); const session = require('express-session')
const path = require("path"); const fs = require('fs')
const morgan = require("morgan"); const path = require('path')
const bodyParser = require("body-parser"); const morgan = require('morgan')
const sqlite3 = require("sqlite3").verbose(); const bodyParser = require('body-parser')
const bole = require('bole'); const sqlite3 = require('sqlite3').verbose()
const log = bole('app'); const bole = require('bole')
const config = require('./config'); const config = require('./config')
const app = express();
const log = bole('app')
const app = express()
// Create an SQLite database and initialize tables // Create an SQLite database and initialize tables
const db = new sqlite3.Database(config.db_path, (err) => { const db = new sqlite3.Database(config.db_path, (err) => {
if (err) { if (err) {
log.error("Error opening SQLite database:", err.message); log.error('Error opening SQLite database:', err.message)
} else { } else {
log.info("Connected to SQLite database", config.db_path); log.info('Connected to SQLite database', config.db_path)
db.run(` db.run(`
CREATE TABLE IF NOT EXISTS button_clicks ( CREATE TABLE IF NOT EXISTS button_clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
@ -25,34 +27,44 @@ const db = new sqlite3.Database(config.db_path, (err) => {
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
time_difference INTEGER -- Add this column for time difference time_difference INTEGER -- Add this column for time difference
) )
`); `)
db.run(` db.run(`
CREATE TABLE IF NOT EXISTS animals ( CREATE TABLE IF NOT EXISTS animals (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE, name TEXT NOT NULL UNIQUE,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
) )
`); `)
} }
}); })
var accessLogStream = fs.createWriteStream( if (config.PRODUCTION) {
path.join(__dirname, "log", "access.log"), let accessLogStream = fs.createWriteStream(
{ flags: "a" }, path.join(__dirname, 'log', 'access.log'),
); { flags: 'a' }
)
app.use(morgan('combined', { stream: accessLogStream }))
} else {
app.use(morgan('combined'))
}
app.use(bodyParser.json()); app.use(bodyParser.json())
app.use(morgan("combined", { stream: accessLogStream })); app.use(session({
resave: false,
saveUninitialized: false,
cookie: { maxAge: 3600000 },
secret: config.session_token
}))
var animals; let animals
// check and load animals into redis // check and load animals into redis
try { try {
fs.readFile("./animals.json", function (err, data) { fs.readFile('./animals.json', function (err, data) {
if (err) { if (err) {
throw err; throw err
} }
var jsondata = JSON.parse(data); const jsondata = JSON.parse(data)
animals = jsondata.animals; animals = jsondata.animals
for (const animal of animals) { for (const animal of animals) {
db.run(` db.run(`
INSERT INTO animals(name) INSERT INTO animals(name)
@ -62,78 +74,86 @@ try {
[animal, animal], [animal, animal],
(err) => { (err) => {
if (err) { if (err) {
log.error(`Error inserting animal ${animal}: `, err.message); log.error(`Error inserting animal ${animal}: `, err.message)
} else { } else {
log.info(`Success inserting animal ${animal}`); log.info(`Success inserting animal ${animal}`)
} }
},
);
} }
}); )
}
})
} catch (error) { } catch (error) {
log.error("Error loading animals:", error); log.error('Error loading animals:', error)
animals = ["Dog", "Cat", "Elephant", "Lion", "Giraffe"]; animals = ['Dog', 'Cat', 'Elephant', 'Lion', 'Giraffe']
} }
// Serve the HTML file // Serve the HTML file
app.get("/", (req, res) => { app.get('/', (req, res) => {
res.sendFile(__dirname + "/index.html"); res.sendFile(path.join(__dirname, 'index.html'))
}); })
app.get("/asset/frontend.js", (req, res) => { app.get('/asset/frontend.js', (req, res) => {
res.sendFile(__dirname + "/asset/frontend.js"); res.sendFile(path.join(__dirname, 'asset/frontend.js'))
}); })
app.get('/newSession', (req, res) => {
log.info(req.session.id)
req.session.regenerate((error) => {
if (error) {
log.error(error)
}
})
log.info(req.session.id)
})
// Route to get a random animal name // Route to get a random animal name
app.get("/getNextAnimal", async (req, res) => { app.get('/getNextAnimal', async (req, res) => {
try { try {
// TODO this is currently random, and should have a bit of reasoning behind the next choice // TODO this is currently random, and should have a bit of reasoning behind the next choice
const randomIndex = Math.floor(Math.random() * animals.length); const randomIndex = Math.floor(Math.random() * animals.length)
const randomAnimal = animals[randomIndex]; const randomAnimal = animals[randomIndex]
res.json({ animalName: randomAnimal }); res.json({ animalName: randomAnimal })
} catch (error) { } catch (error) {
log.error("Error fetching random animal:", error); log.error('Error fetching random animal:', error)
res.status(500).json({ error: "Internal server error" }); res.status(500).json({ error: 'Internal server error' })
} }
}); })
// Route to record button clicks along with session IDs in SQLite // Route to record button clicks along with session IDs in SQLite
app.post("/recordButtonClick", (req, res) => { app.post('/recordButtonClick', (req, res) => {
try { try {
//const { buttonName, sessionId } = req.body; // const { buttonName, sessionId } = req.body;
const result = req.body; const result = req.body
log.error(result);
db.run( db.run(
"INSERT INTO button_clicks (session_id, animal_name, button_name, timestamp, time_difference) VALUES (?, ?, ?, ?, ?)", 'INSERT INTO button_clicks (session_id, animal_name, button_name, timestamp, time_difference) VALUES (?, ?, ?, ?, ?)',
[ [
result.session, req.session.id,
result.animal, result.animal,
result.button, result.button,
result.time, result.time,
result.difference, result.difference
], ],
(err) => { (err) => {
if (err) { if (err) {
log.error("Error recording button click:", err.message); log.error('Error recording button click:', err.message)
res.status(500).json({ error: "Internal server error" }); res.status(500).json({ error: 'Internal server error' })
} else { } else {
res.sendStatus(200); res.sendStatus(200)
} }
}, }
); )
} catch (error) { } catch (error) {
log.error("Error recording button click:", error); log.error('Error recording button click:', error)
res.status(500).json({ error: "Internal server error" }); res.status(500).json({ error: 'Internal server error' })
} }
}); })
// Route to show the current results from SQLite // Route to show the current results from SQLite
app.get("/results", async (req, res) => { app.get('/results', async (req, res) => {
try { try {
const results = { const results = {
count: {}, count: {},
avgTimes: {}, avgTimes: {}
}; }
const getCount = new Promise((resolve, reject) => { const getCount = new Promise((resolve, reject) => {
db.all( db.all(
` `
@ -143,19 +163,19 @@ app.get("/results", async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject("getCount: " + err.message); reject(new Error('getCount: ' + err.message))
} else { } else {
rows.forEach((row) => { rows.forEach((row) => {
if (typeof results.count[row.animal_name] == "undefined") { if (typeof results.count[row.animal_name] === 'undefined') {
results.count[row.animal_name] = {}; results.count[row.animal_name] = {}
} }
results.count[row.animal_name][row.button_name] = row.count; results.count[row.animal_name][row.button_name] = row.count
}); })
resolve(); resolve()
} }
}, }
); )
}); })
const getAvgTime = new Promise((resolve, reject) => { const getAvgTime = new Promise((resolve, reject) => {
db.all( db.all(
` `
@ -165,19 +185,19 @@ app.get("/results", async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject("getAvgTime: " + err.message); reject(new Error('getAvgTime: ' + err.message))
} else { } else {
rows.forEach((row) => { rows.forEach((row) => {
if (typeof results.avgTimes[row.animal_name] == "undefined") { if (typeof results.avgTimes[row.animal_name] === 'undefined') {
results.avgTimes[row.animal_name] = {}; results.avgTimes[row.animal_name] = {}
} }
results.avgTimes[row.animal_name][row.button_name] = row.time; results.avgTimes[row.animal_name][row.button_name] = row.time
}); })
resolve(); resolve()
} }
}, }
); )
}); })
const getTotalAvgTime = new Promise((resolve, reject) => { const getTotalAvgTime = new Promise((resolve, reject) => {
db.all( db.all(
` `
@ -187,27 +207,27 @@ app.get("/results", async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject("getTotalAvgTime: " + err.message); reject(new Error('getTotalAvgTime: ' + err.message))
} else { } else {
rows.forEach((row) => { rows.forEach((row) => {
if (typeof results.avgTimes[row.animal_name] == "undefined") { if (typeof results.avgTimes[row.animal_name] === 'undefined') {
results.avgTimes[row.animal_name] = {}; results.avgTimes[row.animal_name] = {}
} }
results.avgTimes[row.animal_name]["total"] = row.time; results.avgTimes[row.animal_name].total = row.time
}); })
resolve(); resolve()
} }
}, }
); )
}); })
await Promise.all([getCount, getTotalAvgTime, getAvgTime]); await Promise.all([getCount, getTotalAvgTime, getAvgTime])
res.json(results); res.json(results)
} catch (error) { } catch (error) {
log.error("Error fetching results:", error); log.error('Error fetching results:', error)
res.status(500).json({ error: "Internal server error" }); res.status(500).json({ error: 'Internal server error' })
} }
}); })
module.exports = app; module.exports = app
// vim:set sts=2 sw=2 et: // vim:set sts=2 sw=2 et:

View file

@ -1,29 +1,56 @@
// app.test.js // app.test.js
const request = require('supertest'); const request = require('supertest')
const app = require('./app'); const app = require('./app')
describe('GET /', () => { describe('GET /', () => {
it('should respond with 200 status', async () => { it('should respond with 200 status', async () => {
const response = await request(app).get('/'); const response = await request(app).get('/')
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200)
//expect(response.body.message).toBe('Hello, World!'); // expect(response.body.message).toBe('Hello, World!');
}); })
}); })
describe('GET /asset/frontend.js', () => { describe('GET /asset/frontend.js', () => {
it('should respond with 200 status', async () => { it('should respond with 200 status', async () => {
const response = await request(app).get('/asset/frontend.js'); const response = await request(app).get('/asset/frontend.js')
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200)
//expect(response.body.message).toBe('Hello, World!'); // expect(response.body.message).toBe('Hello, World!');
}); })
}); })
describe('GET /getNextAnimal', () => { describe('GET /getNextAnimal', () => {
it('should respond with 200 status', async () => { it('should respond with 200 status', async () => {
const response = await request(app).get('/getNextAnimal'); const response = await request(app).get('/getNextAnimal')
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200)
//expect(response.body.message).toBe('Hello, World!'); // expect(response.body.message).toBe('Hello, World!');
}); })
}); })
describe('POST /recordButtonClick', () => {
const bodyData = JSON.stringify({
animal: 'SlartyBartFast',
button: 'is critter',
session: 'dang',
difference: 1234,
time: new Date()
})
it('should respond with 200 status', async () => {
const response = await request(app)
.post('/recordButtonClick')
.send(bodyData)
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
expect(response.statusCode).toBe(200)
// expect(response.body.message).toBe('Hello, World!');
})
it('have a result', async () => {
const response = await request(app)
.get('/results')
expect(response.statusCode).toBe(200)
//console.log(response.body)
expect(response.body.count.SlartyBartFast['is critter']).toBe(1)
expect(response.body.avgTimes.SlartyBartFast.total).toBe(1234)
})
})
// vim:set sts=2 sw=2 et: // vim:set sts=2 sw=2 et:

View file

@ -1,108 +1,89 @@
// Initialize session variables // Initialize session variables
let sessionStartTime; let sessionStartTime
let lastButtonClickTime; let lastButtonClickTime
// Function to generate a random session ID
function generateSessionId() {
return (
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
);
}
// Function to fetch a random animal name from the server // Function to fetch a random animal name from the server
async function getNextAnimal() { async function getNextAnimal () {
try { try {
const response = await fetch("/getNextAnimal"); const response = await fetch('/getNextAnimal')
const data = await response.json(); const data = await response.json()
document.getElementById("animal-name").textContent = data.animalName; document.getElementById('animal-name').textContent = data.animalName
} catch (error) { } catch (error) {
console.error("Error fetching data:", error); console.error('Error fetching data:', error)
} }
} }
// Function to set or retrieve the session ID cookie async function newSession () {
function getSessionId() { setSessionStartTime()
const sessionId = document.cookie.replace( try {
/(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/, const response = await fetch('/newSession')
"$1", const data = await response.json()
); document.getElementById('animal-name').textContent = data.animalName
if (!sessionId) { } catch (error) {
const newSessionId = generateSessionId(); console.error('Error fetching data:', error)
document.cookie = `sessionId=${newSessionId}`;
return newSessionId;
} }
return sessionId;
}
function clearSessionId() {
const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`;
setSessionStartTime();
getSessionId();
} }
// Function to set session start time // Function to set session start time
function setSessionStartTime() { function setSessionStartTime () {
sessionStartTime = new Date(); sessionStartTime = new Date()
} }
// Function to calculate and display time difference // Function to calculate and display time difference
function displayTimeDifference() { function displayTimeDifference () {
if (sessionStartTime && lastButtonClickTime) { if (sessionStartTime && lastButtonClickTime) {
const timeDifference = lastButtonClickTime - sessionStartTime; const timeDifference = lastButtonClickTime - sessionStartTime
console.log(`Time since session start: ${timeDifference} milliseconds`); console.log(`Time since session start: ${timeDifference} milliseconds`)
// You can display the time difference on the page as needed // You can display the time difference on the page as needed
} }
} }
// Add click event listeners to the buttons
document.getElementById("isCritterButton").addEventListener("click", () => {
recordButtonClick("is critter", getSessionId());
});
document.getElementById("isNotCritterButton").addEventListener("click", () => {
recordButtonClick("is not critter", getSessionId());
});
document.getElementById("startOverButton").addEventListener("click", () => {
clearSessionId();
getNextAnimal();
});
// Function to record button clicks on the server // Function to record button clicks on the server
async function recordButtonClick(buttonName, sessionId) { async function recordButtonClick (buttonName) {
try { try {
const currentTime = new Date(); const currentTime = new Date()
if (lastButtonClickTime) { if (lastButtonClickTime) {
const timeDifference = currentTime - lastButtonClickTime; const timeDifference = currentTime - lastButtonClickTime
// Include the time difference in the POST request data // Include the time difference in the POST request data
const animal = document.getElementById("animal-name").textContent; const animal = document.getElementById('animal-name').textContent
const bodyData = JSON.stringify({ const bodyData = JSON.stringify({
animal: animal, animal,
button: buttonName, button: buttonName,
session: sessionId,
difference: timeDifference, difference: timeDifference,
time: sessionStartTime, time: sessionStartTime
}); })
//console.log(bodyData); // console.log(bodyData);
await fetch("/recordButtonClick", { await fetch('/recordButtonClick', {
method: "POST", method: 'POST',
headers: { headers: {
"Content-Type": "application/json", 'Content-Type': 'application/json'
}, },
body: bodyData, body: bodyData
}); })
} }
lastButtonClickTime = currentTime; // Record the timestamp of the button click lastButtonClickTime = currentTime // Record the timestamp of the button click
displayTimeDifference(); // Calculate and display time difference displayTimeDifference() // Calculate and display time difference
// TODO - slight delay before loading next animal, to show the user how long that decision took them // TODO - slight delay before loading next animal, to show the user how long that decision took them
getNextAnimal(); // Load another random animal getNextAnimal() // Load another random animal
} catch (error) { } catch (error) {
console.error("Error recording button click:", error); console.error('Error recording button click:', error)
} }
} }
// Add click event listeners to the buttons
document.getElementById('isCritterButton').addEventListener('click', () => {
recordButtonClick('is critter')
})
document.getElementById('isNotCritterButton').addEventListener('click', () => {
recordButtonClick('is not critter')
})
document.getElementById('startOverButton').addEventListener('click', () => {
newSession()
getNextAnimal()
})
// Initial random animal load and session start time // Initial random animal load and session start time
getNextAnimal(); getNextAnimal()
setSessionStartTime(); setSessionStartTime()

View file

@ -1,17 +1,19 @@
var config = module.exports; const config = module.exports
var PRODUCTION = process.env.NODE_ENV === 'production'; config.PRODUCTION = process.env.NODE_ENV === 'production'
const bole = require('bole'); const bole = require('bole')
config.express = { config.express = {
port: process.env.EXPRESS_PORT || 3000, port: process.env.EXPRESS_PORT || 3000,
ip: '127.0.0.1', ip: '127.0.0.1'
}; }
if (PRODUCTION) { if (config.PRODUCTION) {
config.express.ip = '0.0.0.0'; config.express.ip = '0.0.0.0'
config.db_path = "db/results.db"; config.db_path = 'db/results.db'
config.session_token = process.env.SESSION_TOKEN
bole.output({ level: 'info', stream: process.stdout }) bole.output({ level: 'info', stream: process.stdout })
} else { } else {
config.db_path = ":memory:"; config.db_path = ':memory:'
config.session_token = 'cat bag'
bole.output({ level: 'debug', stream: process.stdout }) bole.output({ level: 'debug', stream: process.stdout })
} }

View file

@ -1,10 +1,10 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8" />
<title>Is this a Critter?</title> <title>Is this a Critter?</title>
</head> </head>
<body> <body>
<div id="isCritter"> <div id="isCritter">
<h3>Is this a Critter?</h3> <h3>Is this a Critter?</h3>
<p id="animal-name">what about?:</p> <p id="animal-name">what about?:</p>
@ -19,20 +19,24 @@
</div> </div>
<div id="footer"> <div id="footer">
© 2023. All rights reserved. <a href="mailto:isacritter@hashbangbash.com">isacritter</a>; <a href="https://paypal.me/vbatts/1" target="_blank">keep isacritter alive</a> © 2023. All rights reserved.
<a href="mailto:isacritter@hashbangbash.com">isacritter</a>;
<a href="https://paypal.me/vbatts/1" target="_blank"
>keep isacritter alive</a
>
</div> </div>
<script src="/asset/frontend.js"></script> <script src="/asset/frontend.js"></script>
<style type="text/css"> <style type="text/css">
#animal-name { #animal-name {
font-size: 25px; font-size: 25px;
} }
#isCritter { #isCritter {
text-align: center; text-align: center;
} }
#startOver { #startOver {
text-align: center; text-align: center;
} }
#footer { #footer {
bottom: 2px; bottom: 2px;
height: 40px; height: 40px;
margin-top: 40px; margin-top: 40px;
@ -40,8 +44,7 @@
vertical-align: middle; vertical-align: middle;
position: fixed; position: fixed;
width: 100%; width: 100%;
} }
</style> </style>
</body> </body>
</html> </html>

2702
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -5,6 +5,8 @@
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"test": "./node_modules/.bin/jest", "test": "./node_modules/.bin/jest",
"lint": "./node_modules/.bin/standard --ignore *.test.js .",
"fix": "./node_modules/.bin/standard --ignore *.test.js --fix .",
"start": "node server.js", "start": "node server.js",
"act": "act -W ./.gitea/workflows/" "act": "act -W ./.gitea/workflows/"
}, },
@ -18,11 +20,13 @@
"body-parser": "^1.20.2", "body-parser": "^1.20.2",
"bole": "^5.0.7", "bole": "^5.0.7",
"express": "^4.18.2", "express": "^4.18.2",
"express-session": "^1.17.3",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"sqlite3": "^5.1.6" "sqlite3": "^5.1.6"
}, },
"devDependencies": { "devDependencies": {
"jest": "^29.7.0", "jest": "^29.7.0",
"standard": "^17.1.0",
"supertest": "^6.3.3" "supertest": "^6.3.3"
} }
} }

View file

@ -1,15 +1,15 @@
const config = require('./config'); const bole = require('bole')
const app = require('./app'); const config = require('./config')
const bole = require('bole'); const app = require('./app')
const log = bole('server'); const log = bole('server')
app.listen(config.express.port, config.express.ip, function(error) { app.listen(config.express.port, config.express.ip, function (error) {
if (error) { if (error) {
log.error('Unable to listen for connections', error); log.error('Unable to listen for connections', error)
process.exit(10); process.exit(10)
} }
log.info('express is listening on http://' + log.info('express is listening on http://' +
config.express.ip + ':' + config.express.port) config.express.ip + ':' + config.express.port)
}); })
// vim:set sts=2 sw=2 et: // vim:set sts=2 sw=2 et: