Implement storing of calories expended.
[kraftakt.git] / fitbit / fitbit.go
index bdfc3dd..a24f98e 100644 (file)
@@ -23,7 +23,7 @@ var oauth2Config = &oauth2.Config{
        ClientSecret: "@FITBIT_CLIENT_SECRET@",
        Endpoint:     oauth2fitbit.Endpoint,
        RedirectURL:  "https://fitbit-gfit-sync.appspot.com/fitbit/grant",
-       Scopes:       []string{"activity"},
+       Scopes:       []string{"activity", "heartrate", "profile"},
 }
 
 const csrfToken = "@CSRFTOKEN@"
@@ -84,6 +84,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 +101,21 @@ 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"`
+               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"`
 }
 
@@ -127,36 +138,15 @@ func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client,
                fitbitUserID = "-"
        }
 
-       storedToken, err := u.Token(ctx, "Fitbit")
+       c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
        if err != nil {
                return nil, err
        }
 
-       // The oauth2 package will refresh the token when it is valid for less
-       // than 10 seconds. To avoid a race with later calls (which would
-       // refresh the token but the new RefreshToken wouldn't make it back
-       // into datastore), we refresh earlier than that. The Fitbit tokens are
-       // quite long-lived (six hours?); the additional load this puts on the
-       // backends is negligible.
-       if storedToken.Expiry.Round(0).Add(-5 * time.Minute).Before(time.Now()) {
-               storedToken.Expiry = time.Now()
-       }
-
-       refreshedToken, err := oauth2Config.TokenSource(ctx, storedToken).Token()
-       if err != nil {
-               return nil, err
-       }
-
-       if refreshedToken.RefreshToken != storedToken.RefreshToken {
-               if err := u.SetToken(ctx, "Fitbit", refreshedToken); err != nil {
-                       return nil, err
-               }
-       }
-
        return &Client{
                fitbitUserID: fitbitUserID,
                appUser:      u,
-               client:       oauth2Config.Client(ctx, refreshedToken),
+               client:       c,
        }, nil
 }
 
@@ -200,3 +190,43 @@ func (c *Client) Subscribe(ctx context.Context, collection string) error {
 
        return nil
 }
+
+type Profile struct {
+       Name     string
+       Timezone *time.Location
+}
+
+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
+}