]> git.cworth.org Git - zombocom-ai/blobdiff - index.js
Add a welcome stage to the TARDIS
[zombocom-ai] / index.js
index 04fe9bb0c65152eb1537d98a08e2315ca3430655..1fa214bdb28ef79e512980de989f12d40f75e94a 100644 (file)
--- a/index.js
+++ b/index.js
@@ -95,7 +95,16 @@ io.use(wrap(session_middleware));
 // Load comments at server startup
 fs.readFile(state_file, (err, data) => {
     if (err)
-        state = { images: [], targets: [] };
+        state = {
+           images: [],
+           targets: [],
+           tardis: {
+               companions: {
+                   names: [],
+                   count: 0
+               }
+           }
+       };
     else
         state = JSON.parse(data);
 });
@@ -128,6 +137,58 @@ function tardis_app(req, res) {
 app.get('/tardis', tardis_app);
 app.get('/tardis/', tardis_app);
 
+const io_tardis = io.of("/tardis");
+
+io_tardis.use(wrap(session_middleware));
+
+var tardis_interval;
+
+function emit_tardis_timer() {
+    const tardis = state.tardis;
+    console.log("Emitting timer at " + tardis.timer);
+    io_tardis.emit('timer', tardis.timer);
+    tardis.timer = tardis.timer - 1;
+    if (tardis.timer < 0) {
+       clearInterval(tardis_interval);
+       tardis.timer = 30;
+    }
+}
+
+io_tardis.on("connection", (socket) => {
+    console.log("In connection handler.");
+    if (! socket.request.session.name) {
+       console.log("Error: Someone showed up at the Tardis without a name.");
+       return;
+    }
+
+    const name = socket.request.session.name;
+    const tardis = state.tardis;
+
+    if (tardis.companions.count === 0) {
+       tardis.timer = 30;
+       emit_tardis_timer();
+       tardis_interval = setInterval(emit_tardis_timer, 1000);
+    }
+
+    if (! tardis.companions.names.includes(name)) {
+       tardis.companions.count = tardis.companions.count + 1;
+       console.log("Adding " + name + " for " + tardis.companions.count + " companions");
+       io_tardis.emit('companions', tardis.companions.count);
+    }
+    tardis.companions.names.push(name);
+
+    socket.on('disconnect', () => {
+       const names = tardis.companions.names;
+
+       names.splice(names.indexOf(name), 1);
+
+       if (! tardis.companions.includes(name)) {
+           tardis.companions.count = tardis.companions.count - 1;
+           io_tardis.emit('companions', tardis.companions.count);
+       }
+    });
+});
+
 io.on('connection', (socket) => {
 
     // First things first, tell the client their name (if any)