Package fitbit: Don't URL-decode Fitbit's signature.
[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         "time"
13
14         "github.com/octo/gfitsync/app"
15         "golang.org/x/oauth2"
16         oauth2fitbit "golang.org/x/oauth2/fitbit"
17         "google.golang.org/appengine/log"
18 )
19
20 var oauth2Config = &oauth2.Config{
21         ClientID:     "@FITBIT_CLIENT_ID@",
22         ClientSecret: "@FITBIT_CLIENT_SECRET@",
23         Endpoint:     oauth2fitbit.Endpoint,
24         RedirectURL:  "https://kraftakt.octo.it/fitbit/grant",
25         Scopes:       []string{"activity", "heartrate", "profile"},
26 }
27
28 const csrfToken = "@CSRFTOKEN@"
29
30 func AuthURL() string {
31         return oauth2Config.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
32 }
33
34 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
35         if state := r.FormValue("state"); state != csrfToken {
36                 return fmt.Errorf("invalid state parameter: %q", state)
37         }
38
39         tok, err := oauth2Config.Exchange(ctx, r.FormValue("code"))
40         if err != nil {
41                 return err
42         }
43
44         return u.SetToken(ctx, "Fitbit", tok)
45 }
46
47 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
48         signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
49         if err != nil {
50                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
51                 return false
52         }
53
54         mac := hmac.New(sha1.New, []byte(oauth2Config.ClientSecret+"&"))
55         mac.Write(payload)
56         signatureWant := mac.Sum(nil)
57
58         return hmac.Equal(signatureGot, signatureWant)
59 }
60
61 type Activity struct {
62         ActivityID       int     `json:"activityId"`
63         ActivityParentID int     `json:"activityParentId"`
64         Calories         int     `json:"calories"`
65         Description      string  `json:"description"`
66         Distance         float64 `json:"distance"`
67         Duration         int     `json:"duration"`
68         HasStartTime     bool    `json:"hasStartTime"`
69         IsFavorite       bool    `json:"isFavorite"`
70         LogID            int     `json:"logId"`
71         Name             string  `json:"name"`
72         StartTime        string  `json:"startTime"`
73         Steps            int     `json:"steps"`
74 }
75
76 type Distance struct {
77         Activity string  `json:"activity"`
78         Distance float64 `json:"distance"`
79 }
80
81 type HeartRateZone struct {
82         Name        string  `json:"name"`
83         Min         int     `json:"min"`
84         Max         int     `json:"max"`
85         Minutes     int     `json:"minutes"`
86         CaloriesOut float64 `json:"caloriesOut"`
87 }
88
89 type ActivitySummary struct {
90         Activities []Activity `json:"activities"`
91         Goals      struct {
92                 CaloriesOut int     `json:"caloriesOut"`
93                 Distance    float64 `json:"distance"`
94                 Floors      int     `json:"floors"`
95                 Steps       int     `json:"steps"`
96         } `json:"goals"`
97         Summary struct {
98                 ActiveScore          int             `json:"activeScore"`
99                 ActivityCalories     int             `json:"activityCalories"`
100                 CaloriesBMR          int             `json:"caloriesBMR"`
101                 CaloriesOut          float64         `json:"caloriesOut"`
102                 Distances            []Distance      `json:"distances"`
103                 Elevation            float64         `json:"elevation"`
104                 Floors               int             `json:"floors"`
105                 HeartRateZones       []HeartRateZone `json:"heartRateZones"`
106                 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
107                 MarginalCalories     int             `json:"marginalCalories"`
108                 RestingHeartRate     int             `json:"restingHeartRate"`
109                 Steps                int             `json:"steps"`
110                 SedentaryMinutes     int             `json:"sedentaryMinutes"`
111                 LightlyActiveMinutes int             `json:"lightlyActiveMinutes"`
112                 FairlyActiveMinutes  int             `json:"fairlyActiveMinutes"`
113                 VeryActiveMinutes    int             `json:"veryActiveMinutes"`
114         } `json:"summary"`
115 }
116
117 type Subscription struct {
118         CollectionType string `json:"collectionType"`
119         Date           string `json:"date"`
120         OwnerID        string `json:"ownerId"`
121         OwnerType      string `json:"ownerType"`
122         SubscriptionID string `json:"subscriptionId"`
123 }
124
125 type Client struct {
126         fitbitUserID string
127         appUser      *app.User
128         client       *http.Client
129 }
130
131 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
132         if fitbitUserID == "" {
133                 fitbitUserID = "-"
134         }
135
136         c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
137         if err != nil {
138                 return nil, err
139         }
140
141         return &Client{
142                 fitbitUserID: fitbitUserID,
143                 appUser:      u,
144                 client:       c,
145         }, nil
146 }
147
148 func (c *Client) ActivitySummary(t time.Time) (*ActivitySummary, error) {
149         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
150                 c.fitbitUserID, t.Format("2006-01-02"))
151
152         res, err := c.client.Get(url)
153         if err != nil {
154                 return nil, err
155         }
156         defer res.Body.Close()
157
158         var summary ActivitySummary
159         if err := json.NewDecoder(res.Body).Decode(&summary); err != nil {
160                 return nil, err
161         }
162
163         return &summary, nil
164 }
165
166 func (c *Client) Subscribe(ctx context.Context, collection string) error {
167         subscriberID, err := c.appUser.ID(ctx)
168         if err != nil {
169                 return err
170         }
171
172         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
173                 c.fitbitUserID, collection, subscriberID)
174         res, err := c.client.Post(url, "", nil)
175         if err != nil {
176                 return err
177         }
178         defer res.Body.Close()
179
180         if res.StatusCode >= 400 {
181                 data, _ := ioutil.ReadAll(res.Body)
182                 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
183                 return fmt.Errorf("creating subscription failed")
184         }
185
186         return nil
187 }
188
189 type Profile struct {
190         Name     string
191         Timezone *time.Location
192 }
193
194 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
195         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
196         if err != nil {
197                 return nil, err
198         }
199         defer res.Body.Close()
200
201         if res.StatusCode >= 400 {
202                 data, _ := ioutil.ReadAll(res.Body)
203                 log.Errorf(ctx, "reading profile failed: %s", data)
204                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
205         }
206
207         var data struct {
208                 User struct {
209                         FullName            string
210                         OffsetFromUTCMillis int
211                         Timezone            string
212                 }
213         }
214         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
215                 return nil, err
216         }
217
218         loc, err := time.LoadLocation(data.User.Timezone)
219         if err != nil {
220                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
221         }
222
223         return &Profile{
224                 Name:     data.User.FullName,
225                 Timezone: loc,
226         }, nil
227 }