Implement mapping of heart rate zones.
[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://kraftakt.octo.it/fitbit/grant",
26         Scopes:       []string{"activity", "heartrate", "profile"},
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 HeartRateZone struct {
88         Name        string  `json:"name"`
89         Min         int     `json:"min"`
90         Max         int     `json:"max"`
91         Minutes     int     `json:"minutes"`
92         CaloriesOut float64 `json:"caloriesOut"`
93 }
94
95 type ActivitySummary struct {
96         Activities []Activity `json:"activities"`
97         Goals      struct {
98                 CaloriesOut int     `json:"caloriesOut"`
99                 Distance    float64 `json:"distance"`
100                 Floors      int     `json:"floors"`
101                 Steps       int     `json:"steps"`
102         } `json:"goals"`
103         Summary struct {
104                 ActiveScore          int             `json:"activeScore"`
105                 ActivityCalories     int             `json:"activityCalories"`
106                 CaloriesBMR          int             `json:"caloriesBMR"`
107                 CaloriesOut          float64         `json:"caloriesOut"`
108                 Distances            []Distance      `json:"distances"`
109                 Elevation            float64         `json:"elevation"`
110                 Floors               int             `json:"floors"`
111                 HeartRateZones       []HeartRateZone `json:"heartRateZones"`
112                 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
113                 MarginalCalories     int             `json:"marginalCalories"`
114                 RestingHeartRate     int             `json:"restingHeartRate"`
115                 Steps                int             `json:"steps"`
116                 SedentaryMinutes     int             `json:"sedentaryMinutes"`
117                 LightlyActiveMinutes int             `json:"lightlyActiveMinutes"`
118                 FairlyActiveMinutes  int             `json:"fairlyActiveMinutes"`
119                 VeryActiveMinutes    int             `json:"veryActiveMinutes"`
120         } `json:"summary"`
121 }
122
123 type Subscription struct {
124         CollectionType string `json:"collectionType"`
125         Date           string `json:"date"`
126         OwnerID        string `json:"ownerId"`
127         OwnerType      string `json:"ownerType"`
128         SubscriptionID string `json:"subscriptionId"`
129 }
130
131 type Client struct {
132         fitbitUserID string
133         appUser      *app.User
134         client       *http.Client
135 }
136
137 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
138         if fitbitUserID == "" {
139                 fitbitUserID = "-"
140         }
141
142         c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
143         if err != nil {
144                 return nil, err
145         }
146
147         return &Client{
148                 fitbitUserID: fitbitUserID,
149                 appUser:      u,
150                 client:       c,
151         }, nil
152 }
153
154 func (c *Client) ActivitySummary(t time.Time) (*ActivitySummary, error) {
155         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
156                 c.fitbitUserID, t.Format("2006-01-02"))
157
158         res, err := c.client.Get(url)
159         if err != nil {
160                 return nil, err
161         }
162         defer res.Body.Close()
163
164         var summary ActivitySummary
165         if err := json.NewDecoder(res.Body).Decode(&summary); err != nil {
166                 return nil, err
167         }
168
169         return &summary, nil
170 }
171
172 func (c *Client) Subscribe(ctx context.Context, collection string) error {
173         subscriberID, err := c.appUser.ID(ctx)
174         if err != nil {
175                 return err
176         }
177
178         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
179                 c.fitbitUserID, collection, subscriberID)
180         res, err := c.client.Post(url, "", nil)
181         if err != nil {
182                 return err
183         }
184         defer res.Body.Close()
185
186         if res.StatusCode >= 400 {
187                 data, _ := ioutil.ReadAll(res.Body)
188                 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
189                 return fmt.Errorf("creating subscription failed")
190         }
191
192         return nil
193 }
194
195 type Profile struct {
196         Name     string
197         Timezone *time.Location
198 }
199
200 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
201         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
202         if err != nil {
203                 return nil, err
204         }
205         defer res.Body.Close()
206
207         if res.StatusCode >= 400 {
208                 data, _ := ioutil.ReadAll(res.Body)
209                 log.Errorf(ctx, "reading profile failed: %s", data)
210                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
211         }
212
213         var data struct {
214                 User struct {
215                         FullName            string
216                         OffsetFromUTCMillis int
217                         Timezone            string
218                 }
219         }
220         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
221                 return nil, err
222         }
223
224         loc, err := time.LoadLocation(data.User.Timezone)
225         if err != nil {
226                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
227         }
228
229         return &Profile{
230                 Name:     data.User.FullName,
231                 Timezone: loc,
232         }, nil
233 }