-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
359 lines (311 loc) · 12.7 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
// Notification ko lagi
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(() => {
if (this.container.contains(toast)) {
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';
}
}
}
// Main class
class CFXLookup {
constructor() {
this.toastManager = new ToastManager();
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'),
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'),
};
this.addCopyButtonToServerIP();
this.players = [];
this.searchQuery = '';
this.sortCriteria = 'name';
this.autoRefreshInterval = null;
this.setInitialTheme();
this.setupEventListeners();
}
setInitialTheme() {
this.setTheme('dark');
}
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';
}
setupEventListeners() {
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();
});
// Player search and sort
this.elements.playerSearch.addEventListener('input', () => {
this.searchQuery = this.elements.playerSearch.value.trim().toLowerCase();
this.updatePlayerList(); // Refresh list with new filter
});
this.elements.playerSort.addEventListener('change', () => {
this.sortCriteria = this.elements.playerSort.value;
this.updatePlayerList(); // Refresh list with new sort
});
}
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 {
const isOnline = await this.checkServerStatus(serverCode);
if (!isOnline) {
this.toastManager.show('Server is currently offline or not found.', 'warning');
this.hideLoader();
return;
}
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 = '';
// Dherai janne manxey haru ko lagi
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);
this.startAutoRefresh(serverCode);
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 (err) {
return false;
}
}
extractServerCode(input) {
// 1) If it matches a direct cfx code, e.g. "abc123"
if (/^[a-zA-Z0-9]{6,}$/.test(input)) {
return input;
}
// 2) If it's a link with cfx.re/join/xxxxx
const match = input.match(/(?:https?:\/\/)?cfx\.re\/join\/([a-zA-Z0-9]+)/);
return match ? match[1] : null;
}
startAutoRefresh(serverCode) {
// Clear any old intervals
if (this.autoRefreshInterval) {
clearInterval(this.autoRefreshInterval);
}
// Refresh player list every second
this.autoRefreshInterval = setInterval(async () => {
try {
const response = await fetch(
`https://servers-frontend.fivem.net/api/servers/single/${serverCode}`
);
const data = await response.json();
if (data.Data && data.Data.players) {
this.players = data.Data.players;
this.updatePlayerList(); // re-render updated players
}
} catch (error) {
console.error('Error refreshing player data:', error);
}
}, 1000);
}
updateServerInfo(data, ipAddress) {
// Basic server info
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';
// Update player data in memory, then render them
this.players = data.players || [];
this.searchQuery = ''; // reset search on fresh load
this.elements.playerSearch.value = '';
this.sortCriteria = 'name';
this.elements.playerSort.value = 'name';
this.updatePlayerList();
}
cleanServerName(name) {
// Remove any color codes like ^1, ^2 etc.
return name.replace(/\^[0-9]/g, '').trim();
}
// Thau ko name haru ko location fetch garna
async fetchLocationInfo(ip) {
try {
const locationResponse = await fetch(`https://ipapi.co/${ip}/json/`);
const locationData = await locationResponse.json();
if (locationData.error) {
throw new Error('Location data not available.');
}
// Update location fields
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';
// ipapi.co often stores the region name in "region",
// region_code in "region_code" etc.
this.elements.region.textContent = locationData.region || 'N/A';
} catch (error) {
console.warn('Location lookup error:', error);
this.toastManager.show('Location lookup failed.', 'warning');
// If you have fallback logic, you can call it here.
}
}
updatePlayerList() {
// 1) Filter
let filtered = this.players.filter((p) =>
p.name.toLowerCase().includes(this.searchQuery)
);
// 2) Sort
if (this.sortCriteria === 'name') {
filtered.sort((a, b) => a.name.localeCompare(b.name));
} else if (this.sortCriteria === 'id') {
filtered.sort((a, b) => a.id - b.id);
} else if (this.sortCriteria === 'ping') {
filtered.sort((a, b) => a.ping - b.ping);
}
// 3) Render
this.elements.playerList.innerHTML = '';
filtered.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;
}
addCopyButtonToServerIP() {
const copyButton = document.createElement('button');
copyButton.className = 'copy-button';
copyButton.innerHTML = '<i class="fas fa-copy"></i>';
copyButton.onclick = () => this.copyToClipboard('serverIP');
const parent = this.elements.serverIP.parentNode;
parent.style.display = 'flex';
parent.style.alignItems = 'center';
parent.appendChild(copyButton);
}
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');
}
}
showLoader() {
this.elements.loader.classList.remove('hidden');
}
hideLoader() {
this.elements.loader.classList.add('hidden');
}
hideError() {
this.elements.error.classList.add('hidden');
}
}
// Suru choti call garna
document.addEventListener('DOMContentLoaded', () => new CFXLookup());