Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
322 lines (270 loc) · 9.84 KB
/
Copy pathserver.js
File metadata and controls
322 lines (270 loc) · 9.84 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
const express = require('express');
const axios = require('axios');
const path = require('path');
const fs = require('fs');
const app = express();
const PORT = process.env.PORT || 8000;
// Remote API endpoint
const REMOTE_API = process.env.REMOTE_API;
// In-memory cache with key-based storage (username+mode)
const cache = new Map();
const CACHE_TTL = 60; // seconds
// Serve static files from the 'static' folder
app.use('/static', express.static(path.join(__dirname, 'static'), {
setHeaders: (res, filepath) => {
// Only allow PNG files
if (filepath.endsWith('.png')) {
res.setHeader('Content-Type', 'image/png');
res.setHeader('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
}
}
}));
// Serve index.html at root
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Serve ranks configuration
app.get('/api/ranks', (req, res) => {
const configPath = path.join(__dirname, 'ranks_config.json');
if (fs.existsSync(configPath)) {
const ranks = JSON.parse(fs.readFileSync(configPath, 'utf8'));
res.json(ranks);
} else {
// Return default ranks if config file doesn't exist
res.json([]);
}
});
// Proxy endpoint for rank data
app.get('/api/rank', async (req, res) => {
const username = req.query.username || 'bbraad';
const mode = req.query.mode || 'squad';
const now = Date.now() / 1000; // Convert to seconds
// Create cache key based on username and mode
const cacheKey = `${username}:${mode}`;
const cachedEntry = cache.get(cacheKey);
// Test with local file
// var obj = JSON.parse(fs.readFileSync('test.json', 'utf8'));
// return res.json(obj);
// Serve cached data if still valid
if (cachedEntry && (now - cachedEntry.timestamp) < CACHE_TTL) {
console.log(`Cache hit for ${cacheKey}`);
return res.json(cachedEntry.data);
}
try {
console.log(`Fetching fresh data for ${cacheKey}`);
const response = await axios.get(`${REMOTE_API}/rank/get`, {
params: { username, mode },
timeout: 15000
});
const data = response.data;
// Check if response is empty or indicates player not found
if (!data || Object.keys(data).length === 0 || data.error || data.points === undefined) {
console.log(`Player not found: ${cacheKey}`);
return res.status(404).json({
error: 'Player not found',
message: `No data found for player "${username}" in ${mode} mode`
});
}
// Cache the successful response with username+mode key
cache.set(cacheKey, {
data: data,
timestamp: now
});
res.json(data);
} catch (error) {
// If API is slow or errors, return cached data if available (even if expired)
if (cachedEntry) {
console.log(`API error, serving stale cache for ${cacheKey}`);
return res.json(cachedEntry.data);
}
if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
res.status(504).json({ error: 'Rank API timeout' });
} else if (error.response && error.response.status === 404) {
res.status(404).json({
error: 'Player not found',
message: `No data found for player "${username}" in ${mode} mode`
});
} else {
console.log(`${REMOTE_API}/rank/get`, { params: { username, mode } });
res.status(502).json({ error: `Rank API error: ${error.message}` });
}
}
});
// Clean up old cache entries periodically (every 5 minutes)
setInterval(() => {
const now = Date.now() / 1000;
let cleaned = 0;
for (const [key, entry] of cache.entries()) {
if (now - entry.timestamp > CACHE_TTL * 2) {
cache.delete(key);
cleaned++;
}
}
if (cleaned > 0) {
console.log(`Cache cleanup: Removed ${cleaned} expired entries`);
}
}, 5 * 60 * 1000);
// ----------------- Serve old design ---------------------
app.get('/old', (req, res) => {
res.sendFile(path.join(__dirname, '/old_design/index.html'));
});
app.use('/old/static', express.static(path.join(__dirname, '/old_design/static'), {
setHeaders: (res, filepath) => {
// Only allow PNG files
if (filepath.endsWith('.png')) {
res.setHeader('Content-Type', 'image/png');
res.setHeader('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
}
}
}));
app.get('/api/old/ranks', (req, res) => {
const configPath = path.join(__dirname, 'old_design/ranks_config.json');
if (fs.existsSync(configPath)) {
const ranks = JSON.parse(fs.readFileSync(configPath, 'utf8'));
res.json(ranks);
} else {
// Return default ranks if config file doesn't exist
res.json([]);
}
});
// ----------------- Serve old design ---------------------
// ----------------- Serve leaderboard design ---------------------
app.get('/leaderboard', (req, res) => {
res.sendFile(path.join(__dirname, '/leaderboard/index.html'));
});
app.use('/leaderboard/static', express.static(path.join(__dirname, '/leaderboard/static'), {
setHeaders: (res, filepath) => {
// Only allow PNG files
if (filepath.endsWith('.png')) {
res.setHeader('Content-Type', 'image/png');
res.setHeader('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
}
}
}));
// ----------------- Serve leaderboard design ---------------------
// ----------------- Serve leaderboard design ---------------------
app.get('/hotdrop', (req, res) => {
res.sendFile(path.join(__dirname, '/hotdrop/index.html'));
});
app.use('/hotdrop/static', express.static(path.join(__dirname, '/hotdrop/static'), {
setHeaders: (res, filepath) => {
// Only allow PNG files
if (filepath.endsWith('.png')) {
res.setHeader('Content-Type', 'image/png');
res.setHeader('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
}
}
}));
// ----------------- Serve leaderboard design ---------------------
// Proxy endpoint for rank data
app.get('/api/scrim_hotdrop', async (req, res) => {
const id = req.query.id;
const now = Date.now() / 1000; // Convert to seconds
// Create cache key based on username and mode
const cacheKey = `scrim_hotdrop:${id}`;
const cachedEntry = cache.get(cacheKey);
// Serve cached data if still valid
if (cachedEntry && (now - cachedEntry.timestamp) < CACHE_TTL) {
console.log(`Cache hit for ${cacheKey}`);
return res.json(cachedEntry.data);
}
try {
console.log(`Fetching fresh data for ${cacheKey}`);
const response = await axios.get(`${REMOTE_API}/scrims/hotdrop`, {
params: { id },
timeout: 15000
});
const data = response.data;
if (!data || data.error) {
return res.status(404).json({
error: 'Can\'t get selected maps of the scrim',
message: `Failed to get selected maps of the scrim for ${id}`
});
}
// Cache the successful response with username+mode key
cache.set(cacheKey, {
data: data,
timestamp: now
});
res.json(data);
} catch (error) {
// If API is slow or errors, return cached data if available (even if expired)
if (cachedEntry) {
console.log(`API error, serving stale cache for ${cacheKey}`);
return res.json(cachedEntry.data);
}
if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
res.status(504).json({ error: 'Rank API timeout' });
} else if (error.response && error.response.status === 404) {
res.status(404).json({
error: 'Can\'t get selected maps of the scrim',
message: `Failed to get selected maps of the scrim for ${id}`
});
} else {
console.log(`${REMOTE_API}/scrims/hotdrop`, { params: { id } });
res.status(502).json({ error: `Rank API error: ${error.message}` });
}
}
});
// Proxy endpoint for rank data
app.get('/api/scrim_leaderboard', async (req, res) => {
const id = req.query.id;
const now = Date.now() / 1000; // Convert to seconds
// Create cache key based on username and mode
const cacheKey = `scrim_leaderboard:${id}`;
const cachedEntry = cache.get(cacheKey);
// Serve cached data if still valid
if (cachedEntry && (now - cachedEntry.timestamp) < CACHE_TTL) {
console.log(`Cache hit for ${cacheKey}`);
return res.json(cachedEntry.data);
}
try {
console.log(`Fetching fresh data for ${cacheKey}`);
const response = await axios.get(`${REMOTE_API}/scrims/leaderboard`, {
params: { id },
timeout: 15000
});
const data = response.data;
if (!data || data.error) {
return res.status(404).json({
error: 'Can\'t get scrim leaderboard',
message: `Failed to get leaderboard for ${id}`
});
}
// Cache the successful response with username+mode key
cache.set(cacheKey, {
data: data,
timestamp: now
});
res.json(data);
} catch (error) {
// If API is slow or errors, return cached data if available (even if expired)
if (cachedEntry) {
console.log(`API error, serving stale cache for ${cacheKey}`);
return res.json(cachedEntry.data);
}
if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
res.status(504).json({ error: 'Rank API timeout' });
} else if (error.response && error.response.status === 404) {
res.status(404).json({
error: 'Can\'t get scrim leaderboard',
message: `Failed to get leaderboard for ${id}`
});
} else {
console.log(`${REMOTE_API}/scrims/leaderboard`, { params: { id } });
res.status(502).json({ error: `Rank API error: ${error.message}` });
}
}
});
// Start server
app.listen(PORT, () => {
console.log(`\n========================================`);
console.log(` Rank Widget Server is running!`);
console.log(`========================================`);
console.log(`\n Local: http://localhost:${PORT}`);
console.log(` Network: http://127.0.0.1:${PORT}`);
console.log(`\n Usage:`);
console.log(` http://localhost:${PORT}?username=YourName&mode=squad`);
console.log(`\n Available modes: squad, duo, solo`);
console.log(`========================================\n`);
});