app.yaml: Set api_version "go1".
[kraftakt.git] / fitbit / fitbit.go
index 7e38bf1..0d03244 100644 (file)
@@ -1,3 +1,4 @@
+// Package fitbit implements functions to interact with the Fitbit API.
 package fitbit
 
 import (
@@ -5,18 +6,22 @@ import (
        "crypto/hmac"
        "crypto/sha1"
        "encoding/base64"
+       "encoding/hex"
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
+       "net/url"
        "strings"
        "time"
 
        "github.com/octo/kraftakt/app"
+       "github.com/octo/retry"
        "golang.org/x/oauth2"
        oauth2fitbit "golang.org/x/oauth2/fitbit"
        "google.golang.org/appengine"
        "google.golang.org/appengine/log"
+       "google.golang.org/appengine/urlfetch"
 )
 
 func oauthConfig() *oauth2.Config {
@@ -34,10 +39,14 @@ func oauthConfig() *oauth2.Config {
        }
 }
 
+// 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 != u.Sign("Fitbit") {
                return fmt.Errorf("invalid state parameter: %q", state)
@@ -51,6 +60,9 @@ 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 {
        signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
        if err != nil {
@@ -62,6 +74,12 @@ func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
        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)
 }
 
@@ -160,6 +178,9 @@ func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client,
        }, nil
 }
 
+// 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, date)
@@ -188,11 +209,17 @@ 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 {
        url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
                c.fitbitUserID, collection, c.subscriberID(collection))
@@ -204,8 +231,7 @@ func (c *Client) Subscribe(ctx context.Context, collection string) error {
 
        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)
+               return fmt.Errorf("creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
        }
        if res.StatusCode == http.StatusConflict {
                log.Infof(ctx, "creating %q subscription: already exists", collection)
@@ -234,8 +260,7 @@ func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscripti
 
        if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
                data, _ := ioutil.ReadAll(res.Body)
-               log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
-               return fmt.Errorf("deleting %q subscription failed", collection)
+               return fmt.Errorf("deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
        }
        if res.StatusCode == http.StatusNotFound {
                log.Infof(ctx, "deleting %q subscription: not found", collection)
@@ -244,6 +269,10 @@ func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscripti
        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
 
@@ -267,6 +296,8 @@ func (c *Client) UnsubscribeAll(ctx context.Context) error {
        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)
@@ -325,15 +356,58 @@ func (c *Client) ListSubscriptions(ctx context.Context, collection string) ([]Su
        return ret, nil
 }
 
+func (c *Client) revokeToken(ctx context.Context) error {
+       tok, err := c.appUser.Token(ctx, "Fitbit")
+       if err != nil {
+               return err
+       }
+
+       httpClient := urlfetch.Client(ctx)
+       httpClient.Transport = retry.NewTransport(httpClient.Transport)
+
+       url := "https://api.fitbit.com/oauth2/revoke?token=" + url.QueryEscape(tok.AccessToken)
+       req, err := http.NewRequest(http.MethodGet, url, nil)
+       if err != nil {
+               return err
+       }
+       req.Header.Set("Authorization", "Basic "+
+               base64.StdEncoding.EncodeToString([]byte(
+                       app.Config.FitbitClientID+":"+app.Config.FitbitClientSecret)))
+
+       res, err := httpClient.Do(req)
+       if err != nil {
+               return fmt.Errorf("GET %s: %v", url, err)
+       }
+       defer res.Body.Close()
+
+       if res.StatusCode != http.StatusOK {
+               if data, err := ioutil.ReadAll(res.Body); err == nil {
+                       return fmt.Errorf("GET %s: %s", url, data)
+               } else {
+                       return fmt.Errorf("GET %s: %s", url, res.Status)
+               }
+       }
+
+       return nil
+}
+
+// DeleteToken deletes the Fitbit OAuth2 token.
 func (c *Client) DeleteToken(ctx context.Context) error {
+       if err := c.revokeToken(ctx); err != nil {
+               log.Warningf(ctx, "revokeToken() = %v", err)
+       }
+
        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 {
@@ -343,8 +417,7 @@ func (c *Client) Profile(ctx context.Context) (*Profile, error) {
 
        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)
+               return nil, fmt.Errorf("reading profile failed: %s", data)
        }
 
        var data struct {