]> git.cworth.org Git - zombocom-ai/blob - index.js
9d4028fbd4cad5a1889ddadc037fd39949388946
[zombocom-ai] / index.js
1 const fs = require('fs');
2
3 const util = require('util');
4 const execFile = util.promisify(require('child_process').execFile);
5
6 const express = require('express');
7 const app = express();
8 const session = require('express-session');
9 const FileStore = require('session-file-store')(session);
10 const http = require('http');
11 const server = http.createServer(app);
12 const { Server } = require("socket.io");
13 const io = new Server(server);
14 const port = 2122;
15
16 const python_path = '/usr/bin/python3'
17 const generate_image_script = '/home/cworth/src/zombocom-ai/generate-image.py'
18 const state_file = 'zombocom-state.json'
19
20 var state;
21
22 if (!process.env.ZOMBOCOM_SESSION_SECRET) {
23     console.log("Error: Environment variable ZOMBOCOM_SESSION_SECRET not set.");
24     console.log("Please set it to a random, but persistent, value.")
25     process.exit();
26 }
27
28 const session_middleware =  session(
29     {store: new FileStore,
30      secret: process.env.ZOMBOCOM_SESSION_SECRET,
31      resave: false,
32      saveUninitialized: true
33     });
34
35 app.use(session_middleware);
36
37 // convert a connect middleware to a Socket.IO middleware
38 const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
39
40 io.use(wrap(session_middleware));
41
42 // Load comments at server startup
43 fs.readFile(state_file, (err, data) => {
44     if (err)
45         state = { images: [], comments: [] };
46     else
47         state = JSON.parse(data);
48 });
49
50 // Save comments when server is shutting down
51 function cleanup() {
52     fs.writeFileSync('zombocom-state.json', JSON.stringify(state), (error) => {
53         if (error)
54             throw error;
55     })
56 }
57
58 // And connect to that on either clean exit...
59 process.on('exit', cleanup);
60
61 // ... or on a SIGINT (control-C)
62 process.on('SIGINT', () => {
63     cleanup();
64     process.exit();
65 });
66
67 app.get('/index.html', (req, res) => {
68     if (req.session.views) {
69         req.session.views++;
70     } else {
71         req.session.views = 1;
72     }
73     res.sendFile(__dirname + '/index.html');
74 });
75
76 io.on('connection', (socket) => {
77
78     console.log("Connection from client with " + socket.request.session.views + " views.");
79
80     // Replay old comments and images to a newly-joining client
81     socket.emit('reset');
82     state.comments.forEach((comment) => {
83         socket.emit('comment', comment)
84     });
85     state.images.forEach((image) => {
86         socket.emit('image', image)
87     });
88
89     // When any client comments, send that to all clients (including sender)
90     socket.on('comment', (comment) => {
91         io.emit('comment', comment);
92         state.comments.push(comment);
93     });
94
95     // Generate an image when requested
96     socket.on('generate', (request) => {
97         console.log(`Generating image with code=${request['code']} and prompt=${request['prompt']}`);
98         async function generate_image(code, prompt) {
99             var promise;
100             if (code) {
101                 promise = execFile(python_path, [generate_image_script, `--seed=${code}`, prompt])
102             } else {
103                 promise = execFile(python_path, [generate_image_script, prompt])
104             }
105             const child = promise.child;
106             child.stdout.on('data', (data) => {
107                 const images = JSON.parse(data);
108                 images.forEach((image) => {
109                     console.log(`Emitting image to clients: ${image}`);
110                     io.emit('image', image);
111                     state.images.push(image);
112                 });
113             });
114             child.stderr.on('data', (data) => {
115                 console.log("Error occurred during generate-image: " + data);
116             });
117             try {
118                 const { stdout, stderr } = await promise;
119             } catch(e) {
120                 console.error(e);
121             }
122             socket.emit('generation-done');
123         }
124         generate_image(request['code'], request['prompt']);
125     });
126 });
127
128 server.listen(port, () => {
129     console.log(`listening on *:${port}`);
130 });