forked from umami-software/umami
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
83 lines (69 loc) · 1.91 KB
/
request.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
import requestIp from 'request-ip';
import { browserName, detectOS } from 'detect-browser';
import isLocalhost from 'is-localhost-ip';
import maxmind from 'maxmind';
import geolite2 from 'geolite2-redist';
import {
DESKTOP_OS,
MOBILE_OS,
DESKTOP_SCREEN_WIDTH,
LAPTOP_SCREEN_WIDTH,
MOBILE_SCREEN_WIDTH,
} from './constants';
export function getIpAddress(req) {
// Cloudflare
if (req.headers['cf-connecting-ip']) {
return req.headers['cf-connecting-ip'];
}
return requestIp.getClientIp(req);
}
export function getDevice(screen, browser, os) {
if (!screen) return;
const [width] = screen.split('x');
if (DESKTOP_OS.includes(os)) {
if (os === 'Chrome OS' || width < DESKTOP_SCREEN_WIDTH) {
return 'laptop';
}
return 'desktop';
} else if (MOBILE_OS.includes(os)) {
if (os === 'Amazon OS' || width > MOBILE_SCREEN_WIDTH) {
return 'tablet';
}
return 'mobile';
}
if (width >= DESKTOP_SCREEN_WIDTH) {
return 'desktop';
} else if (width >= LAPTOP_SCREEN_WIDTH) {
return 'laptop';
} else if (width >= MOBILE_SCREEN_WIDTH) {
return 'tablet';
} else {
return 'mobile';
}
}
export async function getCountry(req, ip) {
// Cloudflare
if (req.headers['cf-ipcountry']) {
return req.headers['cf-ipcountry'];
}
// Ignore local ips
if (await isLocalhost(ip)) {
return;
}
// Database lookup
const lookup = await geolite2.open('GeoLite2-Country', path => {
return maxmind.open(path);
});
const result = lookup.get(ip);
lookup.close();
return result.country.iso_code;
}
export async function getClientInfo(req, { screen }) {
const userAgent = req.headers['user-agent'];
const ip = getIpAddress(req);
const country = await getCountry(req, ip);
const browser = browserName(userAgent);
const os = detectOS(userAgent);
const device = getDevice(screen, browser, os);
return { userAgent, browser, os, ip, country, device };
}