]> git.cworth.org Git - zombocom-ai/blobdiff - index.js
Send along the user's name with each comment made
[zombocom-ai] / index.js
index 638c59dc6543fbab851e179d9b59b74aa123c51c..1239ea2fab43360d621942d40ecd95cacced79f3 100644 (file)
--- a/index.js
+++ b/index.js
@@ -5,6 +5,8 @@ const execFile = util.promisify(require('child_process').execFile);
 
 const express = require('express');
 const app = express();
+const session = require('express-session');
+const FileStore = require('session-file-store')(session);
 const http = require('http');
 const server = http.createServer(app);
 const { Server } = require("socket.io");
@@ -17,6 +19,26 @@ const state_file = 'zombocom-state.json'
 
 var state;
 
+if (!process.env.ZOMBOCOM_SESSION_SECRET) {
+    console.log("Error: Environment variable ZOMBOCOM_SESSION_SECRET not set.");
+    console.log("Please set it to a random, but persistent, value.")
+    process.exit();
+}
+
+const session_middleware =  session(
+    {store: new FileStore,
+     secret: process.env.ZOMBOCOM_SESSION_SECRET,
+     resave: false,
+     saveUninitialized: true
+    });
+
+app.use(session_middleware);
+
+// convert a connect middleware to a Socket.IO middleware
+const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
+
+io.use(wrap(session_middleware));
+
 // Load comments at server startup
 fs.readFile(state_file, (err, data) => {
     if (err)
@@ -48,7 +70,13 @@ app.get('/index.html', (req, res) => {
 
 io.on('connection', (socket) => {
 
+    // First things first, tell the client their name (if any)
+    if (socket.request.session.name) {
+        socket.emit('inform-name', socket.request.session.name);
+    }
+
     // Replay old comments and images to a newly-joining client
+    socket.emit('reset');
     state.comments.forEach((comment) => {
         socket.emit('comment', comment)
     });
@@ -56,8 +84,16 @@ io.on('connection', (socket) => {
         socket.emit('image', image)
     });
 
+    socket.on('set-name', (name) => {
+        console.log("Received set-name event: " + name);
+        socket.request.session.name = name;
+        socket.request.session.save();
+    });
+
     // When any client comments, send that to all clients (including sender)
-    socket.on('comment', (comment) => {
+    socket.on('comment', (comment_text) => {
+        comment = { name: socket.request.session.name,
+                    text: comment_text }
         io.emit('comment', comment);
         state.comments.push(comment);
     });