aboutsummaryrefslogtreecommitdiff
path: root/referrer.go
blob: cbb11984d37b5fe6c2cebc147183a80ce35eef92 (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
107
108
109
110
111
112
113
114
115
116
117
package sws

import (
	"net/url"
	"sort"
	"strings"
	"time"
)

type Referrer struct {
	Name       string    `json:"name"`
	LastSeenAt time.Time `json:"last_seen_at" db:"last_seen_at"`
	hitSet     *HitSet
}

type ReferrerSet []*Referrer

func NewReferrerSet(hs *HitSet) *ReferrerSet {
	tmp := make(map[string]*Referrer)
	for _, h := range hs.Hits() {
		if h.Referrer == nil {
			continue
		}

		u, err := url.Parse(*h.Referrer)
		if err != nil || h.Host == u.Host {
			continue
		}
		host := u.Host
		if u.Host == "" {
			host = "direct"
		}
		r := &Referrer{
			Name:       host,
			LastSeenAt: h.CreatedAt,
			hitSet: hs.Filter(func(t *Hit) bool {
				if t.Referrer == nil {
					return false
				}
				return strings.Contains(*t.Referrer, u.Host)
			}),
		}
		// if b.LastSeenAt.Before(h.CreatedAt) {
		// 	b.LastSeenAt = h.CreatedAt
		// }
		//b.hitSet.Add(h)
		tmp[u.Host] = r
	}
	if len(tmp) < 1 {
		return nil
	}
	out := make([]*Referrer, len(tmp))
	i := 0
	for _, b := range tmp {
		out[i] = b
		i++
	}
	rs := ReferrerSet(out)
	return &rs
}

func (rs *ReferrerSet) SortByName() {
	sort.Slice(*rs, func(i, j int) bool {
		return (*rs)[i].Name < (*rs)[j].Name
	})
}

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

func (rs ReferrerSet) Count() int {
	return len(rs)
}

func (rs ReferrerSet) GetReferrer(s string) *Referrer {
	for _, r := range rs {
		if r.Name == s {
			return r
		}
	}
	return nil
}

func (r Referrer) Label() string {
	return r.Name
}

func (r Referrer) Count() int {
	return r.hitSet.Count()
}

func (r Referrer) YValue() int {
	return r.hitSet.Count()
}

func (rs ReferrerSet) YMax() int {
	max := 0
	for _, r := range rs {
		if r.hitSet.Count() > max {
			max = r.hitSet.Count()
		}
	}
	return max
}
func (rs ReferrerSet) YSum() int {
	sum := 0
	for _, r := range rs {
		sum += r.hitSet.Count()
	}
	return sum
}
func (rs ReferrerSet) XSeries() []*Referrer {
	return rs
}