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