Package fitbit: Update RefreshToken in Datastore after refreshing OAuth token.
[kraftakt.git] / fitbit / fitbit.go
1 package fitbit
2
3 import (
4         "context"
5         "crypto/hmac"
6         "crypto/sha1"
7         "encoding/base64"
8         "encoding/json"
9         "fmt"
10         "io/ioutil"
11         "net/http"
12         "net/url"
13         "time"
14
15         "github.com/octo/gfitsync/app"
16         "golang.org/x/oauth2"
17         oauth2fitbit "golang.org/x/oauth2/fitbit"
18         "google.golang.org/appengine/log"
19 )
20
21 var oauth2Config = &oauth2.Config{
22         ClientID:     "@FITBIT_CLIENT_ID@",
23         ClientSecret: "@FITBIT_CLIENT_SECRET@",
24         Endpoint:     oauth2fitbit.Endpoint,
25         RedirectURL:  "https://fitbit-gfit-sync.appspot.com/fitbit/grant",
26         Scopes:       []string{"activity"},
27 }
28
29 const csrfToken = "@CSRFTOKEN@"
30
31 func AuthURL() string {
32         return oauth2Config.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
33 }
34
35 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
36         if state := r.FormValue("state"); state != csrfToken {
37                 return fmt.Errorf("invalid state parameter: %q", state)
38         }
39
40         tok, err := oauth2Config.Exchange(ctx, r.FormValue("code"))
41         if err != nil {
42                 return err
43         }
44
45         return u.SetToken(ctx, "Fitbit", tok)
46 }
47
48 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
49         base64Sig, err := url.QueryUnescape(rawSig)
50         if err != nil {
51                 log.Errorf(ctx, "QueryUnescape(%q) = %v", rawSig, err)
52                 return false
53         }
54         signatureGot, err := base64.StdEncoding.DecodeString(base64Sig)
55         if err != nil {
56                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", base64Sig, err)
57                 return false
58         }
59
60         mac := hmac.New(sha1.New, []byte(oauth2Config.ClientSecret+"&"))
61         mac.Write(payload)
62         signatureWant := mac.Sum(nil)
63
64         return hmac.Equal(signatureGot, signatureWant)
65 }
66
67 type Activity struct {
68         ActivityID       int     `json:"activityId"`
69         ActivityParentID int     `json:"activityParentId"`
70         Calories         int     `json:"calories"`
71         Description      string  `json:"description"`
72         Distance         float64 `json:"distance"`
73         Duration         int     `json:"duration"`
74         HasStartTime     bool    `json:"hasStartTime"`
75         IsFavorite       bool    `json:"isFavorite"`
76         LogID            int     `json:"logId"`
77         Name             string  `json:"name"`
78         StartTime        string  `json:"startTime"`
79         Steps            int     `json:"steps"`
80 }
81
82 type Distance struct {
83         Activity string  `json:"activity"`
84         Distance float64 `json:"distance"`
85 }
86
87 type ActivitySummary struct {
88         Activities []Activity `json:"activities"`
89         Goals      struct {
90                 CaloriesOut int     `json:"caloriesOut"`
91                 Distance    float64 `json:"distance"`
92                 Floors      int     `json:"floors"`
93                 Steps       int     `json:"steps"`
94         } `json:"goals"`
95         Summary struct {
96                 ActivityCalories     int        `json:"activityCalories"`
97                 CaloriesBMR          int        `json:"caloriesBMR"`
98                 CaloriesOut          int        `json:"caloriesOut"`
99                 MarginalCalories     int        `json:"marginalCalories"`
100                 Distances            []Distance `json:"distances"`
101                 Elevation            float64    `json:"elevation"`
102                 Floors               int        `json:"floors"`
103                 Steps                int        `json:"steps"`
104                 SedentaryMinutes     int        `json:"sedentaryMinutes"`
105                 LightlyActiveMinutes int        `json:"lightlyActiveMinutes"`
106                 FairlyActiveMinutes  int        `json:"fairlyActiveMinutes"`
107                 VeryActiveMinutes    int        `json:"veryActiveMinutes"`
108         } `json:"summary"`
109 }
110
111 type Subscription struct {
112         CollectionType string `json:"collectionType"`
113         Date           string `json:"date"`
114         OwnerID        string `json:"ownerId"`
115         OwnerType      string `json:"ownerType"`
116         SubscriptionID string `json:"subscriptionId"`
117 }
118
119 type Client struct {
120         fitbitUserID string
121         appUser      *app.User
122         client       *http.Client
123 }
124
125 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
126         if fitbitUserID == "" {
127                 fitbitUserID = "-"
128         }
129
130         storedToken, err := u.Token(ctx, "Fitbit")
131         if err != nil {
132                 return nil, err
133         }
134
135         // The oauth2 package will refresh the token when it is valid for less
136         // than 10 seconds. To avoid a race with later calls (which would
137         // refresh the token but the new RefreshToken wouldn't make it back
138         // into datastore), we refresh earlier than that. The Fitbit tokens are
139         // quite long-lived (six hours?); the additional load this puts on the
140         // backends is negligible.
141         if storedToken.Expiry.Round(0).Add(-5 * time.Minute).Before(time.Now()) {
142                 storedToken.Expiry = time.Now()
143         }
144
145         refreshedToken, err := oauth2Config.TokenSource(ctx, storedToken).Token()
146         if err != nil {
147                 return nil, err
148         }
149
150         if refreshedToken.RefreshToken != storedToken.RefreshToken {
151                 if err := u.SetToken(ctx, "Fitbit", refreshedToken); err != nil {
152                         return nil, err
153                 }
154         }
155
156         return &Client{
157                 fitbitUserID: fitbitUserID,
158                 appUser:      u,
159                 client:       oauth2Config.Client(ctx, refreshedToken),
160         }, nil
161 }
162
163 func (c *Client) ActivitySummary(t time.Time) (*ActivitySummary, error) {
164         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
165                 c.fitbitUserID, t.Format("2006-01-02"))
166
167         res, err := c.client.Get(url)
168         if err != nil {
169                 return nil, err
170         }
171         defer res.Body.Close()
172
173         var summary ActivitySummary
174         if err := json.NewDecoder(res.Body).Decode(&summary); err != nil {
175                 return nil, err
176         }
177
178         return &summary, nil
179 }
180
181 func (c *Client) Subscribe(ctx context.Context, collection string) error {
182         subscriberID, err := c.appUser.ID(ctx)
183         if err != nil {
184                 return err
185         }
186
187         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
188                 c.fitbitUserID, collection, subscriberID)
189         res, err := c.client.Post(url, "", nil)
190         if err != nil {
191                 return err
192         }
193         defer res.Body.Close()
194
195         if res.StatusCode >= 400 {
196                 data, _ := ioutil.ReadAll(res.Body)
197                 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
198                 return fmt.Errorf("creating subscription failed")
199         }
200
201         return nil
202 }