File size: 2,086 Bytes
6f6d8a6
 
feb8590
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f6d8a6
75f825b
cd5701b
75f825b
 
 
 
cd5701b
 
75f825b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d2b84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// place files you want to import through the `$lib` alias in this folder.

import { majorAirportIATAs } from '$lib/icao';

interface ClientInfo {
	clientIp: string;
	clientLocation: string;
}

export async function getClientInfo(): Promise<ClientInfo> {
	let clientIp = 'Detecting...';
	let clientLocation = 'Detecting...';
	const res = await fetch('https://ipapi.co/json/');
	clientIp = 'Not available';
	clientLocation = 'Not available';
	if (res.ok) {
		const data = await res.json();
		clientIp = data.ip || 'Unknown';
		let location = '';
		if (data.city) location += data.city + ', ';
		if (data.region) location += data.region + ', ';
		if (data.country_name) location += data.country_name;
		clientLocation = location || 'Unknown';
	}
	return new Promise((resolve) =>
		resolve({
			clientIp,
			clientLocation
		})
	);
}

export async function sendAnalyticsData(bytesPerSecond: number, latency: number, location: string, progress: number) {
	// send measurements to analytics API
	const measurements = {
		bandwidth: bytesPerSecond,
		latency,
		location,
		progress
	};
	console.log('Sending analytics data');
	return new Promise((resolve) => {
		fetch('/analytics', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify(measurements)
		})
			.then((response) => {
				if (!response.ok) {
					throw new Error(`Network response was not ok: ${response.status}`);
				}
				resolve(response);
			})
			.catch((error) => {
				console.error('Error sending bandwidth data:', error);
				resolve(null);
			});
	});
}

export async function getServerLocation(url: string): Promise<string> {
	// Get server location
	const response = await fetch(url, { method: 'HEAD' });
	let cdnPop = response.headers.get('x-amz-cf-pop');
	if (cdnPop !== null) {
		cdnPop = cdnPop.toUpperCase().slice(0, 3);
		// try to map to IATA
		if (cdnPop in majorAirportIATAs) {
			cdnPop = majorAirportIATAs[cdnPop].city + ', ' + majorAirportIATAs[cdnPop].country;
		} else {
			cdnPop = 'Unknown';
		}
	} else {
		cdnPop = 'Unknown';
	}

	return cdnPop;
}