Package fitbit: Log signatures on failure.
[kraftakt.git] / fitbit / fitbit.go
index 81d4ebc..9466b12 100644 (file)
@@ -1,3 +1,4 @@
+// Package fitbit implements functions to interact with the Fitbit API.
 package fitbit
 
 import (
@@ -5,39 +6,50 @@ import (
        "crypto/hmac"
        "crypto/sha1"
        "encoding/base64"
+       "encoding/hex"
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
-       "net/url"
+       "strings"
        "time"
 
-       "github.com/octo/gfitsync/app"
+       "github.com/octo/kraftakt/app"
        "golang.org/x/oauth2"
        oauth2fitbit "golang.org/x/oauth2/fitbit"
+       "google.golang.org/appengine"
        "google.golang.org/appengine/log"
 )
 
-var oauth2Config = &oauth2.Config{
-       ClientID:     "@FITBIT_CLIENT_ID@",
-       ClientSecret: "@FITBIT_CLIENT_SECRET@",
-       Endpoint:     oauth2fitbit.Endpoint,
-       RedirectURL:  "https://fitbit-gfit-sync.appspot.com/fitbit/grant",
-       Scopes:       []string{"activity"},
+func oauthConfig() *oauth2.Config {
+       return &oauth2.Config{
+               ClientID:     app.Config.FitbitClientID,
+               ClientSecret: app.Config.FitbitClientSecret,
+               Endpoint:     oauth2fitbit.Endpoint,
+               RedirectURL:  "https://kraftakt.octo.it/fitbit/grant",
+               Scopes: []string{
+                       "activity",
+                       "heartrate",
+                       "profile",
+                       "sleep",
+               },
+       }
 }
 
-const csrfToken = "@CSRFTOKEN@"
-
-func AuthURL() string {
-       return oauth2Config.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
+// AuthURL returns the URL of the Fitbit consent screen. Users are redirected
+// there to approve Fitbit minting an OAuth2 token for us.
+func AuthURL(ctx context.Context, u *app.User) string {
+       return oauthConfig().AuthCodeURL(u.Sign("Fitbit"), oauth2.AccessTypeOffline)
 }
 
+// ParseToken parses the request of the user being redirected back from the
+// consent screen. The parsed token is stored in u using SetToken().
 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
-       if state := r.FormValue("state"); state != csrfToken {
+       if state := r.FormValue("state"); state != u.Sign("Fitbit") {
                return fmt.Errorf("invalid state parameter: %q", state)
        }
 
-       tok, err := oauth2Config.Exchange(ctx, r.FormValue("code"))
+       tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
        if err != nil {
                return err
        }
@@ -45,38 +57,45 @@ func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
        return u.SetToken(ctx, "Fitbit", tok)
 }
 
+// CheckSignature validates that rawSig is a valid signature of payload. This
+// is used by the Fitbit API to ansure that the receiver can verify that the
+// sender has access to the OAuth2 client secret.
 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
-       base64Sig, err := url.QueryUnescape(rawSig)
-       if err != nil {
-               log.Errorf(ctx, "QueryUnescape(%q) = %v", rawSig, err)
-               return false
-       }
-       signatureGot, err := base64.StdEncoding.DecodeString(base64Sig)
+       signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
        if err != nil {
-               log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", base64Sig, err)
+               log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
                return false
        }
 
-       mac := hmac.New(sha1.New, []byte(oauth2Config.ClientSecret+"&"))
+       mac := hmac.New(sha1.New, []byte(oauthConfig().ClientSecret+"&"))
        mac.Write(payload)
        signatureWant := mac.Sum(nil)
 
+       if !hmac.Equal(signatureGot, signatureWant) {
+               log.Debugf(ctx, "CheckSignature(): got %q, want %q",
+                       hex.EncodeToString(signatureGot),
+                       hex.EncodeToString(signatureWant))
+       }
+
        return hmac.Equal(signatureGot, signatureWant)
 }
 
 type Activity struct {
-       ActivityID       int     `json:"activityId"`
-       ActivityParentID int     `json:"activityParentId"`
-       Calories         int     `json:"calories"`
-       Description      string  `json:"description"`
-       Distance         float64 `json:"distance"`
-       Duration         int     `json:"duration"`
-       HasStartTime     bool    `json:"hasStartTime"`
-       IsFavorite       bool    `json:"isFavorite"`
-       LogID            int     `json:"logId"`
-       Name             string  `json:"name"`
-       StartTime        string  `json:"startTime"`
-       Steps            int     `json:"steps"`
+       ActivityID         int       `json:"activityId"`
+       ActivityParentID   int       `json:"activityParentId"`
+       ActivityParentName string    `json:"activityParentName"`
+       Calories           int       `json:"calories"`
+       Description        string    `json:"description"`
+       Distance           float64   `json:"distance"`
+       Duration           int       `json:"duration"`
+       HasStartTime       bool      `json:"hasStartTime"`
+       IsFavorite         bool      `json:"isFavorite"`
+       LastModified       time.Time `json:"lastModified"`
+       LogID              int       `json:"logId"`
+       Name               string    `json:"name"`
+       StartTime          string    `json:"startTime"`
+       StartDate          string    `json:"startDate"`
+       Steps              int       `json:"steps"`
 }
 
 type Distance struct {
@@ -84,6 +103,14 @@ type Distance struct {
        Distance float64 `json:"distance"`
 }
 
+type HeartRateZone struct {
+       Name        string  `json:"name"`
+       Min         int     `json:"min"`
+       Max         int     `json:"max"`
+       Minutes     int     `json:"minutes"`
+       CaloriesOut float64 `json:"caloriesOut"`
+}
+
 type ActivitySummary struct {
        Activities []Activity `json:"activities"`
        Goals      struct {
@@ -93,18 +120,22 @@ type ActivitySummary struct {
                Steps       int     `json:"steps"`
        } `json:"goals"`
        Summary struct {
-               ActivityCalories     int        `json:"activityCalories"`
-               CaloriesBMR          int        `json:"caloriesBMR"`
-               CaloriesOut          int        `json:"caloriesOut"`
-               MarginalCalories     int        `json:"marginalCalories"`
-               Distances            []Distance `json:"distances"`
-               Elevation            float64    `json:"elevation"`
-               Floors               int        `json:"floors"`
-               Steps                int        `json:"steps"`
-               SedentaryMinutes     int        `json:"sedentaryMinutes"`
-               LightlyActiveMinutes int        `json:"lightlyActiveMinutes"`
-               FairlyActiveMinutes  int        `json:"fairlyActiveMinutes"`
-               VeryActiveMinutes    int        `json:"veryActiveMinutes"`
+               ActiveScore          int             `json:"activeScore"`
+               ActivityCalories     int             `json:"activityCalories"`
+               CaloriesBMR          int             `json:"caloriesBMR"`
+               CaloriesOut          float64         `json:"caloriesOut"`
+               Distances            []Distance      `json:"distances"`
+               Elevation            float64         `json:"elevation"`
+               Floors               int             `json:"floors"`
+               HeartRateZones       []HeartRateZone `json:"heartRateZones"`
+               CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
+               MarginalCalories     int             `json:"marginalCalories"`
+               RestingHeartRate     int             `json:"restingHeartRate"`
+               Steps                int             `json:"steps"`
+               SedentaryMinutes     int             `json:"sedentaryMinutes"`
+               LightlyActiveMinutes int             `json:"lightlyActiveMinutes"`
+               FairlyActiveMinutes  int             `json:"fairlyActiveMinutes"`
+               VeryActiveMinutes    int             `json:"veryActiveMinutes"`
        } `json:"summary"`
 }
 
@@ -116,6 +147,11 @@ type Subscription struct {
        SubscriptionID string `json:"subscriptionId"`
 }
 
+func (s Subscription) String() string {
+       return fmt.Sprintf("https://api.fitbit.com/1/%s/%s/%s/apiSubscriptions/%s.json",
+               s.OwnerType, s.OwnerID, s.CollectionType, s.SubscriptionID)
+}
+
 type Client struct {
        fitbitUserID string
        appUser      *app.User
@@ -127,9 +163,9 @@ func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client,
                fitbitUserID = "-"
        }
 
-       c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
+       c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
        if err != nil {
-               return nil, err
+               return nil, fmt.Errorf("OAuthClient(%q) = %v", "Fitbit", err)
        }
 
        return &Client{
@@ -139,9 +175,12 @@ func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client,
        }, nil
 }
 
-func (c *Client) ActivitySummary(t time.Time) (*ActivitySummary, error) {
+// ActivitySummary returns the daily activity summary.
+//
+// See https://dev.fitbit.com/build/reference/web-api/activity/#get-daily-activity-summary for details.
+func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
        url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
-               c.fitbitUserID, t.Format("2006-01-02"))
+               c.fitbitUserID, date)
 
        res, err := c.client.Get(url)
        if err != nil {
@@ -149,33 +188,217 @@ func (c *Client) ActivitySummary(t time.Time) (*ActivitySummary, error) {
        }
        defer res.Body.Close()
 
+       data, err := ioutil.ReadAll(res.Body)
+       if err != nil {
+               return nil, err
+       }
+       log.Debugf(ctx, "GET %s -> %s", url, data)
+
        var summary ActivitySummary
-       if err := json.NewDecoder(res.Body).Decode(&summary); err != nil {
+       if err := json.Unmarshal(data, &summary); err != nil {
                return nil, err
        }
 
        return &summary, nil
 }
 
+func (c *Client) subscriberID(collection string) string {
+       return fmt.Sprintf("%s:%s", c.appUser.ID, collection)
+}
+
+// UserFromSubscriberID parses the user ID from the subscriber ID and calls
+// app.UserByID() with the user ID.
+func UserFromSubscriberID(ctx context.Context, subscriberID string) (*app.User, error) {
+       uid := strings.Split(subscriberID, ":")[0]
+       return app.UserByID(ctx, uid)
+}
+
+// Subscribe subscribes to one collection of the user. It uses a per-collection
+// subscription ID so that we can subscribe to more than one collection.
+//
+// See https://dev.fitbit.com/build/reference/web-api/subscriptions/#adding-a-subscription for details.
 func (c *Client) Subscribe(ctx context.Context, collection string) error {
-       subscriberID, err := c.appUser.ID(ctx)
+       url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
+               c.fitbitUserID, collection, c.subscriberID(collection))
+       res, err := c.client.Post(url, "", nil)
        if err != nil {
                return err
        }
+       defer res.Body.Close()
+
+       if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
+               data, _ := ioutil.ReadAll(res.Body)
+               log.Errorf(ctx, "creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
+               return fmt.Errorf("creating %q subscription failed", collection)
+       }
+       if res.StatusCode == http.StatusConflict {
+               log.Infof(ctx, "creating %q subscription: already exists", collection)
+       }
+
+       return nil
+}
+
+func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscriptionID string) error {
+       if userID == "" {
+               userID = c.fitbitUserID
+       }
 
        url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
-               c.fitbitUserID, collection, subscriberID)
-       res, err := c.client.Post(url, "", nil)
+               userID, collection, subscriptionID)
+       req, err := http.NewRequest(http.MethodDelete, url, nil)
+       if err != nil {
+               return err
+       }
+
+       res, err := c.client.Do(req.WithContext(ctx))
        if err != nil {
                return err
        }
        defer res.Body.Close()
 
