aboutsummaryrefslogtreecommitdiff
path: root/country.go
blob: f3d49b0a60fc62f77090a6da0184b5102e41a5d9 (plain)
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
package sws

import (
	"net"
	"sort"

	maxminddb "github.com/oschwald/maxminddb-golang"
)

type Country struct {
	Name   string `json:"name"`
	hitSet *HitSet
}

type CountrySet []*Country

func NewCountrySet(hs *HitSet) *CountrySet {
	tmp := make(map[string]*Country)
	for _, h := range hs.Hits() {
		if h.CountryCode == nil {
			continue
		}
		cc := *h.CountryCode

		if _, ok := tmp[cc]; ok {
			// Already captured this country
			continue
		}
		b := &Country{
			Name: cc,
			//LastSeenAt: h.CreatedAt,
			hitSet: hs.Filter(func(t *Hit) bool {
				return t.CountryCode != nil && *t.CountryCode == cc
			}),
		}
		tmp[cc] = b
	}
	if len(tmp) < 1 {
		return nil
	}
	out := make([]*Country, len(tmp))
	i := 0
	for _, b := range tmp {
		out[i] = b
		i++
	}
	cs := CountrySet(out)
	return &cs
}

func (cs *CountrySet) SortByHits() {
	sort.Slice(*cs, func(i, j int) bool {
		return (*cs)[i].hitSet.Count() > (*cs)[j].hitSet.Count()
	})
}

func (c Country) Label() string {
	return c.Name
}

func (c Country) Count() int {
	return c.hitSet.Count()
}

func (cs CountrySet) Count() int {
	return len(cs)
}

func (cs CountrySet) YMax() int {
	max := 0
	for _, c := range cs {
		if c.hitSet.Count() > max {
			max = c.hitSet.Count()
		}
	}
	return max
}
func (cs CountrySet) YSum() int {
	sum := 0
	for _, c := range cs {
		sum += c.hitSet.Count()
	}
	return sum
}
func (cs CountrySet) XSeries() []*Country {
	return cs
}

func FetchCountryCode(path, host string) (*string, error) {
	db, err := maxminddb.Open(path)
	if err != nil {
		return nil, err
	}
	defer db.Close()

	ip := net.ParseIP(host)
	var r struct {
		Country struct {
			ISOCode string `maxminddb:"iso_code"`
		} `maxminddb:"country"`
	}
	if err := db.Lookup(ip, &r); err != nil {
		return nil, err
	}
	return &r.Country.ISOCode, nil
}