ef6282e0b4120db0ef26a5583bb068c253fc3dab
[kraftakt.git] / fitbit / fitbit.go
1 // Package fitbit implements functions to interact with the Fitbit API.
2 package fitbit
3
4 import (
5         "context"
6         "crypto/hmac"
7         "crypto/sha1"
8         "encoding/base64"
9         "encoding/hex"
10         "encoding/json"
11         "fmt"
12         "io/ioutil"
13         "net/http"
14         "strings"
15         "time"
16
17         "github.com/octo/kraftakt/app"
18         "golang.org/x/oauth2"
19         oauth2fitbit "golang.org/x/oauth2/fitbit"
20         "google.golang.org/appengine"
21         "google.golang.org/appengine/log"
22 )
23
24 func oauthConfig() *oauth2.Config {
25         return &oauth2.Config{
26                 ClientID:     app.Config.FitbitClientID,
27                 ClientSecret: app.Config.FitbitClientSecret,
28                 Endpoint:     oauth2fitbit.Endpoint,
29                 RedirectURL:  "https://kraftakt.octo.it/fitbit/grant",
30                 Scopes: []string{
31                         "activity",
32                         "heartrate",
33                         "profile",
34                         "sleep",
35                 },
36         }
37 }
38
39 // AuthURL returns the URL of the Fitbit consent screen. Users are redirected
40 // there to approve Fitbit minting an OAuth2 token for us.
41 func AuthURL(ctx context.Context, u *app.User) string {
42         return oauthConfig().AuthCodeURL(u.Sign("Fitbit"), oauth2.AccessTypeOffline)
43 }
44
45 // ParseToken parses the request of the user being redirected back from the
46 // consent screen. The parsed token is stored in u using SetToken().
47 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
48         if state := r.FormValue("state"); state != u.Sign("Fitbit") {
49                 return fmt.Errorf("invalid state parameter: %q", state)
50         }
51
52         tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
53         if err != nil {
54                 return err
55         }
56
57         return u.SetToken(ctx, "Fitbit", tok)
58 }
59
60 // CheckSignature validates that rawSig is a valid signature of payload. This
61 // is used by the Fitbit API to ansure that the receiver can verify that the
62 // sender has access to the OAuth2 client secret.
63 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
64         signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
65         if err != nil {
66                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
67                 return false
68         }
69
70         mac := hmac.New(sha1.New, []byte(oauthConfig().ClientSecret+"&"))
71         mac.Write(payload)
72         signatureWant := mac.Sum(nil)
73
74         if !hmac.Equal(signatureGot, signatureWant) {
75                 log.Debugf(ctx, "CheckSignature(): got %q, want %q",
76                         hex.EncodeToString(signatureGot),
77                         hex.EncodeToString(signatureWant))
78         }
79
80         return hmac.Equal(signatureGot, signatureWant)
81 }
82
83 type Activity struct {
84         ActivityID         int       `json:"activityId"`
85         ActivityParentID   int       `json:"activityParentId"`
86         ActivityParentName string    `json:"activityParentName"`
87         Calories           int       `json:"calories"`
88         Description        string    `json:"description"`
89         Distance           float64   `json:"distance"`
90         Duration           int       `json:"duration"`
91         HasStartTime       bool      `json:"hasStartTime"`
92         IsFavorite         bool      `json:"isFavorite"`
93         LastModified       time.Time `json:"lastModified"`
94         LogID              int       `json:"logId"`
95         Name               string    `json:"name"`
96         StartTime          string    `json:"startTime"`
97         StartDate          string    `json:"startDate"`
98         Steps              int       `json:"steps"`
99 }
100
101 type Distance struct {
102         Activity string  `json:"activity"`
103         Distance float64 `json:"distance"`
104 }
105
106 type HeartRateZone struct {
107         Name        string  `json:"name"`
108         Min         int     `json:"min"`
109         Max         int     `json:"max"`
110         Minutes     int     `json:"minutes"`
111         CaloriesOut float64 `json:"caloriesOut"`
112 }
113
114 type ActivitySummary struct {
115         Activities []Activity `json:"activities"`
116         Goals      struct {
117                 CaloriesOut int     `json:"caloriesOut"`
118                 Distance    float64 `json:"distance"`
119                 Floors      int     `json:"floors"`
120                 Steps       int     `json:"steps"`
121         } `json:"goals"`
122         Summary struct {
123                 ActiveScore          int             `json:"activeScore"`
124                 ActivityCalories     int             `json:"activityCalories"`
125                 CaloriesBMR          int             `json:"caloriesBMR"`
126                 CaloriesOut          float64         `json:"caloriesOut"`
127                 Distances            []Distance      `json:"distances"`
128                 Elevation            float64         `json:"elevation"`
129                 Floors               int             `json:"floors"`
130                 HeartRateZones       []HeartRateZone `json:"heartRateZones"`
131                 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
132                 MarginalCalories     int             `json:"marginalCalories"`
133                 RestingHeartRate     int             `json:"restingHeartRate"`
134                 Steps                int             `json:"steps"`
135                 SedentaryMinutes     int             `json:"sedentaryMinutes"`
136                 LightlyActiveMinutes int             `json:"lightlyActiveMinutes"`
137                 FairlyActiveMinutes  int             `json:"fairlyActiveMinutes"`
138                 VeryActiveMinutes    int             `json:"veryActiveMinutes"`
139         } `json:"summary"`
140 }
141
142 type Subscription struct {
143         CollectionType string `json:"collectionType"`
144         Date           string `json:"date"`
145         OwnerID        string `json:"ownerId"`
146         OwnerType      string `json:"ownerType"`
147         SubscriptionID string `json:"subscriptionId"`
148 }
149
150 func (s Subscription) String() string {
151         return fmt.Sprintf("https://api.fitbit.com/1/%s/%s/%s/apiSubscriptions/%s.json",
152                 s.OwnerType, s.OwnerID, s.CollectionType, s.SubscriptionID)
153 }
154
155 type Client struct {
156         fitbitUserID string
157         appUser      *app.User
158         client       *http.Client
159 }
160
161 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
162         if fitbitUserID == "" {
163                 fitbitUserID = "-"
164         }
165
166         c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
167         if err != nil {
168                 return nil, fmt.Errorf("OAuthClient(%q) = %v", "Fitbit", err)
169         }
170
171         return &Client{
172                 fitbitUserID: fitbitUserID,
173                 appUser:      u,
174                 client:       c,
175         }, nil
176 }
177
178 // ActivitySummary returns the daily activity summary.
179 //
180 // See https://dev.fitbit.com/build/reference/web-api/activity/#get-daily-activity-summary for details.
181 func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
182         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
183                 c.fitbitUserID, date)
184
185         res, err := c.client.Get(url)
186         if err != nil {
187                 return nil, err
188         }
189         defer res.Body.Close()
190
191         data, err := ioutil.ReadAll(res.Body)
192         if err != nil {
193                 return nil, err
194         }
195         log.Debugf(ctx, "GET %s -> %s", url, data)
196
197         var summary ActivitySummary
198         if err := json.Unmarshal(data, &summary); err != nil {
199                 return nil, err
200         }
201
202         return &summary, nil
203 }
204
205 func (c *Client) subscriberID(collection string) string {
206         return fmt.Sprintf("%s:%s", c.appUser.ID, collection)
207 }
208
209 // UserFromSubscriberID parses the user ID from the subscriber ID and calls
210 // app.UserByID() with the user ID.
211 func UserFromSubscriberID(ctx context.Context, subscriberID string) (*app.User, error) {
212         uid := strings.Split(subscriberID, ":")[0]
213         return app.UserByID(ctx, uid)
214 }
215
216 // Subscribe subscribes to one collection of the user. It uses a per-collection
217 // subscription ID so that we can subscribe to more than one collection.
218 //
219 // See https://dev.fitbit.com/build/reference/web-api/subscriptions/#adding-a-subscription for details.
220 func (c *Client) Subscribe(ctx context.Context, collection string) error {
221         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
222                 c.fitbitUserID, collection, c.subscriberID(collection))
223         res, err := c.client.Post(url, "", nil)
224         if err != nil {
225                 return err
226         }
227         defer res.Body.Close()
228
229         if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
230                 data, _ := ioutil.ReadAll(res.Body)
231                 return fmt.Errorf("creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
232         }
233         if res.StatusCode == http.StatusConflict {
234                 log.Infof(ctx, "creating %q subscription: already exists", collection)
235         }
236
237         return nil
238 }
239
240 func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscriptionID string) error {
241         if userID == "" {
242                 userID = c.fitbitUserID
243         }
244
245         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
246                 userID, collection, subscriptionID)
247         req, err := http.NewRequest(http.MethodDelete, url, nil)
248         if err != nil {
249                 return err
250         }
251
252         res, err := c.client.Do(req.WithContext(ctx))
253         if err != nil {
254                 return err
255         }
256         defer res.Body.Close()
257
258         if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
259                 data, _ := ioutil.ReadAll(res.Body)
260                 return fmt.Errorf("deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
261         }
262         if res.StatusCode == http.StatusNotFound {
263                 log.Infof(ctx, "deleting %q subscription: not found", collection)
264         }
265
266         return nil
267 }
268
269 // UnsubscribeAll gets a list of all subscriptions we have with the user's
270 // account and deletes all found subscriptions.
271 //
272 // See https://dev.fitbit.com/build/reference/web-api/subscriptions/#deleting-a-subscription for details.
273 func (c *Client) UnsubscribeAll(ctx context.Context) error {
274         var errs appengine.MultiError
275
276         for _, collection := range []string{"activities", "sleep"} {
277                 subs, err := c.ListSubscriptions(ctx, collection)
278                 if err != nil {
279                         errs = append(errs, err)
280                         continue
281                 }
282
283                 for _, sub := range subs {
284                         if err := c.unsubscribe(ctx, sub.OwnerID, sub.CollectionType, sub.SubscriptionID); err != nil {
285                                 errs = append(errs, err)
286                         }
287                 }
288         }
289         if len(errs) != 0 {
290                 return errs
291         }
292
293         return nil
294 }
295
296 // ListSubscriptions returns a list of all subscriptions for a given collection
297 // the OAuth2 client has to a user's account.
298 func (c *Client) ListSubscriptions(ctx context.Context, collection string) ([]Subscription, error) {
299         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions.json", c.fitbitUserID, collection)
300         res, err := c.client.Get(url)
301         if err != nil {
302                 return nil, fmt.Errorf("Get(%q) = %v", url, err)
303         }
304         defer res.Body.Close()
305
306         if res.StatusCode == http.StatusNotFound {
307                 log.Infof(ctx, "get %q subscription: not found", collection)
308                 return nil, nil
309         }
310
311         data, err := ioutil.ReadAll(res.Body)
312         if err != nil {
313                 return nil, err
314         }
315         log.Debugf(ctx, "GET %s -> %s", url, data)
316
317         if res.StatusCode >= 400 {
318                 return nil, fmt.Errorf("Get(%q) = %d", url, res.StatusCode)
319         }
320
321         var parsed struct {
322                 Subscriptions []Subscription `json:"apiSubscriptions"`
323         }
324         if err := json.Unmarshal(data, &parsed); err != nil {
325                 return nil, err
326         }
327
328         var errs appengine.MultiError
329         var ret []Subscription
330         for _, sub := range parsed.Subscriptions {
331                 if sub.CollectionType != collection {
332                         errs = append(errs, fmt.Errorf("unexpected collection type: got %q, want %q", sub.CollectionType, collection))
333                         continue
334                 }
335                 if sub.SubscriptionID == "" {
336                         errs = append(errs, fmt.Errorf("missing subscription ID: %+v", sub))
337                         continue
338                 }
339                 if sub.OwnerID == "" {
340                         sub.OwnerID = c.fitbitUserID
341                 }
342                 ret = append(ret, sub)
343         }
344
345         if len(ret) == 0 && len(errs) != 0 {
346                 return nil, errs
347         }
348
349         for _, err := range errs {
350                 log.Warningf(ctx, "%v", err)
351         }
352
353         return ret, nil
354 }
355
356 // DeleteToken deletes the Fitbit OAuth2 token.
357 func (c *Client) DeleteToken(ctx context.Context) error {
358         return c.appUser.DeleteToken(ctx, "Fitbit")
359 }
360
361 // Provile contains data about the user.
362 // It only contains the subset of fields required by Kraftakt.
363 type Profile struct {
364         Name     string
365         Timezone *time.Location
366 }
367
368 // Profile returns the profile information of the user.
369 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
370         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
371         if err != nil {
372                 return nil, err
373         }
374         defer res.Body.Close()
375
376         if res.StatusCode >= 400 {
377                 data, _ := ioutil.ReadAll(res.Body)
378                 return nil, fmt.Errorf("reading profile failed: %s", data)
379         }
380
381         var data struct {
382                 User struct {
383                         FullName            string
384                         OffsetFromUTCMillis int
385                         Timezone            string
386                 }
387         }
388         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
389                 return nil, err
390         }
391
392         loc, err := time.LoadLocation(data.User.Timezone)
393         if err != nil {
394                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
395         }
396
397         return &Profile{
398                 Name:     data.User.FullName,
399                 Timezone: loc,
400         }, nil
401 }