-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
273 lines (240 loc) · 8.45 KB
/
server.js
File metadata and controls
273 lines (240 loc) · 8.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const { spawn } = require('child_process');
const app = express();
const path = require('path');
const nodePort = 3000;
const pythonPort = 4000;
const fs = require('fs');
const fsPromises = require('fs').promises;
const fsExtra = require('fs-extra')
const https = require('https');
const StreamZip = require('node-stream-zip');
const AdmZip = require('adm-zip');
const { rimraf } = require('rimraf');
const { v4: uuidv4 } = require('uuid');
const DEBUG_MODE = process.env.DEBUG_MODE === 'true' || false;
// Start the Python server
const pythonProcess = spawn('python', ['scripts/MythicForge.py', '--port', pythonPort], {
env: { ...process.env, DEBUG_MODE: DEBUG_MODE.toString() }
});
// Listen for output from the Python server (for debugging)
if (DEBUG_MODE) {
pythonProcess.stdout.on('data', async (data) => {
console.log(`Python Server: ${data}`);
});
pythonProcess.stderr.on('data', (data) => {
console.error(`Python Error: ${data}`);
});
} else {
pythonProcess.stderr.on('data', (data) => {
if (data.toString().includes('Error')) {
console.error(`Python Error: ${data}`);
}
});
}
pythonProcess.on('close', (code) => {
console.log(`Python server exited with code ${code}`);
});
const cleanupDirectory = async (dirPath, maxRetries = 3) => {
for (let i = 0; i < maxRetries; i++) {
try {
await rimraf(dirPath);
return;
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
};
const extractLargeZip = async (zipPath, outputPath) => {
const zip = new StreamZip.async({ file: zipPath });
try {
await zip.extract(null, outputPath);
} finally {
await zip.close();
}
};
const downloadLargeFile = async (url, destination) => {
const writer = fs.createWriteStream(destination);
const response = await axios({
url,
method: 'GET',
responseType: 'stream'
});
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
};
const downloadDataFrom5eTools = async () => {
const zipFilePath = '5etools.zip';
const dataPath = 'public/data';
const sourcePath = '5etools/5etools-src-main/data';
if (!fs.existsSync(dataPath)) {
console.log('Downloading 5eTools data, Please wait...');
try {
const url = 'https://github.com/5etools-mirror-3/5etools-src/archive/refs/heads/master.zip';
const response = await axios({
url,
method: 'GET',
responseType: 'arraybuffer'
});
await fsPromises.writeFile('5etools.zip', response.data);
console.log('Download complete, extracting...');
await extractLargeZip('5etools.zip', '5etools');
await fsPromises.mkdir(dataPath, { recursive: true });
// Verify source exists
if (!fs.existsSync(sourcePath)) {
throw new Error('Source data directory not found after extraction');
}
// Move files using async/await
await fsExtra.move(sourcePath, dataPath, {
overwrite: true
});
// Cleanup
// Cleanup with retry mechanism
await cleanupFiles([
zipFilePath,
'5etools'
]);
console.log('5eTools data downloaded');
} catch (error) {
console.error('Error downloading data:', error);
throw error;
}
}
};
const cleanupFiles = async (paths) => {
for (const path of paths) {
try {
if (await fs.existsSync(path)) {
if (fs.lstatSync(path).isDirectory()) {
await cleanupDirectory(path);
} else {
await unlinkWithRetry(path);
}
}
} catch (error) {
console.warn(`Warning: Could not cleanup ${path}:`, error.message);
}
}
};
const unlinkWithRetry = async (filePath, maxRetries = 3) => {
for (let i = 0; i < maxRetries; i++) {
try {
await fsPromises.access(filePath, fs.constants.W_OK);
await fsPromises.unlink(filePath);
return;
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
};
const downloadImagesFrom5eTools = async () => {
const imagePath = 'public/assets/images/5eTools';
const zipFilePath = '5etools.zip';
const zipUrl = 'https://github.com/5etools-mirror-3/5etools-img/archive/refs/heads/master.zip';
if (!fs.existsSync(imagePath)) {
console.log('Downloading 5eTools images, Please wait, this can take a long while...');
try {
await downloadLargeFile(zipUrl, zipFilePath);
await extractLargeZip(zipFilePath, 'public/assets/images');
await fsPromises.rename('public/assets/images/5etools-img-main', imagePath);
await fsPromises.unlink(zipFilePath).catch(() => {});
console.log('5eTools images downloaded successfully');
} catch (error) {
console.error('Error downloading images:', error.message);
// Cleanup on error
await fsPromises.rm('public/assets/images/5etools-img-main', { recursive: true, force: true }).catch(() => {});
await fsPromises.unlink(zipFilePath).catch(() => {});
throw error;
}
}
};
// Middleware to serve static files
app.use(express.static('public'));
app.use(bodyParser.json());
app.set('view engine', 'ejs');
// Set the views directory
app.set('views', path.join(__dirname, 'views'));
// Route to handle the main page
app.get('/', async (req, res) => {
try {
entries = [];
res.render('index.ejs', { entries });
} catch (error) {
console.error('Error handling user session:', error);
res.status(500).send('Error handling user session');
}
});
app.get('/data', async (req, res) => {
try {
if (!req.query.type) {
return res.status(400).json({ error: 'Missing required parameters' });
}
const requestData = {
method: 'GET',
url: `http://127.0.0.1:${pythonPort}/data`,
params: {
type: req.query.type,
q: req.query.q
}
};
const response = await axios(requestData);
if (!response.data) {
return res.status(404).json({ error: 'No data found' });
}
res.json(response.data);
} catch (error) {
console.error('Error fetching data from Python API:', error);
res.status(500).json({ error: 'Error fetching data' });
}
});
// Route to Create a monster story
app.post('/story', async (req, res) => {
try {
const response = await axios.post('http://127.0.0.1:'+pythonPort+'/story', req.body.monster);
res.json(response.data);
} catch (error) {
console.error('Error executing Python function:', error);
res.status(500).send('Error executing Python function: '+error);
}
});
// Route to Explain a property
app.post('/prop', async (req, res) => {
try {
const response = await axios.post('http://127.0.0.1:'+pythonPort+'/prop', req.body);
res.json(response.data);
} catch (error) {
console.error('Error executing Python function:', error);
res.status(500).send('Error executing Python function');
}
});
// Route to trigger a Python function
app.post('/execute', async (req, res) => {
try {
const response = await axios.post('http://127.0.0.1:'+pythonPort+'/execute', req.body);
res.json(response.data);
} catch (error) {
console.error('Error executing Python function:', error);
res.status(500).send('Error executing Python function');
}
});
// Start the Node.js server
app.listen(nodePort, async () => {
await downloadDataFrom5eTools();
await downloadImagesFrom5eTools();
console.log(`MythicForge server running at http://127.0.0.1:${nodePort}`);
});
// Ensure Python process is killed when Node.js exits
process.on('exit', () => {
pythonProcess.kill();
});
process.on('SIGINT', () => {
pythonProcess.kill();
process.exit();
});