Implement storing of calories expended.
[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", "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                 MarginalCalories     int             `json:"marginalCalories"`
113                 RestingHeartRate     int             `json:"restingHeartRate"`
114                 Steps                int             `json:"steps"`
115                 SedentaryMinutes     int             `json:"sedentaryMinutes"`
116                 LightlyActiveMinutes int             `json:"lightlyActiveMinutes"`
117                 FairlyActiveMinutes  int             `json:"fairlyActiveMinutes"`
118                 VeryActiveMinutes    int             `json:"veryActiveMinutes"`
119         } `json:"summary"`
120 }
121
122 type Subscription struct {
123         CollectionType string `json:"collectionType"`
124         Date           string `json:"date"`
125         OwnerID        string `json:"ownerId"`
126         OwnerType      string `json:"ownerType"`
127         SubscriptionID string `json:"subscriptionId"`
128 }
129
130 type Client struct {
131         fitbitUserID string
132         appUser      *app.User
133         client       *http.Client
134 }
135
136 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
137         if fitbitUserID == "" {
138                 fitbitUserID = "-"
139         }
140
141         c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
142         if err != nil {
143                 return nil, err
144         }
145
146         return &Client{
147                 fitbitUserID: fitbitUserID,
148                 appUser:      u,
149                 client:       c,
150         }, nil
151 }
152
153 func (c *Client) ActivitySummary(t time.Time) (*ActivitySummary, error) {
154         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
155                 c.fitbitUserID, t.Format("2006-01-02"))
156
157         res, err := c.client.Get(url)
158         if err != nil {
159                 return nil, err
160         }
161         defer res.Body.Close()
162
163         var summary ActivitySummary
164         if err := json.NewDecoder(res.Body).Decode(&summary); err != nil {
165                 return nil, err
166         }
167
168         return &summary, nil
169 }
170
171 func (c *Client) Subscribe(ctx context.Context, collection string) error {
172         subscriberID, err := c.appUser.ID(ctx)
173         if err != nil {
174                 return err
175         }
176
177         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
178                 c.fitbitUserID, collection, subscriberID)
179         res, err := c.client.Post(url, "", nil)
180         if err != nil {
181                 return err
182         }
183         defer res.Body.Close()
184
185         if res.StatusCode >= 400 {
186                 data, _ := ioutil.ReadAll(res.Body)
187                 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
188                 return fmt.Errorf("creating subscription failed")
189         }
190
191         return nil
192 }
193
194 type Profile struct {
195         Name     string
196         Timezone *time.Location
197 }
198
199 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
200         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
201         if err != nil {
202                 return nil, err
203         }
204         defer res.Body.Close()
205
206         if res.StatusCode >= 400 {
207                 data, _ := ioutil.ReadAll(res.Body)
208                 log.Errorf(ctx, "reading profile failed: %s", data)
209                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
210         }
211
212         var data struct {
213                 User struct {
214                         FullName            string
215                         OffsetFromUTCMillis int
216                         Timezone            string
217                 }
218         }
219         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
220                 return nil, err
221         }
222
223         loc, err := time.LoadLocation(data.User.Timezone)
224         if err != nil {
225                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
226         }
227
228         return &Profile{
229                 Name:     data.User.FullName,
230                 Timezone: loc,
231         }, nil
232 }