9466b12f9de0edf8d326705a5a51b8587f3db5d9
[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                 log.Errorf(ctx, "creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
232                 return fmt.Errorf("creating %q subscription failed", collection)
233         }
234         if res.StatusCode == http.StatusConflict {
235                 log.Infof(ctx, "creating %q subscription: already exists", collection)
236         }
237
238         return nil
239 }
240
241 func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscriptionID string) error {
242         if userID == "" {
243                 userID = c.fitbitUserID
244         }
245
246         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
247                 userID, collection, subscriptionID)
248         req, err := http.NewRequest(http.MethodDelete, url, nil)
249         if err != nil {
250                 return err
251         }
252
253         res, err := c.client.Do(req.WithContext(ctx))
254         if err != nil {
255                 return err
256         }
257         defer res.Body.Close()
258
259         if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
260                 data, _ := ioutil.ReadAll(res.Body)
261                 log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
262                 return fmt.Errorf("deleting %q subscription failed", collection)
263         }
264         if res.StatusCode == http.StatusNotFound {
265                 log.Infof(ctx, "deleting %q subscription: not found", collection)
266         }
267
268         return nil
269 }
270
271 // UnsubscribeAll gets a list of all subscriptions we have with the user's
272 // account and deletes all found subscriptions.
273 //
274 // See https://dev.fitbit.com/build/reference/web-api/subscriptions/#deleting-a-subscription for details.
275 func (c *Client) UnsubscribeAll(ctx context.Context) error {
276         var errs appengine.MultiError
277
278         for _, collection := range []string{"activities", "sleep"} {
279                 subs, err := c.ListSubscriptions(ctx, collection)
280                 if err != nil {
281                         errs = append(errs, err)
282                         continue
283                 }
284
285                 for _, sub := range subs {
286                         if err := c.unsubscribe(ctx, sub.OwnerID, sub.CollectionType, sub.SubscriptionID); err != nil {
287                                 errs = append(errs, err)
288                         }
289                 }
290         }
291         if len(errs) != 0 {
292                 return errs
293         }
294
295         return nil
296 }
297
298 // ListSubscriptions returns a list of all subscriptions for a given collection
299 // the OAuth2 client has to a user's account.
300 func (c *Client) ListSubscriptions(ctx context.Context, collection string) ([]Subscription, error) {
301         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions.json", c.fitbitUserID, collection)
302         res, err := c.client.Get(url)
303         if err != nil {
304                 return nil, fmt.Errorf("Get(%q) = %v", url, err)
305         }
306         defer res.Body.Close()
307
308         if res.StatusCode == http.StatusNotFound {
309                 log.Infof(ctx, "get %q subscription: not found", collection)
310                 return nil, nil
311         }
312
313         data, err := ioutil.ReadAll(res.Body)
314         if err != nil {
315                 return nil, err
316         }
317         log.Debugf(ctx, "GET %s -> %s", url, data)
318
319         if res.StatusCode >= 400 {
320                 return nil, fmt.Errorf("Get(%q) = %d", url, res.StatusCode)
321         }
322
323         var parsed struct {
324                 Subscriptions []Subscription `json:"apiSubscriptions"`
325         }
326         if err := json.Unmarshal(data, &parsed); err != nil {
327                 return nil, err
328         }
329
330         var errs appengine.MultiError
331         var ret []Subscription
332         for _, sub := range parsed.Subscriptions {
333                 if sub.CollectionType != collection {
334                         errs = append(errs, fmt.Errorf("unexpected collection type: got %q, want %q", sub.CollectionType, collection))
335                         continue
336                 }
337                 if sub.SubscriptionID == "" {
338                         errs = append(errs, fmt.Errorf("missing subscription ID: %+v", sub))
339                         continue
340                 }
341                 if sub.OwnerID == "" {
342                         sub.OwnerID = c.fitbitUserID
343                 }
344                 ret = append(ret, sub)
345         }
346
347         if len(ret) == 0 && len(errs) != 0 {
348                 return nil, errs
349         }
350
351         for _, err := range errs {
352                 log.Warningf(ctx, "%v", err)
353         }
354
355         return ret, nil
356 }
357
358 // DeleteToken deletes the Fitbit OAuth2 token.
359 func (c *Client) DeleteToken(ctx context.Context) error {
360         return c.appUser.DeleteToken(ctx, "Fitbit")
361 }
362
363 // Provile contains data about the user.
364 // It only contains the subset of fields required by Kraftakt.
365 type Profile struct {
366         Name     string
367         Timezone *time.Location
368 }
369
370 // Profile returns the profile information of the user.
371 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
372         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
373         if err != nil {
374                 return nil, err
375         }
376         defer res.Body.Close()
377
378         if res.StatusCode >= 400 {
379                 data, _ := ioutil.ReadAll(res.Body)
380                 log.Errorf(ctx, "reading profile failed: %s", data)
381                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
382         }
383
384         var data struct {
385                 User struct {
386                         FullName            string
387                         OffsetFromUTCMillis int
388                         Timezone            string
389                 }
390         }
391         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
392                 return nil, err
393         }
394
395         loc, err := time.LoadLocation(data.User.Timezone)
396         if err != nil {
397                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
398         }
399
400         return &Profile{
401                 Name:     data.User.FullName,
402                 Timezone: loc,
403         }, nil
404 }