/
web.go
109 lines (97 loc) · 2.49 KB
/
web.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
// Package web scrapes the strava website for functionality not available via the API.
//
// Inspired by https://github.com/pR0Ps/stravaweblib
package web
//go:generate genwith --client --ratelimit --package web
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"golang.org/x/net/publicsuffix"
"github.com/bzimmer/gravl/pkg"
"github.com/bzimmer/gravl/pkg/providers/activity"
)
const baseWebURL = "https://www.strava.com"
// Client client
type Client struct {
client *http.Client
Auth *AuthService
Export *ExportService
Fitness *FitnessService
}
func (c *Client) Exporter() activity.Exporter {
return c.Export
}
func withServices() Option {
return func(c *Client) error {
if c.client.Jar == nil {
return errors.New("no cookiejar set; use WithHTTPClient() or WithCookieJar()")
}
c.Auth = &AuthService{client: c}
c.Export = &ExportService{client: c}
c.Fitness = &FitnessService{client: c}
return nil
}
}
// WithCookieJar attaches a cookie jar to the client
func WithCookieJar() Option {
return func(c *Client) error {
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
return err
}
c.client.Jar = jar
return nil
}
}
func (c *Client) newWebRequest(ctx context.Context, method, uri string, values url.Values) (*http.Request, error) {
u, err := url.Parse(fmt.Sprintf("%s/%s", baseWebURL, uri))
if err != nil {
return nil, err
}
var b io.Reader
if values != nil {
b = strings.NewReader(values.Encode())
}
req, err := http.NewRequestWithContext(ctx, method, u.String(), b)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", pkg.UserAgent)
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
if values != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
return req, nil
}
// do executes the http request and populates v with the result.
func (c *Client) do(req *http.Request, v interface{}) error {
ctx := req.Context()
res, err := c.client.Do(req)
if err != nil {
select {
case <-ctx.Done():
return ctx.Err()
default:
return err
}
}
defer res.Body.Close()
if res.StatusCode >= http.StatusBadRequest {
return errors.New("something bad happened; enable --http-tracing to investigate")
}
if v != nil {
err := json.NewDecoder(res.Body).Decode(v)
if err == io.EOF {
err = nil // ignore EOF errors caused by empty response body
}
return err
}
return nil
}