-
Notifications
You must be signed in to change notification settings - Fork 0
/
dao.go
153 lines (138 loc) · 3.61 KB
/
dao.go
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package dao
import (
"code.google.com/p/goauth2/oauth/jwt"
"code.google.com/p/google-api-go-client/analytics/v3"
"encoding/gob"
"encoding/json"
resourcelocator "github.com/baardsen/resourcelocator"
"log"
"os"
"strconv"
"time"
)
type Point struct {
Time int64 `json:"x"`
Value int `json:"y"`
}
type Series struct {
Name string `json:"name"`
Data []Point `json:"data"`
}
type measure struct {
Name string
Time int64
Value int
}
var config struct {
Profile string
ClientId string
ClientEmail string
CertificateFile string
Certificate []byte
TokenUri string
}
func Init() {
tokData := resourcelocator.Locate("/resources/config.json")
if err := json.Unmarshal(tokData, &config); err != nil {
log.Fatal("dao.init", err)
}
config.Certificate = resourcelocator.Locate(config.CertificateFile)
cacheFile := os.TempDir() + string(os.PathSeparator) + "browserusage.dat"
if file, err := os.Open(cacheFile); err != nil {
log.Println("Couldn't open cacheFile: "+cacheFile, err)
} else {
decoder := gob.NewDecoder(file)
decoder.Decode(&cache)
file.Close()
}
Query(firstDate, time.Now())
if file, err := os.Create(cacheFile); err != nil {
log.Println("Couldn't create cacheFile: "+cacheFile, err)
} else {
encoder := gob.NewEncoder(file)
encoder.Encode(cache)
file.Close()
}
}
var firstDate = time.Date(2012, 4, 16, 0, 0, 0, 0, time.UTC)
func Query(from, to time.Time) []Series {
from = from.In(time.UTC).AddDate(0, 0, int(time.Monday-from.Weekday()))
if from.Before(firstDate) {
from = firstDate
}
if to.IsZero() || to.After(time.Now()) {
to = time.Now()
}
dataGaService := createDataService()
ch := make(chan measure)
done := make(chan struct{})
counter := 0
for from.Before(to) {
counter++
go makeRequest(dataGaService, from, ch, done)
if cache[from] == nil {
time.Sleep(1 * time.Second)
}
from = from.AddDate(0, 0, 7)
}
values := make(map[string][]Point, 0)
for {
select {
case m := <-ch:
browser := m.Name
points := values[browser]
if points == nil {
points = make([]Point, 0)
}
values[browser] = append(points, Point{m.Time, m.Value})
case <-done:
counter--
if counter == 0 {
close(ch)
close(done)
series := make([]Series, 0)
for name, points := range values {
series = append(series, Series{name, points})
}
return sortSeries(series)
}
}
}
}
const format = "2006-01-02"
var cache = make(map[time.Time][][]string)
func makeRequest(dataGaService *analytics.DataGaService, from time.Time, ch chan measure, done chan struct{}) {
defer func() {
done <- struct{}{}
}()
if from.AddDate(0, 0, 7).After(time.Now()) {
return
}
rows := cache[from]
if rows == nil {
log.Println("Sending request: " + from.Format(format))
dataGaGetCall := dataGaService.Get(config.Profile, from.Format(format), from.AddDate(0, 0, 6).Format(format), "ga:users")
dataGaGetCall.Dimensions("ga:browser")
gaData, err := dataGaGetCall.Do()
if err != nil {
log.Fatal("GaData:", err)
}
rows = gaData.Rows
cache[from] = rows
}
for _, arr := range rows {
count, _ := strconv.Atoi(arr[1])
ch <- measure{arr[0], from.Unix() * 1000, count}
}
}
func createDataService() *analytics.DataGaService {
// Craft the ClaimSet and JWT token.
token := jwt.NewToken(config.ClientEmail, analytics.AnalyticsReadonlyScope, config.Certificate)
//token.ClaimSet.Aud = config.TokenUri
transport, err := jwt.NewTransport(token)
if err != nil {
log.Fatalf("failed to create authenticated transport: %+v.", err)
}
analyticsService, _ := analytics.New(transport.Client())
return analytics.NewDataGaService(analyticsService)
}