]> git.cworth.org Git - zombocom-ai/blob - index.js
249537fd3414cd2541b16513901ab6eaeb68359a
[zombocom-ai] / index.js
1 const fs = require('fs');
2
3 const express = require('express');
4 const app = express();
5 const http = require('http');
6 const server = http.createServer(app);
7 const { Server } = require("socket.io");
8 const io = new Server(server);
9 const port = 2122;
10
11 const state_file = 'zombocom-state.json'
12
13 var comments;
14
15 // Load comments at server startup
16 fs.readFile(state_file, (err, data) => {
17     if (err)
18         comments = [];
19     else
20         comments = JSON.parse(data);
21 });
22
23 // Save comments when server is shutting down
24 function cleanup() {
25     fs.writeFileSync('zombocom-state.json', JSON.stringify(comments), (error) => {
26         if (error)
27             throw error;
28     })
29 }
30
31 // And connect to that on either clean exit...
32 process.on('exit', cleanup);
33
34 // ... or on a SIGINT (control-C)
35 process.on('SIGINT', () => {
36     cleanup();
37     process.exit();
38 });
39
40 app.get('/index.html', (req, res) => {
41     res.sendFile(__dirname + '/index.html');
42 });
43
44 io.on('connection', (socket) => {
45
46     // Replay old comments to a newly-joining client
47     comments.forEach((comment) => {
48         socket.emit('comment', comment)
49     });
50
51     // When any client comments, send that to all clients (including sender)
52     socket.on('comment', (comment) => {
53         io.emit('comment', comment);
54         comments.push(comment);
55     });
56
57     // Generate an image when requested
58     socket.on('generate', (request) => {
59         console.log(`Generating image with code=${request['code']} and prompt=${request['prompt']}`);
60     });
61 });
62
63 server.listen(port, () => {
64     console.log(`listening on *:${port}`);
65 });