-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
415 lines (356 loc) · 15.1 KB
/
index.html
File metadata and controls
415 lines (356 loc) · 15.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ping Test</title>
<style>
/* Container for grid layout */
#ping-results {
display: grid;
grid-template-columns: repeat(4, 1fr);
/* Four equal columns */
gap: 20px;
/* Add some space between the columns */
padding: 20px;
}
/* Styling for each server section */
.server-section {
border: 1px solid #ccc;
border-radius: 8px;
padding: 10px;
background-color: #f9f9f9;
}
h2 {
text-align: center;
font-size: 18px;
margin-bottom: 10px;
}
ul {
list-style-type: none;
padding-left: 0;
max-height: 200px;
/* Max height to prevent overflow */
overflow-y: auto;
/* Scroll if list gets too long */
}
ul li {
padding: 5px 0;
border-bottom: 1px solid #ddd;
}
p {
font-weight: bold;
text-align: center;
margin-top: 10px;
/* Ensure margin to separate from list */
}
/* Progress bar container */
#progress-container {
margin: 20px auto;
width: 80%;
background-color: #e0e0e0;
border-radius: 25px;
overflow: hidden;
position: relative;
height: 30px;
}
/* Progress bar fill */
#progress-bar {
width: 0%;
height: 100%;
background-color: #4CAF50;
transition: width 0.5s ease;
}
/* Timer display */
#timer {
text-align: center;
font-size: 18px;
margin-top: 10px;
}
/* Export button styling */
#export-btn {
display: block;
margin: 20px auto;
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 8px;
cursor: not-allowed;
opacity: 0.5;
position: relative;
}
/* Tooltip container */
#export-btn:hover::after {
content: attr(data-hover);
position: absolute;
bottom: -35px;
left: 50%;
transform: translateX(-50%);
background-color: #333;
color: #fff;
padding: 5px;
border-radius: 5px;
font-size: 12px;
white-space: nowrap;
opacity: 0;
transition: opacity 0.3s ease;
pointer-events: none;
visibility: hidden;
}
/* Show tooltip when hovered */
#export-btn:hover:enabled::after {
visibility: hidden;
}
#export-btn:hover:disabled::after {
visibility: visible;
opacity: 1;
}
#export-btn:enabled {
cursor: pointer;
opacity: 1;
}
</style>
</head>
<body>
<h1>Ping Test Results</h1>
<!-- Explanation Section -->
<div id="explanation">
<h3>Why are we doing this?</h3>
<p>
We are conducting this test to determine the best location to host our FiveM server for optimal performance.
By measuring your connection to different server regions (Chicago, Dallas, Miami, and New York), we can
determine which location offers the lowest latency.
</p>
<p>
All data collected is confidential and secure. No private information is collected or stored; only
non-identifiable information such as your connection speed to these servers is used.
</p>
</div>
<!-- Progress Bar -->
<div id="progress-container">
<div id="progress-bar"></div>
</div>
<!-- Timer -->
<div id="timer">Estimated time remaining: calculating...</div>
<p id="location-info">Detecting your location...</p>
<div id="ping-results"></div>
<button id="export-btn" data-hover="You need 120 pings to enable export" disabled>Export Pings to JSON</button>
<script>
let userLocation = '';
let userLat = '';
let userLon = '';
const totalPings = 120; // Total number of pings to collect
const pingInterval = 1000 / 4; // 4 pings per second (1000ms / 4 = 250ms between each ping)
// Servers and their coordinates for distance calculation
const servers = {
'Chicago': {
url: 'http://ping.chi.scdb.gg',
lat: 41.8781,
lon: -87.6298,
pings: []
},
'Dallas': {
url: 'http://ping.dal.scdb.gg',
lat: 32.7767,
lon: -96.7970,
pings: []
},
'Miami': {
url: 'http://ping.mia.scdb.gg',
lat: 25.7617,
lon: -80.1918,
pings: []
},
'New York': {
url: 'http://ping.nyc.scdb.gg',
lat: 40.7128,
lon: -74.0060,
pings: []
}
};
const resultsElement = document.getElementById('ping-results');
const exportBtn = document.getElementById('export-btn');
const progressBar = document.getElementById('progress-bar');
const timerElement = document.getElementById('timer');
// Initialize results storage and display containers for each server
for (const name in servers) {
createServerSection(name);
}
// Function to create a section for each server
function createServerSection(name) {
const section = document.createElement('div');
section.classList.add('server-section'); // Add class for styling
const header = document.createElement('h2');
header.textContent = `${name} Ping Results`;
const average = document.createElement('p');
average.id = `average-${name}`;
average.textContent = `Average: calculating...`;
const distance = document.createElement('p');
distance.id = `distance-${name}`;
distance.textContent = `Distance: calculating...`;
const list = document.createElement('ul');
list.id = `ping-list-${name}`;
section.appendChild(header);
section.appendChild(average); // Average is below the header but above the list
section.appendChild(distance); // Distance below the average
section.appendChild(list);
resultsElement.appendChild(section);
}
// Function to ping a server using HTTP
async function pingServerHTTP(name, url) {
const startTime = Date.now(); // Record the time before the request
try {
const response = await fetch(url, {
method: 'GET',
mode: 'cors'
});
if (response.ok) {
const endTime = Date.now(); // Record the time after the response is received
const ping = endTime - startTime; // Calculate the time difference (ping)
servers[name].pings.push(ping); // Store the ping result
if (servers[name].pings.length > totalPings) servers[name].pings
.shift(); // Keep only the last 120 pings
updateResults(name); // Update the results in real-time
updateProgressBarAndTimer(); // Update progress bar and timer
checkExportAvailability(); // Check if export should be enabled
} else {
appendPing(name, 'Failed to ping');
}
} catch (error) {
appendPing(name, 'Failed to ping');
}
}
// Function to calculate the average ping for a server after removing outliers
function calculateAverageWithoutOutliers(pings) {
if (pings.length <= 2) return pings.length > 0 ? pings[0] : 0; // If only 1-2 pings, return the raw average
// Sort the pings
const sortedPings = [...pings].sort((a, b) => a - b);
// Remove the top 10% and bottom 10% (for 120 values, this is the top and bottom 60)
const trimCount = Math.floor(sortedPings.length * 0.1); // 10% trimming
const trimmedPings = sortedPings.slice(trimCount, sortedPings.length - trimCount);
// Calculate the average of the remaining pings
const sum = trimmedPings.reduce((a, b) => a + b, 0);
return (sum / trimmedPings.length).toFixed(2);
}
// Function to update the displayed results
function updateResults(name) {
const pings = servers[name].pings;
const averagePing = calculateAverageWithoutOutliers(pings);
const list = document.getElementById(`ping-list-${name}`);
const average = document.getElementById(`average-${name}`);
// Update the average display
average.textContent = `Average (without outliers): ${averagePing} ms (Last ${pings.length} pings)`;
// Clear and re-populate the list only when new pings are added
if (pings.length > 0) {
const newPing = pings[pings.length - 1];
appendPing(name, `${pings.length}: ${newPing} ms`);
}
}
// Function to append a single ping result to the list without clearing
function appendPing(name, pingText) {
const list = document.getElementById(`ping-list-${name}`);
const li = document.createElement('li');
li.textContent = pingText;
list.appendChild(li);
}
// Function to update the progress bar and estimated time remaining
function updateProgressBarAndTimer() {
const totalPingsRecorded = Object.values(servers).reduce((sum, server) => sum + server.pings.length, 0);
const percentageComplete = (totalPingsRecorded / (totalPings * Object.keys(servers).length)) * 100;
progressBar.style.width = `${percentageComplete}%`;
// Calculate remaining pings and time
const pingsLeft = (totalPings * Object.keys(servers).length) - totalPingsRecorded;
const timeRemaining = (pingsLeft * pingInterval) / 1000; // seconds
// Display the estimated time remaining in minutes and seconds
const minutes = Math.floor(timeRemaining / 60);
const seconds = Math.floor(timeRemaining % 60);
timerElement.textContent = `Estimated time remaining: ${minutes}m ${seconds}s`;
}
// Check if we can enable the export button (only when all servers have 120 pings)
function checkExportAvailability() {
const allServersReachedLimit = Object.values(servers).every(server => server.pings.length >= totalPings);
if (allServersReachedLimit) {
exportBtn.disabled = false;
exportBtn.style.cursor = 'pointer';
}
}
// Function to generate a timestamped filename
function getTimestampedFilename() {
const now = new Date();
const timestamp = now.toISOString().replace(/[-:]/g, '').split('.')[0]; // YYYYMMDDTHHMMSS
return `pings_${timestamp}.json`;
}
// Function to export pings and location data to a JSON file
function exportToJson() {
const exportData = {
location: userLocation,
servers: {}
};
// Add ping data for each server
for (const [name, server] of Object.entries(servers)) {
exportData.servers[name] = {
distance: document.getElementById(`distance-${name}`).textContent,
pings: server.pings
};
}
const jsonString = JSON.stringify(exportData, null, 2); // Pretty-print the JSON
const blob = new Blob([jsonString], {
type: 'application/json'
});
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = getTimestampedFilename();
link.click();
}
// Function to calculate the distance between two lat/lon pairs using the Haversine formula
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 3958.8; // Radius of the Earth in miles
const dLat = (lat2 - lat1) * (Math.PI / 180);
const dLon = (lon2 - lon1) * (Math.PI / 180);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c;
return distance.toFixed(2);
}
// Function to get user's location via IP and calculate distances to server regions
async function getLocationAndCalculateDistances() {
try {
const response = await fetch('http://ip-api.com/json'); // IP-based location API
const data = await response.json();
if (data.status === 'success') {
userLat = data.lat;
userLon = data.lon;
userLocation = `${data.regionName}, ${data.country}`; // Only show state/region and country
document.getElementById('location-info').textContent = `Your location: ${userLocation}`;
for (const [name, server] of Object.entries(servers)) {
const distance = calculateDistance(userLat, userLon, server.lat, server.lon);
document.getElementById(`distance-${name}`).textContent = `Distance: ${distance} miles`;
}
} else {
document.getElementById('location-info').textContent = 'Unable to retrieve location.';
}
} catch (error) {
document.getElementById('location-info').textContent = 'Error fetching location.';
}
}
// Ping each server 4 times per second (each with a static delay between requests)
function startPinging() {
let delay = 0;
for (const [name, server] of Object.entries(servers)) {
setInterval(() => pingServerHTTP(name, server.url), pingInterval + delay);
delay += pingInterval; // Add 250ms delay between each server's requests
}
}
// Start the IP-based geolocation and ping process
getLocationAndCalculateDistances();
startPinging(); // Start the pinging process
// Set up the export button
exportBtn.addEventListener('click', exportToJson);
</script>
</body>
</html>