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
- name: Run tests
run: npm test
- name: Lint
run: npm run lint
- run: echo "🍏 This job's status is ${{ job.status }}."

226
app.js
View file

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

View file

@ -1,29 +1,56 @@
// app.test.js
const request = require('supertest');
const app = require('./app');
const request = require('supertest')
const app = require('./app')
describe('GET /', () => {
it('should respond with 200 status', async () => {
const response = await request(app).get('/');
expect(response.statusCode).toBe(200);
//expect(response.body.message).toBe('Hello, World!');
});
});
const response = await request(app).get('/')
expect(response.statusCode).toBe(200)
// expect(response.body.message).toBe('Hello, World!');
})
})
describe('GET /asset/frontend.js', () => {
it('should respond with 200 status', async () => {
const response = await request(app).get('/asset/frontend.js');
expect(response.statusCode).toBe(200);
//expect(response.body.message).toBe('Hello, World!');
});
});
const response = await request(app).get('/asset/frontend.js')
expect(response.statusCode).toBe(200)
// expect(response.body.message).toBe('Hello, World!');
})
})
describe('GET /getNextAnimal', () => {
it('should respond with 200 status', async () => {
const response = await request(app).get('/getNextAnimal');
expect(response.statusCode).toBe(200);
//expect(response.body.message).toBe('Hello, World!');
});
});
const response = await request(app).get('/getNextAnimal')
expect(response.statusCode).toBe(200)
// 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:

View file

@ -1,108 +1,89 @@
// Initialize session variables
let sessionStartTime;
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)
);
}
let sessionStartTime
let lastButtonClickTime
// Function to fetch a random animal name from the server
async function getNextAnimal() {
async function getNextAnimal () {
try {
const response = await fetch("/getNextAnimal");
const data = await response.json();
document.getElementById("animal-name").textContent = data.animalName;
const response = await fetch('/getNextAnimal')
const data = await response.json()
document.getElementById('animal-name').textContent = data.animalName
} catch (error) {
console.error("Error fetching data:", error);
console.error('Error fetching data:', error)
}
}
// Function to set or retrieve the session ID cookie
function getSessionId() {
const sessionId = document.cookie.replace(
/(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/,
"$1",
);
if (!sessionId) {
const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`;
return newSessionId;
async function newSession () {
setSessionStartTime()
try {
const response = await fetch('/newSession')
const data = await response.json()
document.getElementById('animal-name').textContent = data.animalName
} catch (error) {
console.error('Error fetching data:', error)
}
return sessionId;
}
function clearSessionId() {
const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`;
setSessionStartTime();
getSessionId();
}
// Function to set session start time
function setSessionStartTime() {
sessionStartTime = new Date();
function setSessionStartTime () {
sessionStartTime = new Date()
}
// Function to calculate and display time difference
function displayTimeDifference() {
function displayTimeDifference () {
if (sessionStartTime && lastButtonClickTime) {
const timeDifference = lastButtonClickTime - sessionStartTime;
console.log(`Time since session start: ${timeDifference} milliseconds`);
const timeDifference = lastButtonClickTime - sessionStartTime
console.log(`Time since session start: ${timeDifference} milliseconds`)
// 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
async function recordButtonClick(buttonName, sessionId) {
async function recordButtonClick (buttonName) {
try {
const currentTime = new Date();
const currentTime = new Date()
if (lastButtonClickTime) {
const timeDifference = currentTime - lastButtonClickTime;
const timeDifference = currentTime - lastButtonClickTime
// 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({
animal: animal,
animal,
button: buttonName,
session: sessionId,
difference: timeDifference,
time: sessionStartTime,
});
//console.log(bodyData);
await fetch("/recordButtonClick", {
method: "POST",
time: sessionStartTime
})
// console.log(bodyData);
await fetch('/recordButtonClick', {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Content-Type': 'application/json'
},
body: bodyData,
});
body: bodyData
})
}
lastButtonClickTime = currentTime; // Record the timestamp of the button click
displayTimeDifference(); // Calculate and display time difference
lastButtonClickTime = currentTime // Record the timestamp of the button click
displayTimeDifference() // Calculate and display time difference
// 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) {
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
getNextAnimal();
setSessionStartTime();
getNextAnimal()
setSessionStartTime()

View file

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

View file

@ -1,47 +1,50 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<head>
<meta charset="UTF-8" />
<title>Is this a Critter?</title>
</head>
<body>
<div id="isCritter">
<h3>Is this a Critter?</h3>
<p id="animal-name">what about?:</p>
<button id="isCritterButton">Is Critter</button>
<button id="isNotCritterButton">Is <b>not</b> Critter</button>
</div>
</head>
<body>
<div id="isCritter">
<h3>Is this a Critter?</h3>
<p id="animal-name">what about?:</p>
<button id="isCritterButton">Is Critter</button>
<button id="isNotCritterButton">Is <b>not</b> Critter</button>
</div>
<div id="startOver">
<p>
<button id="startOverButton">Start over</button>
</p>
</div>
<div id="startOver">
<p>
<button id="startOverButton">Start over</button>
</p>
</div>
<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>
</div>
<script src="/asset/frontend.js"></script>
<style type="text/css">
#animal-name {
font-size: 25px;
}
#isCritter {
text-align: center;
}
#startOver {
text-align: center;
}
#footer {
bottom: 2px;
height: 40px;
margin-top: 40px;
text-align: center;
vertical-align: middle;
position: fixed;
width: 100%;
}
</style>
</body>
<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
>
</div>
<script src="/asset/frontend.js"></script>
<style type="text/css">
#animal-name {
font-size: 25px;
}
#isCritter {
text-align: center;
}
#startOver {
text-align: center;
}
#footer {
bottom: 2px;
height: 40px;
margin-top: 40px;
text-align: center;
vertical-align: middle;
position: fixed;
width: 100%;
}
</style>
</body>
</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",
"scripts": {
"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",
"act": "act -W ./.gitea/workflows/"
},
@ -18,11 +20,13 @@
"body-parser": "^1.20.2",
"bole": "^5.0.7",
"express": "^4.18.2",
"express-session": "^1.17.3",
"morgan": "^1.10.0",
"sqlite3": "^5.1.6"
},
"devDependencies": {
"jest": "^29.7.0",
"standard": "^17.1.0",
"supertest": "^6.3.3"
}
}

View file

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