-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
270 lines (239 loc) · 9.7 KB
/
server.js
File metadata and controls
270 lines (239 loc) · 9.7 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
const express = require('express');
const fs = require('fs');
const bodyParser = require('body-parser');
const path = require('path');
const PokemonBoosterPriceCalculator = require('./PokemonBoosterPriceCalculator');
const WebSocket = require('ws');
const app = express();
const port = 80;
const jsonFilePath = 'items_simon.json';
const { spawn } = require('child_process');
const calculatorProcess = spawn('node', ['PokemonBoosterPriceCalculator.js']);
calculatorProcess.stdout.on('data', (data) => {
const messages = data.toString().trim().split('\n');
messages.forEach(message => {
try {
const logData = JSON.parse(message);
console.log(`[Calculator] Function: ${logData.function}, Data:`, logData.data);
} catch (error) {
console.log(`[Calculator] Raw Log: ${message}`);
}
});
});
calculatorProcess.stderr.on('data', (data) => {
console.error(`[Calculator ERROR] ${data.toString()}`);
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));
const loadItems = () => {
try {
const data = fs.readFileSync(jsonFilePath, 'utf8');
return JSON.parse(data);
} catch (err) {
logError('Error reading file:', err);
return [];
}
};
const saveItems = (items) => {
try {
fs.writeFileSync(jsonFilePath, JSON.stringify(items, null, 2));
console.log('[ITEMMANAGER] Änderungen wurden gespeichert.');
} catch (err) {
logError('Error writing file:', err);
}
};
const logError = (message, error) => {
const errorMessage = `${new Date().toISOString()} - ${message} ${error ? error.message : ''}\n`;
fs.appendFileSync('error.txt', errorMessage);
console.error(message, error);
};
process.on('uncaughtException', (err) => {
logError('Uncaught Exception:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
logError('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
class ItemManager {
constructor(filePath) {
this.filePath = filePath;
}
getItems() {
return loadItems();
}
saveItems(items) {
saveItems(items);
}
}
const itemManager = new ItemManager(jsonFilePath);
const calculator = new PokemonBoosterPriceCalculator(itemManager);
const wss = new WebSocket.Server({ noServer: true });
wss.on('connection', (ws) => {
console.log('[SERVER] Client wurde geöffnet und ist mit dem Server verbunden.');
ws.on('message', async (message) => {
try {
const data = JSON.parse(message);
if (data.type === 'addItem') {
const items = itemManager.getItems();
const item = data.item;
const index = parseInt(item.index, 10);
const isValidIndex = !isNaN(index) && index >= 0 && index < items.length;
if (item.image) {
const base64Data = item.image.replace(/^data:image\/\w+;base64,/, "");
const filename = `public/uploads/${Date.now()}.png`;
fs.writeFileSync(filename, base64Data, 'base64');
item.image = `/uploads/${path.basename(filename)}`;
} else if (isValidIndex) { item.image = items[index].image; }
if (isValidIndex) {
item.previousPrice = items[index].price;
items[index] = item;
} else { items.push(item); }
itemManager.saveItems(items);
ws.send(JSON.stringify({ type: 'updateItems', items }));
} else if (data.type === 'pauseUpdate') {
calculator.pauseUpdate();
ws.send(JSON.stringify({ type: 'updateStatus', status: 'paused' }));
} else if (data.type === 'resumeUpdate') {
calculator.resumeUpdate();
ws.send(JSON.stringify({ type: 'updateStatus', status: 'resumed' }));
} else if (data.type === 'stopUpdate') {
calculator.stopUpdate();
ws.send(JSON.stringify({ type: 'updateStatus', status: 'stopped' }));
}
} catch (err) {
logError('[SERVER] Websocket Verbindung konnte nicht gestartet werden:', err);
}
});
});
const server = app.listen(port, () => {
console.log(`<br>
########################################<br>
# #<br>
# #<br>
# PokeBinder #<br>
# #<br>
# #<br>
# IG: @ichbinmalkurzweg #<br>
# E-MAIL: simondevde@gmail.com #<br>
# #<br>
########################################<br>
`);
console.log('[SERVER] Itemmanager wurde gestartet.<br>');
console.log('[SERVER] Preis Updater wurde gestartet.<br>');
console.log(`[SERVER] PokeBinder Server wurde gestartet unter http://localhost:${port}<br>`);
console.log(`---------------------------------------------------------------------`);
console.log('');
});
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
app.get('/api/items', (req, res) => {
try {
const items = itemManager.getItems();
res.json(items);
} catch (err) {
logError('[Error] Item wurde nicht gefunden. Grund:', err);
res.status(500).json({ error: 'Internes Server Problem' });
}
});
app.delete('/api/items/:index', (req, res) => {
try {
const items = itemManager.getItems();
const index = parseInt(req.params.index, 10);
if (index >= 0 && index < items.length) {
items.splice(index, 1);
itemManager.saveItems(items);
res.json(items);
} else {
res.status(404).json({ error: 'Item nicht gefunden' });
}
} catch (err) {
logError('[ERROR] Item konnte nicht gelöscht werden Grund:', err);
res.status(500).json({ error: 'Internes Server Problem' });
}
});
app.post('/api/update-item-price', async (req, res) => {
try {
const { index } = req.body;
const items = itemManager.getItems();
const item = items[index];
if (!item) {
return res.status(404).json({ error: 'Item not found' });
}
const currentPrice = await calculator.getPrice(item.link);
if (currentPrice === null) {
return res.status(500).json({ error: 'Price could not be retrieved' });
}
item.previousPrice = item.price;
item.price = currentPrice.toFixed(2);
itemManager.saveItems(items);
res.json({ message: 'Price successfully updated', item });
} catch (err) {
logError('[ERROR] Price could not be updated:', err);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/resync-prices', async (req, res) => {
try {
const ws = [...wss.clients][0];
await calculator.updatePrices(ws);
res.json({ message: '[SERVER] Preise wurden erfolgreich synchronisiert.' });
console.log('[SERVER & BPC] Daten wurden erfolgreich geupdated.');
} catch (err) {
logError('[ERROR] Synchronisation konnte nicht realisiert werden. Grund:', err);
res.status(500).json({ error: 'Internes Server Problem' });
}
});
process.stdin.on('data', async (data) => {
try {
const message = JSON.parse(data.toString());
if (message.type === 'triggerUpdate') {
console.log('[SERVER] Auto Update:');
// Alle Items im Hintergrund aktualisieren
//await updateAllPricesInBackground();
const ws = [...wss.clients][0];
await calculator.updatePrices(ws);
// Optionale Rückmeldung an alle Clients über den WebSocket
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ message: 'Alle Preise wurden erfolgreich aktualisiert.' }));
}
});
}
} catch (err) {
console.error('[SERVER] Fehler beim Verarbeiten der IPC-Nachricht:', err);
}
});
// Funktion, um alle Preise im Hintergrund zu aktualisieren
async function updateAllPricesInBackground() {
try {
const items = itemManager.getItems();
const priceCalculator = new PokemonBoosterPriceCalculator(itemManager);
for (let item of items) {
try {
const currentPrice = await priceCalculator.getPrice(item.link);
if (currentPrice !== null) {
console.log(`Neuer Preis für ${item.name}: ${currentPrice.toFixed(2)}`);
item.previousPrice = item.price;
item.price = currentPrice.toFixed(2);
await priceCalculator.saveDailyPrice(currentPrice, item.name);
await priceCalculator.generateCharts(item);
}
} catch (err) {
console.error('[ERROR] Fehler beim Aktualisieren des Preises für Item:', item, err);
}
}
// Nach der Aktualisierung alle Items speichern
itemManager.saveItems(items);
priceCalculator.cleanPrices();
console.log('[SERVER] Alle Preise wurden erfolgreich aktualisiert.');
} catch (err) {
console.error('[SERVER] Fehler beim Aktualisieren aller Preise:', err);
}
}
module.exports = { app, server, wss };