-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
277 lines (207 loc) · 6.32 KB
/
main.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
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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/spf13/viper"
"golang.org/x/oauth2"
models "github.com/marekq/go-whoop/model"
)
// Check error, exit if error
func check(e error) {
if e != nil {
fmt.Println(e)
panic(e)
}
}
func readLocalToken() oauth2.Token {
f, err := os.Open("token.json")
check(err)
defer f.Close()
var token oauth2.Token
json.NewDecoder(f).Decode(&token)
return token
}
func writeLocalToken(token *oauth2.Token) {
f, err := os.Create("token.json")
check(err)
defer f.Close()
json, err := json.Marshal(token)
check(err)
f.WriteString(string(json))
}
func getOauthConfig() (*oauth2.Config, string, string) {
// Read config file from .env
viper.SetConfigFile(".env")
viper.ReadInConfig()
// Set API key and profile from config file
ClientID := viper.GetString("ClientID")
ClientSecret := viper.GetString("ClientSecret")
// Check ClientID and ClientSecret values exist
if ClientID == "" || ClientSecret == "" {
fmt.Println("ClientID and ClientSecret must be set in .env file")
os.Exit(1)
}
// Set OAuth2 config
conf := &oauth2.Config{
ClientID: ClientID,
ClientSecret: ClientSecret,
Scopes: []string{
"offline",
"read:recovery",
"read:cycles",
"read:workout",
"read:sleep",
"read:profile",
"read:body_measurement",
},
RedirectURL: "https://coldstart.dev/",
Endpoint: oauth2.Endpoint{
AuthURL: "https://api.prod.whoop.com/oauth/oauth2/auth",
TokenURL: "https://api.prod.whoop.com/oauth/oauth2/token",
},
}
return conf, ClientID, ClientSecret
}
// Load oauth2 token from local file
func loadToken() string {
// Set accessToken variable
accessToken := ""
// Set OAuth2 config
conf, ClientID, ClientSecret := getOauthConfig()
// Check if token.json file exists
if _, err := os.Stat("token.json"); err == nil {
localToken := readLocalToken()
if !localToken.Valid() {
fmt.Println("Local token expired at " + localToken.Expiry.String() + " , refreshing...")
form := url.Values{}
form.Add("grant_type", "refresh_token")
form.Add("refresh_token", localToken.RefreshToken)
form.Add("client_id", ClientID)
form.Add("client_secret", ClientSecret)
form.Add("scope", "offline")
body := strings.NewReader(form.Encode())
req, err := http.NewRequest("POST", "https://api.prod.whoop.com/oauth/oauth2/token", body)
check(err)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
check(err)
// Decode JSON
var tokenResponse models.TokenLocalFile
err = json.NewDecoder(resp.Body).Decode(&tokenResponse)
check(err)
// Marshal JSON
newToken := &oauth2.Token{
AccessToken: tokenResponse.AccessToken,
TokenType: tokenResponse.TokenType,
RefreshToken: tokenResponse.RefreshToken,
Expiry: time.Now().Local().Add(time.Second * time.Duration(tokenResponse.ExpiresIn)),
}
// Write token to file
writeLocalToken(newToken)
accessToken = tokenResponse.AccessToken
} else {
// Token is valid, use it without refresh
fmt.Println("Local token valid till " + localToken.Expiry.String() + ", reused without refresh")
accessToken = localToken.AccessToken
}
} else {
// If token.json not present, start browser authentication flow
fmt.Println("No token.json found, starting OAuth2 flow")
// Redirect user to consent page to ask for permission
authUrl := conf.AuthCodeURL("stateidentifier", oauth2.AccessTypeOffline)
fmt.Println("Visit the URL for the auth dialog: \n\n" + authUrl + "\n")
fmt.Println("Enter the response URL: ")
// Wait for user to paste in the response URL
var respUrl string
if _, err := fmt.Scan(&respUrl); err != nil {
fmt.Println(respUrl)
log.Fatal(err)
}
// Get response code from response URL string
parseUrl, _ := url.Parse(respUrl)
code := parseUrl.Query().Get("code")
// Exchange response code for token
accessToken, err := conf.Exchange(context.Background(), code)
check(err)
// Write token to file
writeLocalToken(accessToken)
}
// Return access token and newline
fmt.Println("")
return accessToken
}
// Make request to Whoop API
func makeRequest(path string, filename string, accessToken string) {
fmt.Println("Making requests to " + path)
// Create log file
f2, err := os.Create(filename)
check(err)
defer f2.Close()
// Set empty next token
nextToken := "empty"
count := 0
// Loop through all next tokens
for nextToken != "" {
whoop_url := "https://api.prod.whoop.com/developer/" + path
// If next token is not empty, add it to the get URL
if nextToken != "" && nextToken != "empty" {
whoop_url = whoop_url + "?nextToken=" + nextToken
}
// Request sleep data from Whoop API using client
req, err := http.NewRequest("GET", whoop_url, nil)
check(err)
// Add authorization and content header
req.Header.Add("Authorization", "Bearer "+accessToken)
req.Header.Add("Content-Type", "application/json")
// Make request
client := &http.Client{}
resp, err := client.Do(req)
check(err)
// Decode JSON to get nextToken
var decodeStruct models.All
err = json.NewDecoder(resp.Body).Decode(&decodeStruct)
check(err)
// Iterate through all structs
for _, record := range decodeStruct.Records {
// Write JSON to file
json, err := json.Marshal(record)
check(err)
f2.WriteString(string(json) + ",\n")
// Increment count
count++
}
// Print status message per 100 records
xrate_str := resp.Header.Get("X-RateLimit-Remaining")
xrate_int, err := strconv.Atoi(xrate_str)
check(err)
if count%100 == 0 {
fmt.Println("Processed " + strconv.Itoa(count) + " " + path + ", X-RateLimit remaining: " + xrate_str)
}
if xrate_int < 25 {
fmt.Println("X-RateLimit low: " + xrate_str + ", waiting 5 seconds...")
time.Sleep(5 * time.Second)
}
// Get nextToken
nextToken = decodeStruct.NextToken
}
fmt.Println("Completed " + strconv.Itoa(count) + " " + path + " records\n")
}
// Main function
func main() {
// Create client
accessToken := loadToken()
// Make requests to Whoop Sleep API
makeRequest("v1/activity/sleep", "sleep.log", accessToken)
makeRequest("v1/recovery", "recovery.log", accessToken)
makeRequest("v1/cycle", "cycle.log", accessToken)
makeRequest("v1/activity/workout", "workout.log", accessToken)
}