-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
582 lines (495 loc) · 26.6 KB
/
script.js
File metadata and controls
582 lines (495 loc) · 26.6 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
document.addEventListener('DOMContentLoaded', () => {
const serversContainer = document.getElementById('servers-container');
const favoritesContainer = document.getElementById('favorites-container');
const favoritesSection = document.getElementById('favorites-section');
const allServersSection = document.getElementById('all-servers-section');
const loadingElement = document.getElementById('loading');
const errorElement = document.getElementById('error');
const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');
const modal = document.getElementById('server-modal');
const closeBtn = document.querySelector('.close-modal');
const tabAll = document.getElementById('tab-all');
const tabFavorites = document.getElementById('tab-favorites');
// Store all servers for searching
let allServers = [];
// Store favorite servers and IMMEDIATELY LOAD THEM
let favoriteServers = loadFavorites();
console.log("[INIT] favoriteServers:", favoriteServers);
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
// Tab switching functionality
tabAll.addEventListener('click', () => {
tabAll.classList.add('active');
tabFavorites.classList.remove('active');
allServersSection.style.display = 'block';
favoritesSection.style.display = 'none';
});
tabFavorites.addEventListener('click', () => {
tabFavorites.classList.add('active');
tabAll.classList.remove('active');
favoritesSection.style.display = 'block';
allServersSection.style.display = 'none';
displayFavorites(); // Refresh favorites display
});
// Function to parse MOTD formatting with color tags
function parseMotdFormatting(motd) {
if (!motd) return '';
// Replace color tags with span elements
let formatted = motd
// Handle color tags like <color:#00ccff>
.replace(/<color:(#[0-9a-fA-F]{6})>/g, '<span style="color:$1;">')
// Handle predefined color tags like <white>, <green>
.replace(/<white>/g, '<span style="color:white;">')
.replace(/<green>/g, '<span style="color:green;">')
.replace(/<blue>/g, '<span style="color:#00ccff;">')
.replace(/<\/color>/g, '</span>')
// Close any unclosed color tags
.replace(/<\/white>/g, '</span>')
.replace(/<\/green>/g, '</span>')
.replace(/<\/blue>/g, '</span>')
// Handle bold tags
.replace(/<b>/g, '<strong>')
.replace(/<\/b>/g, '</strong>');
return formatted;
}
// Function to fetch servers from Minehut API
// API Status monitoring
let lastApiStatus = 'unknown'; // ? Why is this here? Currently not being used.
let lastApiCheck = 0;
const API_CHECK_INTERVAL = 30000; // Check every 30 seconds
// Enhanced API fetch with rate limiting and status monitoring
async function fetchMinehutServers() {
try {
const now = Date.now();
if (lastApiCheck === 0 || now - lastApiCheck > API_CHECK_INTERVAL) { // Allow initial call
lastApiCheck = now;
const apiStatusElement = document.getElementById('api-status');
const lastUpdateElement = document.getElementById('last-update');
apiStatusElement.className = 'status-chip';
apiStatusElement.textContent = 'API: Checking...';
const response = await fetch('https://api.minehut.com/servers');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
if (!data || !data.servers || !Array.isArray(data.servers)) {
throw new Error('Invalid data format received from API');
}
lastApiStatus = 'connected';
apiStatusElement.className = 'status-chip status-online';
apiStatusElement.textContent = 'API: Connected';
lastUpdateElement.textContent = `Last Update: ${new Date().toLocaleTimeString()}`;
document.getElementById('total-servers').textContent = data.servers.length;
const totalPlayers = data.servers.reduce((sum, server) =>
sum + (server.playerData ? server.playerData.playerCount : 0), 0);
document.getElementById('total-players').textContent = totalPlayers;
return data.servers.sort((a, b) =>
(b.playerData ? b.playerData.playerCount : 0) -
(a.playerData ? a.playerData.playerCount : 0)
);
}
throw new Error('Rate limit: Please wait before refreshing');
} catch (error) {
console.error('Error fetching Minehut servers:', error);
const apiStatusElement = document.getElementById('api-status');
apiStatusElement.className = 'status-chip status-offline';
apiStatusElement.textContent = 'API: Error';
errorElement.style.display = 'block';
errorElement.textContent = `Error: ${error.message}. Retrying in 30 seconds...`;
lastApiStatus = 'error';
throw error;
}
}
// Load favorites from local storage
function loadFavorites() {
const storedFavorites = localStorage.getItem('minehutFavorites');
console.log("[LOAD] Stored Favorites (raw):", storedFavorites);
if (storedFavorites) {
try {
const parsedFavorites = JSON.parse(storedFavorites);
console.log("[LOAD] Parsed Favorites:", parsedFavorites);
// // const filteredFavorites = parsedFavorites.filter(fav => fav && fav._id && fav.serverPlan);
// // console.log("[LOAD] Filtered Favorites:", filteredFavorites);
// // return filteredFavorites; // the loaded and parsed favorites from local storage
return parsedFavorites || [];
} catch (e) {
console.error('Error parsing favorites from local storage:', e);
return [];
}
}
return [];
}
// Save favorites to local storage
function saveFavorites() {
console.log("[SAVE] Saving Favorites (full objects):", favoriteServers);
localStorage.setItem('minehutFavorites', JSON.stringify(favoriteServers));
}
// Check if a server is in favorites
function isServerFavorite(serverId) {
return favoriteServers.some(server => server._id === serverId);
}
// Add or remove a server from favorites
function toggleFavorite(server) {
// Normalizing the server object to make sure it has top-level _id
const normalizedServer = server.staticInfo ? { _id: server.staticInfo._id, serverPlan: server.staticInfo.serverPlan } : { _id: server._id, serverPlan: server.serverPlan };
const index = favoriteServers.findIndex(s => s._id === normalizedServer._id);
const wasFavorite = index !== -1;
if (index === -1) {
favoriteServers.push(server);
console.log("[TOGGLE] Added to Favorites:", server.name, "Current Favorites:", favoriteServers);
} else {
favoriteServers.splice(index, 1);
console.log("[TOGGLE] Removed from Favorites:", server.name, "Current Favorites:", favoriteServers);
}
saveFavorites();
displayFavorites();
// Update the specific favorite button in the main list
const mainServerCard = document.querySelector(`.server-card[data-server-id="${server._id}"]`);
if (mainServerCard) {
const favoriteButton = mainServerCard.querySelector('.favorite-btn');
if (favoriteButton) {
favoriteButton.classList.toggle('active', !wasFavorite); // switch based on the previous state
favoriteButton.title = !wasFavorite ? 'Remove from favorites' : 'Add to favorites';
}
}
// If we're in the favorites tab and removed a favorite, check if we need to show empty state
if (wasFavorite && tabFavorites.classList.contains('active')) {
if (favoriteServers.length === 0) {
favoritesContainer.innerHTML = '<div class="empty-state"><span class="mdi mdi-star-outline"></span><p>No favorite servers yet. Click the star icon on any server to add it to your favorites.</p></div>';
}
}
}
// Category color mapping and display order
const categoryColors = {
"pvp": { label: "⚔️ PvP", color: "#DF3D4B" },
"lifesteal": { label: "❤️ Lifesteal", color: "#70C8D2" },
"smp": { label: "🏡 SMP", color: "#0DC255" },
"gens": { label: "⚡ Gens", color: "#484372" },
"box": { label: "📦 Box", color: "#A068B7" },
"minigames": { label: "🎉 Minigames", color: "#F6BC51" },
"rpg": { label: "🛡️ RPG", color: "#982341" },
"roleplay": { label: "🎭 Roleplay", color: "#D384F2" },
"parkour": { label: "🤸 Parkour", color: "#DE916C" },
"farming": { label: "🌾 Farming", color: "#B44176" },
"prison": { label: "⛓️ Prison", color: "#188643" },
"factions": { label: "🚩 Factions", color: "#C4E04A" },
"puzzle": { label: "🧩 Puzzle", color: "#85827B" },
"meme": { label: "😂 Meme", color: "#12BF59" },
"creative": { label: "🎨 Creative", color: "#2F7D7C" }
};
const categoryOrder = [
"pvp", "lifesteal", "smp", "gens", "box", "minigames", "rpg",
"roleplay", "parkour", "farming", "prison", "factions", "puzzle", "meme", "creative"
];
// Create a server card element (simplified overview)
function createServerCard(server, index, isFavorite = false) {
const serverCard = document.createElement('div');
serverCard.className = 'server-card';
serverCard.dataset.serverId = server._id;
// Add click event to show server details (will be implemented later)
serverCard.addEventListener('click', () => showServerDetails(server));
// Main info line
const mainInfo = document.createElement('div');
mainInfo.className = 'server-main-info';
// Rank
if (index !== null && !isFavorite) { // Only show rank on the main list
const rankElement = document.createElement('span');
rankElement.className = `server-rank ${index < 3 ? 'top-3' : ''}`;
rankElement.textContent = `#${index + 1}`;
mainInfo.appendChild(rankElement);
}
// Server name
const nameElement = document.createElement('span');
nameElement.className = 'server-name';
nameElement.textContent = server.name;
mainInfo.appendChild(nameElement);
// Player count
const playersElement = document.createElement('span');
playersElement.className = 'server-players';
playersElement.textContent = `${server.playerData ? server.playerData.playerCount : 0} Online`;
mainInfo.appendChild(playersElement);
// Status
const statusElement = document.createElement('span');
statusElement.className = `server-status ${server.online ? 'online' : 'offline'}`;
statusElement.textContent = server.online ? 'Online' : 'Offline';
mainInfo.appendChild(statusElement);
serverCard.appendChild(mainInfo);
// Category tags
const categoryContainer = document.createElement('div');
categoryContainer.className = 'server-categories';
// Check if the server object has the 'categories' property and it's an array
if (server.categories && Array.isArray(server.categories)) {
const prioritizedCategories = server.categories
.sort((a, b) => categoryOrder.indexOf(a) - categoryOrder.indexOf(b))
.slice(0, 3);
prioritizedCategories.forEach(category => {
if (categoryColors[category]) {
const tagElement = document.createElement('span');
tagElement.className = 'category-tag';
tagElement.textContent = categoryColors[category].label;
tagElement.style.backgroundColor = categoryColors[category].color;
categoryContainer.appendChild(tagElement);
}
});
}
serverCard.appendChild(categoryContainer);
// Favorite button
const favoriteBtn = document.createElement('button');
favoriteBtn.className = `favorite-btn ${isServerFavorite(server._id) ? 'active' : ''}`;
favoriteBtn.innerHTML = '★';
favoriteBtn.title = isServerFavorite(server._id) ? 'Remove from favorites' : 'Add to favorites';
favoriteBtn.addEventListener('click', function(e) {
e.stopPropagation();
toggleFavorite(server);
const isCurrentlyFavorite = isServerFavorite(server._id);
this.classList.toggle('active', isCurrentlyFavorite);
this.title = isCurrentlyFavorite ? 'Remove from favorites' : 'Add to favorites';
});
serverCard.appendChild(favoriteBtn);
return serverCard;
}
// Function to display servers (modified to use the simplified card)
function displayServers(servers) {
serversContainer.innerHTML = '';
console.log("First server object:", servers[0]); // Add this line
servers.forEach((server, index) => {
const serverCard = createServerCard(server, index);
if (serverCard) {
serversContainer.appendChild(serverCard);
} else {
console.error('createServerCard returned null for:', server.name);
}
});
}
// Function to display favorite servers (modified to use the simplified card)
function displayFavorites() {
favoritesContainer.innerHTML = '';
console.log("[DISPLAY-FAV] Rendering Favorites:", favoriteServers);
if (favoriteServers.length === 0) {
// Show empty state message instead of hiding the section
favoritesContainer.innerHTML = '<div class="empty-state"><span class="mdi mdi-star-outline"></span><p>No favorite servers yet. Click the star icon on any server to add it to your favorites.</p></div>';
} else {
favoriteServers.forEach(favorite => {
const serverCard = createServerCard(favorite, null, true);
if (serverCard) {
favoritesContainer.appendChild(serverCard);
} else {
console.error('createServerCard returned null for favorite:', favorite?.name);
}
});
}
document.getElementById('favorites-count').textContent = `${favoriteServers.length} tracked`;
// **REMOVED THE CODE THAT UPDATES MAIN SERVER LIST BUTTONS**
// // Update the favorite button in the MAIN server list
// // const allServerCards = document.querySelectorAll('.server-card');
// // allServerCards.forEach(card => {
// // const serverId = card.dataset.serverId;
// // const favoriteButton = card.querySelector('.favorite-btn');
// // if (favoriteButton && serverId) {
// // const isFav = favoriteServers.some(fav => fav._id === serverId);
// // console.log(`[FAV-UPDATE] Server ID: ${serverId}, Is Favorite: ${isFav}`);
// // favoriteButton.classList.toggle('active', isFav);
// // favoriteButton.title = isFav ? 'Remove from favorites' : 'Add to favorites';
// // }
// // });
}
// Search servers function
function searchServers() {
const searchTerm = searchInput.value.trim().toLowerCase();
if (searchTerm === '') {
// If search is empty, show all servers
displayServers(allServers);
return;
}
// Filter servers by name
const filteredServers = allServers.filter(server =>
server.name.toLowerCase().includes(searchTerm)
);
// Display filtered results
displayServers(filteredServers);
}
// Main function to load and display servers
async function loadServers() {
const errorElement = document.getElementById('error');
const serversContainer = document.getElementById('servers-container');
try {
loadingElement.style.display = 'block';
errorElement.style.display = 'none';
serversContainer.innerHTML = '';
// Initialize favorites display
displayFavorites();
// Make sure the correct tab is active on initial load
if (tabFavorites.classList.contains('active')) {
allServersSection.style.display = 'none';
favoritesSection.style.display = 'block';
} else {
allServersSection.style.display = 'block';
favoritesSection.style.display = 'none';
}
// favoriteServers is now initialized at the top of the DOMContentLoaded block
console.log("[INIT] favoriteServers (after load):", favoriteServers);
let initialServers = await fetchMinehutServers();
allServers = initialServers.map(server => {
console.log(`[INITIAL] Server ${server.name} Categories:`, server.allCategories);
return {...server, categories: server.allCategories || [], online: false};
});
// Fetch detailed information for all servers
const serversToDetail = initialServers;
const detailedServersPromises = serversToDetail.map(async (server) => {
try {
const response = await fetch(`https://api.minehut.com/server/${server.staticInfo._id}`);
if (!response.ok) {
console.error(`[DETAIL-FAIL] Failed to fetch details for ${server.name}: ${response.status}`);
return { ...server, _id: server.staticInfo._id };
}
const data = await response.json();
if (data && data.server) {
console.log(`[DETAIL-SUCCESS] Server ${server.name} Detailed Info (Online: ${data.server.online}):`, data.server.categories);
return { ...server, online: data.server.online, categories: data.server.categories || server.allCategories || [], _id: data.server._id };
}
console.log(`[DETAIL-MISSING] Detailed data missing for ${server.name}:`, data);
return { ...server, _id: server.staticInfo._id };
} catch (error) {
console.error(`[DETAIL-ERROR] Error fetching details for ${server.name}:`, error);
return { ...server, _id: server.staticInfo._id };
}
});
const detailedServers = await Promise.all(detailedServersPromises);
// Update servers with detailed info
for (let i = 0; i < detailedServers.length && i < allServers.length; i++) {
console.log(`[MERGE] Server ${allServers[i]?.name} Before Merge - Categories:`, allServers[i]?.categories, "Detailed Categories:", detailedServers[i]?.categories, "Online:", detailedServers[i]?.online, "_id (before):", allServers[i]?._id); // before merge
allServers[i] = {
...allServers[i],
online: detailedServers[i]?.online !== undefined ? detailedServers[i].online : allServers[i].online,
categories: detailedServers[i]?.categories || allServers[i].categories,
_id: detailedServers[i]?._id || allServers[i]?.staticInfo?._id // Prioritizes detailed _id, then initial
};
console.log(`[MERGE] Server ${allServers[i]?.name} After Merge - Categories:`, allServers[i]?.categories, "Online:", allServers[i]?.online, "_id (after):", allServers[i]?._id); // after merge
}
console.log("[FINAL - First Server]", allServers[0]); // logs the final state of the first server
loadingElement.style.display = 'none';
displayFavorites();
displayServers(allServers);
} catch (error) {
loadingElement.style.display = 'none';
errorElement.style.display = 'block';
errorElement.textContent = `Error loading servers: ${error.message}. Retrying in 30 seconds...`;
setTimeout(loadServers, 30000);
}
}
// Event listeners
searchButton.addEventListener('click', searchServers);
searchInput.addEventListener('keyup', (event) => {
if (event.key === 'Enter') {
searchServers();
}
});
// Function to show server details in modal
async function showServerDetails(server) {
const modal = document.getElementById('server-modal');
const modalContent = document.getElementById('modal-content-container');
// Show loading state
modalContent.innerHTML = `
<div class="loading-state">
<div class="loading-spinner"></div>
<p>Loading server details...</p>
</div>
`;
modal.style.display = 'block';
try {
// Fetch detailed server data
const response = await fetch(`https://api.minehut.com/server/${server._id}`);
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
const data = await response.json();
const detailedServer = data.server;
modalContent.innerHTML = ''; // Clear loading state
// Create header with server name and status
const headerDiv = document.createElement('div');
headerDiv.className = 'server-detail-header';
headerDiv.innerHTML = `
<h2 class="server-detail-name">${detailedServer.name}</h2>
<span class="server-detail-status ${detailedServer.online ? 'status-online' : 'status-offline'}">
${detailedServer.online ? 'Online' : 'Offline'}
</span>
`;
modalContent.appendChild(headerDiv);
// Add player count (use detailedServer if available, otherwise fallback to server)
addDetailRow(modalContent, 'Players', `${detailedServer.playerCount} / ${detailedServer.maxPlayers || 'Unknown'}`);
// Add server description/MOTD if available (use detailedServer)
if (detailedServer.motd) {
const descDiv = document.createElement('div');
descDiv.className = 'server-detail description-section';
descDiv.innerHTML = `
<div class="server-detail-label">Description:</div>
<div class="server-detail-value">${parseMotdFormatting(detailedServer.motd)}</div>
`;
modalContent.appendChild(descDiv);
}
// Add server IP
addDetailRow(modalContent, 'Server IP', `${detailedServer.name}.minehut.gg`);
// Add creation date
if (detailedServer.creation) {
const creationDate = new Date(detailedServer.creation);
addDetailRow(modalContent, 'Created', creationDate.toLocaleDateString());
}
// Add server version
if (detailedServer.server_version_type) {
addDetailRow(modalContent, 'Version Type', detailedServer.server_version_type);
}
// Add server platform
if (detailedServer.platform) {
addDetailRow(modalContent, 'Platform', detailedServer.platform);
}
// Primary Information Section
const primarySection = document.createElement('div');
primarySection.className = 'server-detail-section primary';
[
['Total Joins', detailedServer.joins],
['Credits/Day', detailedServer.credits_per_day?.toFixed(2)],
['Server Plan', detailedServer.activeServerPlan]
].forEach(([label, value]) => {
if (value !== null && value !== undefined) addDetailRow(primarySection, label, value);
});
modalContent.appendChild(primarySection);
// Secondary Information Section
const secondarySection = document.createElement('div');
secondarySection.className = 'server-detail-section secondary';
// Add any other secondary information from detailedServer here
modalContent.appendChild(secondarySection);
} catch (error) {
console.error('Error fetching server details:', error);
modalContent.innerHTML = `
<div class="error-state">
<p>Error loading server details: ${error.message}</p>
<button class="retry-button" onclick="showServerDetails(${JSON.stringify(server)})">
Retry
</button>
</div>
`;
}
}
// Helper function to add a detail row to the modal
function addDetailRow(container, label, value) {
const detailDiv = document.createElement('div');
detailDiv.className = 'server-detail';
const labelElement = document.createElement('span');
labelElement.className = 'server-detail-label';
labelElement.textContent = `${label}: `;
detailDiv.appendChild(labelElement);
const valueElement = document.createElement('span');
valueElement.className = 'server-detail-value';
valueElement.textContent = value;
detailDiv.appendChild(valueElement);
container.appendChild(detailDiv);
}
// Close modal when clicking the close button or outside the modal
document.addEventListener('click', (event) => {
if (modal && (event.target === modal || event.target === closeBtn)) {
modal.style.display = 'none';
}
});
// Load servers when page loads
loadServers();
});