Compare commits

..

No commits in common. "session" and "main" have entirely different histories.

9 changed files with 250 additions and 2991 deletions

View file

@ -20,6 +20,4 @@ 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 }}."

226
app.js
View file

@ -1,23 +1,21 @@
const express = require('express') const express = require("express");
const session = require('express-session') const fs = require("fs");
const fs = require('fs') const path = require("path");
const path = require('path') const morgan = require("morgan");
const morgan = require('morgan') const bodyParser = require("body-parser");
const bodyParser = require('body-parser') const sqlite3 = require("sqlite3").verbose();
const sqlite3 = require('sqlite3').verbose() const bole = require('bole');
const bole = require('bole') const log = bole('app');
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,
@ -27,133 +25,115 @@ 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
) )
`) `);
} }
}) });
if (config.PRODUCTION) { var accessLogStream = fs.createWriteStream(
let accessLogStream = fs.createWriteStream( path.join(__dirname, "log", "access.log"),
path.join(__dirname, 'log', 'access.log'), { flags: "a" },
{ flags: 'a' } );
)
app.use(morgan('combined', { stream: accessLogStream }))
} else {
app.use(morgan('combined'))
}
app.use(bodyParser.json()) app.use(bodyParser.json());
app.use(session({ app.use(morgan("combined", { stream: accessLogStream }));
resave: false,
saveUninitialized: false,
cookie: { maxAge: 3600000 },
secret: config.session_token
}))
let animals var 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;
} }
const jsondata = JSON.parse(data) var 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)
SELECT ? SELECT ?
WHERE NOT EXISTS(SELECT 1 FROM animals WHERE name = ?); WHERE NOT EXISTS(SELECT 1 FROM animals WHERE name = ?);
`, `,
[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(path.join(__dirname, 'index.html')) res.sendFile(__dirname + "/index.html");
}) });
app.get('/asset/frontend.js', (req, res) => { app.get("/asset/frontend.js", (req, res) => {
res.sendFile(path.join(__dirname, 'asset/frontend.js')) res.sendFile(__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 (?, ?, ?, ?, ?)",
[ [
req.session.id, result.session,
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(
` `
@ -163,19 +143,19 @@ app.get('/results', async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject(new Error('getCount: ' + err.message)) reject("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(
` `
@ -185,19 +165,19 @@ app.get('/results', async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject(new Error('getAvgTime: ' + err.message)) reject("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(
` `
@ -207,27 +187,27 @@ app.get('/results', async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject(new Error('getTotalAvgTime: ' + err.message)) reject("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,56 +1,29 @@
// 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,89 +1,108 @@
// 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);
} }
} }
async function newSession () { // Function to set or retrieve the session ID cookie
setSessionStartTime() function getSessionId() {
try { const sessionId = document.cookie.replace(
const response = await fetch('/newSession') /(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/,
const data = await response.json() "$1",
document.getElementById('animal-name').textContent = data.animalName );
} catch (error) { if (!sessionId) {
console.error('Error fetching data:', error) const newSessionId = generateSessionId();
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) { async function recordButtonClick(buttonName, sessionId) {
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,19 +1,17 @@
const config = module.exports var config = module.exports;
config.PRODUCTION = process.env.NODE_ENV === 'production' var 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 (config.PRODUCTION) { if (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,50 +1,47 @@
<!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>
<button id="isCritterButton">Is Critter</button> <button id="isCritterButton">Is Critter</button>
<button id="isNotCritterButton">Is <b>not</b> Critter</button> <button id="isNotCritterButton">Is <b>not</b> Critter</button>
</div> </div>
<div id="startOver"> <div id="startOver">
<p> <p>
<button id="startOverButton">Start over</button> <button id="startOverButton">Start over</button>
</p> </p>
</div> </div>
<div id="footer"> <div id="footer">
© 2023. All rights reserved. © 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>
<a href="mailto:isacritter@hashbangbash.com">isacritter</a>; </div>
<a href="https://paypal.me/vbatts/1" target="_blank" <script src="/asset/frontend.js"></script>
>keep isacritter alive</a <style type="text/css">
> #animal-name {
</div> font-size: 25px;
<script src="/asset/frontend.js"></script> }
<style type="text/css"> #isCritter {
#animal-name { text-align: center;
font-size: 25px; }
} #startOver {
#isCritter { text-align: center;
text-align: center; }
} #footer {
#startOver { bottom: 2px;
text-align: center; height: 40px;
} margin-top: 40px;
#footer { text-align: center;
bottom: 2px; vertical-align: middle;
height: 40px; position: fixed;
margin-top: 40px; width: 100%;
text-align: center; }
vertical-align: middle; </style>
position: fixed; </body>
width: 100%;
}
</style>
</body>
</html> </html>

2702
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -5,8 +5,6 @@
"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/"
}, },
@ -20,13 +18,11 @@
"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 bole = require('bole') const config = require('./config');
const config = require('./config') const app = require('./app');
const app = require('./app') const bole = require('bole');
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: