-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
361 lines (313 loc) · 13.1 KB
/
script.js
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
class ToastManager {
constructor() {
this.container = document.createElement('div');
this.container.className = 'toast-container';
document.body.appendChild(this.container);
}
show(message, type = 'error', duration = 5000) {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.innerHTML = `
<i class="fas ${this.getIconForType(type)}"></i>
<span>${message}</span>
`;
this.container.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
setTimeout(() => {
this.container.removeChild(toast);
}, 300);
}, duration);
}
getIconForType(type) {
switch(type) {
case 'error': return 'fa-exclamation-circle';
case 'success': return 'fa-check-circle';
case 'warning': return 'fa-exclamation-triangle';
default: return 'fa-info-circle';
}
}
}
class CFXLookup {
constructor() {
this.initializeElements();
this.initializeState();
this.initializeEventListeners();
this.toastManager = new ToastManager();
this.setInitialTheme();
}
setInitialTheme() {
this.setTheme('dark'); // Always start with dark mode
}
initializeElements() {
this.elements = {
body: document.body,
themeToggle: document.getElementById('themeToggle'),
serverAddress: document.getElementById('serverAddress'),
lookupBtn: document.getElementById('lookupBtn'),
loader: document.getElementById('loader'),
error: document.getElementById('error'),
errorText: document.getElementById('errorText'),
serverInfo: document.getElementById('serverInfo'),
playerSearch: document.getElementById('playerSearch'),
playerSort: document.getElementById('playerSort'),
serverName: document.getElementById('serverName'),
serverIP: document.getElementById('serverIP'),
players: document.getElementById('players'),
onesync: document.getElementById('onesync'),
gamebuild: document.getElementById('gamebuild'),
country: document.getElementById('country'),
city: document.getElementById('city'),
isp: document.getElementById('isp'),
region: document.getElementById('region'),
playerList: document.getElementById('playerList')
};
// Add copy button to server IP
const ipWrapper = document.createElement('div');
ipWrapper.style.display = 'flex';
ipWrapper.style.alignItems = 'center';
const copyButton = document.createElement('button');
copyButton.className = 'copy-button';
copyButton.innerHTML = '<i class="fas fa-copy"></i>';
copyButton.onclick = () => this.copyToClipboard('serverIP');
this.elements.serverIP.parentNode.appendChild(copyButton);
}
initializeState() {
this.currentServerData = null;
this.players = []; // Store player data
this.isLoading = false; // Track loading state
this.autoRefreshInterval = null; // For auto-refresh
}
initializeEventListeners() {
this.elements.themeToggle.addEventListener('click', () => this.toggleTheme());
this.elements.lookupBtn.addEventListener('click', () => this.handleLookup());
this.elements.serverAddress.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.handleLookup();
});
this.elements.playerSearch.addEventListener('input', () => this.filterPlayers());
this.elements.playerSort.addEventListener('change', () => this.sortPlayers());
}
// Theme Management
setTheme(theme) {
this.elements.body.classList.remove('light-mode', 'dark-mode');
this.elements.body.classList.add(`${theme}-mode`);
this.updateThemeIcon(theme);
localStorage.setItem('cfx-lookup-theme', theme);
}
toggleTheme() {
const currentTheme = this.elements.body.classList.contains('light-mode') ? 'light' : 'dark';
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
this.setTheme(newTheme);
}
updateThemeIcon(theme) {
const icon = this.elements.themeToggle.querySelector('i');
icon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun';
}
// Server Lookup and Data Handling
async handleLookup() {
this.hideError();
this.showLoader();
this.elements.serverInfo.classList.add('hidden');
const input = this.elements.serverAddress.value.trim();
const serverCode = this.extractServerCode(input);
if (!serverCode) {
this.toastManager.show('Invalid CFX address format', 'error');
this.hideLoader();
return;
}
try {
// Check server status before fetching details
const isOnline = await this.checkServerStatus(serverCode);
if (!isOnline) {
this.toastManager.show('Server is currently offline', 'warning');
this.hideLoader();
return;
}
// Fetch server data
const serverResponse = await fetch(`https://servers-frontend.fivem.net/api/servers/single/${serverCode}`);
const serverData = await serverResponse.json();
if (!serverData.Data) {
throw new Error('Server not found or offline');
}
const data = serverData.Data;
let ipAddress = '';
// Handle different server address formats
if (input.includes('.users.cfx.re')) {
try {
const endpointResponse = await fetch(
`https://${data.ownerName}-${serverCode}.users.cfx.re/client`,
{
method: 'POST',
body: 'method=getEndpoints',
headers: {
'Content-Type': 'text/plain'
}
}
);
const endpoints = await endpointResponse.json();
ipAddress = endpoints[0];
} catch (error) {
ipAddress = data.connectEndPoints[0] || 'Hidden';
}
} else {
ipAddress = data.connectEndPoints[0] || 'Hidden';
}
this.updateServerInfo(data, ipAddress);
// Start auto-refresh for player data
this.startAutoRefresh(serverCode);
// Fetch and display server location info
if (ipAddress && ipAddress !== 'Hidden') {
await this.fetchLocationInfo(ipAddress.split(':')[0]);
}
this.toastManager.show('Server information retrieved successfully', 'success');
this.elements.serverInfo.classList.remove('hidden');
} catch (error) {
this.toastManager.show(error.message, 'error');
} finally {
this.hideLoader();
}
}
async checkServerStatus(serverCode) {
try {
const response = await fetch(`https://servers-frontend.fivem.net/api/servers/single/${serverCode}`);
const data = await response.json();
return data.Data && data.Data.clients !== undefined;
} catch {
return false;
}
}
// Fetch location info for IP address
async fetchLocationInfo(ip) {
try {
// Use ipapi.co which supports CORS
const locationResponse = await fetch(`https://ipapi.co/${ip}/json/`);
const locationData = await locationResponse.json();
if (!locationData.error) {
this.elements.country.textContent = locationData.country_name || 'N/A';
this.elements.city.textContent = locationData.city || 'N/A';
this.elements.isp.textContent = locationData.org || 'N/A';
this.elements.region.textContent = locationData.asn || 'N/A';
} else {
throw new Error('Location data not available');
}
} catch (error) {
console.error('Location lookup error:', error);
this.toastManager.show('Location lookup failed. Using fallback method.', 'warning');
this.fetchLocationInfoFallback(ip);
}
}
updateServerInfo(data, ipAddress) {
this.elements.serverName.textContent = this.cleanServerName(data.hostname);
this.elements.serverIP.textContent = ipAddress;
this.elements.players.textContent = `${data.clients}/${data.sv_maxclients}`;
this.elements.onesync.textContent = data.vars.onesync_enabled === 'true' ? 'Enabled' : 'Disabled';
this.elements.gamebuild.textContent = data.vars.sv_enforceGameBuild || 'N/A';
if (data.players) {
this.players = data.players;
this.updatePlayerList(data.players);
}
}
cleanServerName(name) {
return name.replace(/\^[0-9]/g, '').trim();
}
// Clipboard copy
async copyToClipboard(elementId) {
const text = document.getElementById(elementId).textContent;
try {
await navigator.clipboard.writeText(text);
this.toastManager.show('Copied to clipboard!', 'success');
} catch (err) {
this.toastManager.show('Failed to copy text', 'error');
}
}
// Loader and error handling
showLoader() {
this.isLoading = true;
this.elements.loader.classList.remove('hidden');
}
hideLoader() {
this.isLoading = false;
this.elements.loader.classList.add('hidden');
}
showError(message) {
this.elements.errorText.textContent = message;
this.elements.error.classList.remove('hidden');
this.elements.serverInfo.classList.add('hidden');
}
hideError() {
this.elements.error.classList.add('hidden');
}
// Player list manipulation
filterPlayers() {
const query = this.elements.playerSearch.value.trim().toLowerCase();
const filteredPlayers = this.players.filter(player =>
player.name.toLowerCase().includes(query)
);
this.updatePlayerList(filteredPlayers);
}
sortPlayers() {
const criteria = this.elements.playerSort.value;
let sortedPlayers = [...this.players];
if (criteria === 'name') {
sortedPlayers.sort((a, b) => a.name.localeCompare(b.name));
} else if (criteria === 'id') {
sortedPlayers.sort((a, b) => a.id - b.id);
} else if (criteria === 'ping') {
sortedPlayers.sort((a, b) => a.ping - b.ping);
}
this.updatePlayerList(sortedPlayers);
}
updatePlayerList(players) {
this.elements.playerList.innerHTML = ''; // Clear the existing list
players.forEach(player => {
const playerItem = document.createElement('div');
playerItem.className = 'player-item';
playerItem.innerHTML = `
<div class="player-info">
<span class="player-name">${this.escapeHtml(player.name)}</span>
<span class="player-id">#${player.id}</span>
</div>
<div class="player-stats">
<div class="stat">
<div class="stat-label">Ping</div>
<div class="stat-value">${player.ping}ms</div>
</div>
</div>
`;
this.elements.playerList.appendChild(playerItem);
});
}
escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// Start auto-refresh for player data every second
startAutoRefresh(serverCode) {
if (this.autoRefreshInterval) {
clearInterval(this.autoRefreshInterval); // Clear any existing interval
}
this.autoRefreshInterval = setInterval(async () => {
try {
const serverResponse = await fetch(`https://servers-frontend.fivem.net/api/servers/single/${serverCode}`);
const serverData = await serverResponse.json();
if (serverData.Data) {
const data = serverData.Data;
if (data.players) {
this.players = data.players;
this.updatePlayerList(data.players); // Update the player list with fresh data
}
}
} catch (error) {
console.error('Error refreshing player data:', error);
}
}, 1000); // Refresh every second
}
// Helper method to extract server code from input
extractServerCode(input) {
const match = input.match(/cfx\.re\/join\/([a-zA-Z0-9]+)/);
return match ? match[1] : null;
}
}
// Initialize the app when DOM is fully loaded
document.addEventListener('DOMContentLoaded', () => new CFXLookup());