-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcounter.js
71 lines (62 loc) · 1.34 KB
/
counter.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
import geoip from 'geoip-lite'
import DeviceDetector from 'node-device-detector'
const detector = new DeviceDetector({
clientIndexes: true,
deviceIndexes: true,
deviceAliasCode: false,
})
export class Counter {
constructor(ip, headers) {
this.day = this.getDay()
const {country = '-'} = this.lookupGeoip(ip, headers) || {}
this.stats = {country}
const referer = headers['referer']
this.setReferer(referer)
const userAgent = headers['user-agent']
this.setUserAgent(userAgent)
}
getDay() {
const timestamp = new Date()
return timestamp.toISOString().substring(0, 10)
}
setReferer(referer) {
if (!referer) {
return
}
const url = new URL(referer)
this.site = url.host
this.page = url.pathname
}
setUserAgent(userAgent) {
if (!userAgent) {
return
}
const device = this.getDevice(userAgent)
// transfer to stats
for (const key in device) {
this.stats[key] = device[key]
}
}
getDevice(userAgent) {
if (!userAgent) {
return null
}
const device = detector.detect(userAgent)
return {
type: device.device.type,
os: device.os.name,
platform: device.os.platform,
browser: device.client.name,
}
}
lookupGeoip(ip, headers) {
if (ip != '127.0.0.1') {
return geoip.lookup(ip)
}
const realIp = headers['x-real-ip']
if (!realIp) {
return {}
}
return geoip.lookup(realIp)
}
}