-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathumami.go
More file actions
435 lines (371 loc) · 10.2 KB
/
Copy pathumami.go
File metadata and controls
435 lines (371 loc) · 10.2 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const metricTypePath = "path"
type UmamiClient struct {
baseURL string
username string
password string
apiKey string
apiBasePath string
token string
teamID string
httpClient *http.Client
}
func NewUmamiClient(baseURL, username, password string) *UmamiClient {
return &UmamiClient{
baseURL: strings.TrimSuffix(baseURL, "/"),
username: username,
password: password,
apiBasePath: "/api",
httpClient: &http.Client{Timeout: 30 * time.Second},
}
}
func NewUmamiClientWithAPIKey(baseURL, apiKey string) *UmamiClient {
return &UmamiClient{
baseURL: strings.TrimSuffix(baseURL, "/"),
apiKey: apiKey,
apiBasePath: "/v1",
httpClient: &http.Client{Timeout: 30 * time.Second},
}
}
func (c *UmamiClient) basePath() string {
if c.apiBasePath == "" {
return "/api"
}
return c.apiBasePath
}
func (c *UmamiClient) websitesPath() string {
return c.basePath() + "/websites"
}
func (c *UmamiClient) Authenticate() error {
if c.apiKey != "" {
return nil
}
payload := map[string]string{
"username": c.username,
"password": c.password,
}
data, _ := json.Marshal(payload)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/auth/login", bytes.NewReader(data))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("authentication request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("authentication failed with status %d", resp.StatusCode)
}
var result struct {
Token string `json:"token"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("failed to decode auth response: %w", err)
}
c.token = result.Token
return nil
}
func (c *UmamiClient) doRequest(path string, params map[string]string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, http.NoBody)
if err != nil {
return nil, err
}
if params != nil {
q := req.URL.Query()
for k, v := range params {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
if c.apiKey != "" {
req.Header.Set("x-umami-api-key", c.apiKey)
} else {
req.Header.Set("Authorization", "Bearer "+c.token)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
}
return body, nil
}
type Website struct {
ID string `json:"id"`
Name string `json:"name"`
Domain string `json:"domain"`
CreatedAt time.Time `json:"createdAt"`
}
func (c *UmamiClient) GetWebsites(includeTeams bool) ([]Website, error) {
var endpoint string
var params map[string]string
if c.teamID != "" {
endpoint = fmt.Sprintf("%s/teams/%s/websites", c.basePath(), c.teamID)
} else {
endpoint = c.websitesPath()
if includeTeams {
params = map[string]string{"includeTeams": "true"}
}
}
data, err := c.doRequest(endpoint, params)
if err != nil {
return nil, err
}
var result struct {
Data []Website `json:"data"`
}
if err := json.Unmarshal(data, &result); err != nil {
return nil, err
}
return result.Data, nil
}
type Stats struct {
PageViews int `json:"pageviews"`
Visitors int `json:"visitors"`
Visits int `json:"visits"`
Bounces int `json:"bounces"`
TotalTime int `json:"totaltime"`
Comparison *StatsComparison `json:"comparison,omitempty"`
}
type StatsComparison struct {
PageViews int `json:"pageviews"`
Visitors int `json:"visitors"`
Visits int `json:"visits"`
Bounces int `json:"bounces"`
TotalTime int `json:"totaltime"`
}
func (c *UmamiClient) GetStats(websiteID, startDate, endDate string) (*Stats, error) {
params := map[string]string{
"startAt": startDate,
"endAt": endDate,
}
data, err := c.doRequest(fmt.Sprintf("%s/%s/stats", c.websitesPath(), websiteID), params)
if err != nil {
return nil, err
}
var stats Stats
if err := json.Unmarshal(data, &stats); err != nil {
return nil, err
}
return &stats, nil
}
type PageView struct {
T string `json:"t"`
Y int `json:"y"`
}
func (c *UmamiClient) GetPageViews(websiteID, startDate, endDate, unit string) ([]PageView, error) {
params := map[string]string{
"startAt": startDate,
"endAt": endDate,
"unit": unit,
}
data, err := c.doRequest(fmt.Sprintf("%s/%s/pageviews", c.websitesPath(), websiteID), params)
if err != nil {
return nil, err
}
var response struct {
PageViews []PageView `json:"pageviews"`
Sessions []PageView `json:"sessions"`
}
if err := json.Unmarshal(data, &response); err != nil {
var pageviews []PageView
if err2 := json.Unmarshal(data, &pageviews); err2 != nil {
return nil, err
}
return pageviews, nil
}
return response.PageViews, nil
}
type Metric struct {
X string `json:"x"`
Y int `json:"y"`
}
func (c *UmamiClient) GetMetrics(websiteID, startDate, endDate, metricType string, limit int) ([]Metric, error) {
// Map legacy "url" type to current "path" type (renamed Oct 2025)
if metricType == "url" {
metricType = metricTypePath
}
params := map[string]string{
"startAt": startDate,
"endAt": endDate,
"type": metricType,
"limit": fmt.Sprintf("%d", limit),
}
data, err := c.doRequest(fmt.Sprintf("%s/%s/metrics", c.websitesPath(), websiteID), params)
if err != nil {
return nil, err
}
var metrics []Metric
if err := json.Unmarshal(data, &metrics); err != nil {
return nil, err
}
return metrics, nil
}
func (c *UmamiClient) GetActive(websiteID string) ([]Metric, error) {
data, err := c.doRequest(fmt.Sprintf("%s/%s/active", c.websitesPath(), websiteID), nil)
if err != nil {
return nil, err
}
var response []struct {
X int `json:"x"`
Y int `json:"y"`
}
if err := json.Unmarshal(data, &response); err != nil {
var singleResponse struct {
X int `json:"x"`
}
if err2 := json.Unmarshal(data, &singleResponse); err2 != nil {
return nil, err
}
return []Metric{{X: fmt.Sprintf("%d", singleResponse.X), Y: singleResponse.X}}, nil
}
metrics := make([]Metric, len(response))
for i, r := range response {
metrics[i] = Metric{X: fmt.Sprintf("%d", r.X), Y: r.Y}
}
return metrics, nil
}
type Session struct {
ID string `json:"id"`
WebsiteID string `json:"websiteId"`
Hostname string `json:"hostname"`
Browser string `json:"browser"`
OS string `json:"os"`
Device string `json:"device"`
Screen string `json:"screen"`
Language string `json:"language"`
Country string `json:"country"`
Region string `json:"region"`
City string `json:"city"`
FirstAt time.Time `json:"firstAt"`
LastAt time.Time `json:"lastAt"`
Visits int `json:"visits"`
Views int `json:"views"`
CreatedAt time.Time `json:"createdAt"`
}
type SessionList struct {
Data []Session `json:"data"`
Count int `json:"count"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
}
func (c *UmamiClient) GetSessions(
websiteID, startDate, endDate, search string, page, pageSize int,
) (*SessionList, error) {
params := map[string]string{
"startAt": startDate,
"endAt": endDate,
}
if search != "" {
params["search"] = search
}
if page > 0 {
params["page"] = fmt.Sprintf("%d", page)
}
if pageSize > 0 {
params["pageSize"] = fmt.Sprintf("%d", pageSize)
}
data, err := c.doRequest(fmt.Sprintf("%s/%s/sessions", c.websitesPath(), websiteID), params)
if err != nil {
return nil, err
}
var result SessionList
if err := json.Unmarshal(data, &result); err != nil {
return nil, err
}
return &result, nil
}
type SessionStats struct {
PageViews int `json:"pageviews"`
Visitors int `json:"visitors"`
Visits int `json:"visits"`
Countries int `json:"countries"`
Events int `json:"events"`
}
type valueField struct {
Value int `json:"value"`
}
func (c *UmamiClient) GetSessionStats(websiteID, startDate, endDate string) (*SessionStats, error) {
params := map[string]string{
"startAt": startDate,
"endAt": endDate,
}
data, err := c.doRequest(fmt.Sprintf("%s/%s/sessions/stats", c.websitesPath(), websiteID), params)
if err != nil {
return nil, err
}
var raw struct {
PageViews valueField `json:"pageviews"`
Visitors valueField `json:"visitors"`
Visits valueField `json:"visits"`
Countries valueField `json:"countries"`
Events valueField `json:"events"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return nil, err
}
return &SessionStats{
PageViews: raw.PageViews.Value,
Visitors: raw.Visitors.Value,
Visits: raw.Visits.Value,
Countries: raw.Countries.Value,
Events: raw.Events.Value,
}, nil
}
type SessionActivity struct {
CreatedAt time.Time `json:"createdAt"`
URLPath string `json:"urlPath"`
URLQuery string `json:"urlQuery"`
ReferrerDomain string `json:"referrerDomain"`
EventID string `json:"eventId"`
EventType int `json:"eventType"`
EventName string `json:"eventName"`
VisitID string `json:"visitId"`
HasData bool `json:"hasData"`
}
func (c *UmamiClient) GetSessionActivity(websiteID, sessionID, startDate, endDate string) ([]SessionActivity, error) {
if startDate == "" {
startDate = "0"
}
if endDate == "" {
endDate = fmt.Sprintf("%d", time.Now().UnixMilli())
}
params := map[string]string{
"startAt": startDate,
"endAt": endDate,
}
data, err := c.doRequest(
fmt.Sprintf("%s/%s/sessions/%s/activity", c.websitesPath(), websiteID, sessionID), params,
)
if err != nil {
return nil, err
}
var activity []SessionActivity
if err := json.Unmarshal(data, &activity); err != nil {
return nil, err
}
return activity, nil
}