~hokiegeek/fitstrava

ref: f5bac16231013630f1c8e6996ecfbe398a034d23 fitstrava/fitbit.go -rw-r--r-- 8.0 KiB
f5bac162HokieGeek Done and done 6 months ago
                                                                                
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
package fitstrava

import (
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

func genCodeVerifier() string {
	rand.Seed(time.Now().UnixNano())
	nums := []rune("0123456789")

	// length is between 43 - 128 based on: https://dev.fitbit.com/build/reference/web-api/developer-guide/authorization/
	s := make([]rune, rand.Intn(85)+43)
	for i := range s {
		s[i] = nums[rand.Intn(len(nums))]
	}
	return string(s)
}

func hashCodeVerifier(verifier string) string {
	sum := sha256.Sum256([]byte(verifier))
	return base64.RawURLEncoding.EncodeToString(sum[:])
}

func genCodeChallenge() (string, string) {
	verifier := genCodeVerifier()
	sum := sha256.Sum256([]byte(verifier))
	return base64.RawURLEncoding.EncodeToString(sum[:]), verifier
}

func fitbitCodeFromWeb(clientID, codeChallenge string) string {
	return codeFromWeb(8585,
		fmt.Sprintf("https://www.fitbit.com/oauth2/authorize?client_id=%s&response_type=code&code_challenge=%s&code_challenge_method=S256&scope=%s", clientID, codeChallenge, "activity%20heartrate%20location"))
}

type fitbitAuthToken struct {
	AccessToken  string `json:"access_token"`
	ExpiresIn    int64  `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	Scope        string `json:"scope"`
	TokenType    string `json:"token_type"`
	UserID       string `json:"user_id"`
}

func getFitbitAuthToken(clientID, clientSecret, codeVerifier, authCode string) (fitbitAuthToken, error) {
	data := url.Values{}
	data.Set("client_id", clientID)
	data.Set("code", authCode)
	data.Set("code_verifier", codeVerifier)
	data.Set("grant_type", "authorization_code")

	client := &http.Client{}
	r, err := http.NewRequest(http.MethodPost, "https://api.fitbit.com/oauth2/token", strings.NewReader(data.Encode()))
	if err != nil {
		return fitbitAuthToken{}, err
	}
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
	r.SetBasicAuth(clientID, clientSecret)

	resp, err := client.Do(r)
	if err != nil {
		return fitbitAuthToken{}, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fitbitAuthToken{}, fmt.Errorf("fitbit returned non-ok status: %s", resp.Status)
	}

	var token fitbitAuthToken
	if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
		return fitbitAuthToken{}, err
	}

	return token, nil
}

type FitbitClient struct {
	clientID, clientSecret string
	Token                  fitbitAuthToken
}

func NewFitbitClient(clientID, clientSecret string) (FitbitClient, error) {
	codeChallenge, codeVerifier := genCodeChallenge()
	// fmt.Println("code callenge:", codeChallenge)

	code := fitbitCodeFromWeb(clientID, codeChallenge)
	// fmt.Println("code:", code)

	token, err := getFitbitAuthToken(clientID, clientSecret, codeVerifier, code)
	if err != nil {
		panic(err)
	}

	return FitbitClient{
		clientID:     clientID,
		clientSecret: clientSecret,
		Token:        token,
	}, nil
}

type fitbitErrorResponse struct {
	Errors []fitbitError `json:"errors"`
}

type fitbitError struct {
	ErrorType string `json:"errorType"`
	FieldName string `json:"fieldName"`
	Message   string `json:"message"`
}

func fitbitHttp(fitbit FitbitClient, method, url string, body io.Reader) (*http.Response, error) {
	client := &http.Client{}
	r, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	r.Header.Add("Accept", "application/json")
	r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", fitbit.Token.AccessToken))

	return client.Do(r)
}

func fitbitGet(fitbit FitbitClient, url string) (*http.Response, error) {
	return fitbitHttp(fitbit, http.MethodGet, url, nil)
}

type fitbitActivitiesResponse struct {
	Activities []FitbitActivity `json:"activities"`
	Pagination fitbitPagination `json:"pagination"`
}

type FitbitActivity struct {
	ActiveDuration        int64                       `json:"activeDuration"`
	ActivityLevel         []FitbitActivityLevel       `json:"activityLevel"`
	ActivityName          string                      `json:"activityName"`
	ActivityTypeID        int64                       `json:"activityTypeId"`
	Calories              int64                       `json:"calories"`
	CaloriesLink          string                      `json:"caloriesLink"`
	Duration              int64                       `json:"duration"`
	ElevationGain         float64                     `json:"elevationGain"`
	LastModified          string                      `json:"lastModified"`
	LogID                 int64                       `json:"logId"`
	LogType               string                      `json:"logType"`
	ManualValuesSpecified FitbitManualValuesSpecified `json:"manualValuesSpecified"`
	OriginalDuration      int64                       `json:"originalDuration"`
	OriginalStartTime     string                      `json:"originalStartTime"`
	StartTime             string                      `json:"startTime"`
	Steps                 int64                       `json:"steps"`
	TcxLink               string                      `json:"tcxLink"`
}

type fitbitActivityType struct {
	Activity activityType `json:"activity"`
}

type activityType struct {
	AccessLevel    string                `json:"accessLevel"`
	ActivityLevels []fitbitActivityLevel `json:"activityLevels"`
	HasSpeed       bool                  `json:"hasSpeed"`
	ID             int64                 `json:"id"`
	Name           string                `json:"name"`
}

type fitbitActivityLevel struct {
	ID          int64   `json:"id"`
	MaxSpeedMPH float64 `json:"maxSpeedMPH"`
	Mets        float64 `json:"mets"`
	MinSpeedMPH int64   `json:"minSpeedMPH"`
	Name        string  `json:"name"`
}

var fitbitActivityTypes = make(map[int64]fitbitActivityType, 0)

func (a FitbitActivity) ActivityTypeName(fitbit FitbitClient) string {
	t, ok := fitbitActivityTypes[a.ActivityTypeID]
	if !ok {
		resp, err := fitbitGet(fitbit, fmt.Sprintf("https://api.fitbit.com/1/activities/%d.json", a.ActivityTypeID))
		if err != nil {
			return err.Error()
		}
		defer resp.Body.Close()

		if err := json.NewDecoder(resp.Body).Decode(&t); err != nil {
			return err.Error()
		}

		fitbitActivityTypes[a.ActivityTypeID] = t
	}

	return t.Activity.Name
}

type FitbitActivityLevel struct {
	Minutes int64  `json:"minutes"`
	Name    string `json:"name"`
}

type FitbitManualValuesSpecified struct {
	Calories bool `json:"calories"`
	Distance bool `json:"distance"`
	Steps    bool `json:"steps"`
}

type fitbitPagination struct {
	AfterDate string `json:"afterDate"`
	Limit     int64  `json:"limit"`
	Next      string `json:"next"`
	Offset    int64  `json:"offset"`
	Previous  string `json:"previous"`
	Sort      string `json:"sort"`
}

func FitbitGetActivities(fitbit FitbitClient, after time.Time) ([]FitbitActivity, error) {
	activities := make([]FitbitActivity, 0)

	qp := url.Values{}
	qp.Set("afterDate", after.Format("2006-01-02"))
	qp.Set("sort", "asc")
	qp.Set("limit", "100")
	qp.Set("offset", "0")

	next := "https://api.fitbit.com/1/user/-/activities/list.json?" + qp.Encode()

	for {
		if next == "" {
			break
		}

		resp, err := fitbitGet(fitbit, next)
		if err != nil {
			return nil, err
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			var ferr fitbitErrorResponse
			if err := json.NewDecoder(resp.Body).Decode(&ferr); err != nil {
				return nil, fmt.Errorf("could not get Fitbit activities: %s", resp.Status)
			}
			return nil, fmt.Errorf("could not get Fitbit activities: %s: %s", resp.Status, ferr.Errors[0].Message)
		}

		// print a warning if getting low
		if rem, _ := strconv.Atoi(resp.Header["Fitbit-Rate-Limit-Remaining"][0]); rem < 20 {
			fmt.Printf("WARNING: Exceeding the Fitbit rate limit: %s/%s (%s)\n",
				resp.Header["Fitbit-Rate-Limit-Remaining"],
				resp.Header["Fitbit-Rate-Limit-Limit"],
				resp.Header["Fitbit-Rate-Limit-Reset"])
		}
		var fitbitResp fitbitActivitiesResponse
		if err := json.NewDecoder(resp.Body).Decode(&fitbitResp); err != nil {
			return nil, err
		}

		activities = append(activities, fitbitResp.Activities...)
		next = fitbitResp.Pagination.Next
	}

	return activities, nil
}