-       if res.StatusCode >= 400 {
+       if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
                data, _ := ioutil.ReadAll(res.Body)
-               log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
-               return fmt.Errorf("creating subscription failed")
+               log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
+               return fmt.Errorf("deleting %q subscription failed", collection)
+       }
+       if res.StatusCode == http.StatusNotFound {
+               log.Infof(ctx, "deleting %q subscription: not found", collection)
+       }
+
+       return nil
+}
+
+// UnsubscribeAll gets a list of all subscriptions we have with the user's
+// account and deletes all found subscriptions.
+//
+// See https://dev.fitbit.com/build/reference/web-api/subscriptions/#deleting-a-subscription for details.
+func (c *Client) UnsubscribeAll(ctx context.Context) error {
+       var errs appengine.MultiError
+
+       for _, collection := range []string{"activities", "sleep"} {
+               subs, err := c.ListSubscriptions(ctx, collection)
+               if err != nil {
+                       errs = append(errs, err)
+                       continue
+               }
+
+               for _, sub := range subs {
+                       if err := c.unsubscribe(ctx, sub.OwnerID, sub.CollectionType, sub.SubscriptionID); err != nil {
+                               errs = append(errs, err)
+                       }
+               }
+       }
+       if len(errs) != 0 {
+               return errs
        }
 
        return nil
 }
+
+// ListSubscriptions returns a list of all subscriptions for a given collection
+// the OAuth2 client has to a user's account.
+func (c *Client) ListSubscriptions(ctx context.Context, collection string) ([]Subscription, error) {
+       url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions.json", c.fitbitUserID, collection)
+       res, err := c.client.Get(url)
+       if err != nil {
+               return nil, fmt.Errorf("Get(%q) = %v", url, err)
+       }
+       defer res.Body.Close()
+
+       if res.StatusCode == http.StatusNotFound {
+               log.Infof(ctx, "get %q subscription: not found", collection)
+               return nil, nil
+       }
+
+       data, err := ioutil.ReadAll(res.Body)
+       if err != nil {
+               return nil, err
+       }
+       log.Debugf(ctx, "GET %s -> %s", url, data)
+
+       if res.StatusCode >= 400 {
+               return nil, fmt.Errorf("Get(%q) = %d", url, res.StatusCode)
+       }
+
+       var parsed struct {
+               Subscriptions []Subscription `json:"apiSubscriptions"`
+       }
+       if err := json.Unmarshal(data, &parsed); err != nil {
+               return nil, err
+       }
+
+       var errs appengine.MultiError
+       var ret []Subscription
+       for _, sub := range parsed.Subscriptions {
+               if sub.CollectionType != collection {
+                       errs = append(errs, fmt.Errorf("unexpected collection type: got %q, want %q", sub.CollectionType, collection))
+                       continue
+               }
+               if sub.SubscriptionID == "" {
+                       errs = append(errs, fmt.Errorf("missing subscription ID: %+v", sub))
+                       continue
+               }
+               if sub.OwnerID == "" {
+                       sub.OwnerID = c.fitbitUserID
+               }
+               ret = append(ret, sub)
+       }
+
+       if len(ret) == 0 && len(errs) != 0 {
+               return nil, errs
+       }
+
+       for _, err := range errs {
+               log.Warningf(ctx, "%v", err)
+       }
+
+       return ret, nil
+}
+
+// DeleteToken deletes the Fitbit OAuth2 token.
+func (c *Client) DeleteToken(ctx context.Context) error {
+       return c.appUser.DeleteToken(ctx, "Fitbit")
+}
+
+// Provile contains data about the user.
+// It only contains the subset of fields required by Kraftakt.
+type Profile struct {
+       Name     string
+       Timezone *time.Location
+}
+
+// Profile returns the profile information of the user.
+func (c *Client) Profile(ctx context.Context) (*Profile, error) {
+       res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
+       if err != nil {
+               return nil, err
+       }
+       defer res.Body.Close()
+
+       if res.StatusCode >= 400 {
+               data, _ := ioutil.ReadAll(res.Body)
+               log.Errorf(ctx, "reading profile failed: %s", data)
+               return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
+       }
+
+       var data struct {
+               User struct {
+                       FullName            string
+                       OffsetFromUTCMillis int
+                       Timezone            string
+               }
+       }
+       if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
+               return nil, err
+       }
+
+       loc, err := time.LoadLocation(data.User.Timezone)
+       if err != nil {
+               loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
+       }
+
+       return &Profile{
+               Name:     data.User.FullName,
+               Timezone: loc,
+       }, nil
+}