Call ActivitySummary() and Profile() concurrently.
[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(ctx context.Context, date string) (*ActivitySummary, error) {
149         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
150                 c.fitbitUserID, date)
151
152         res, err := c.client.Get(url)
153         if err != nil {
154                 return nil, err
155         }
156         defer res.Body.Close()
157
158         data, _ := ioutil.ReadAll(res.Body)
159         log.Debugf(ctx, "GET %s -> %s", url, data)
160
161         var summary ActivitySummary
162         if err := json.Unmarshal(data, &summary); err != nil {
163                 return nil, err
164         }
165
166         return &summary, nil
167 }
168
169 func (c *Client) Subscribe(ctx context.Context, collection string) error {
170         subscriberID, err := c.appUser.ID(ctx)
171         if err != nil {
172                 return err
173         }
174
175         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
176                 c.fitbitUserID, collection, subscriberID)
177         res, err := c.client.Post(url, "", nil)
178         if err != nil {
179                 return err
180         }
181         defer res.Body.Close()
182
183         if res.StatusCode >= 400 {
184                 data, _ := ioutil.ReadAll(res.Body)
185                 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
186                 return fmt.Errorf("creating subscription failed")
187         }
188
189         return nil
190 }
191
192 type Profile struct {
193         Name     string
194         Timezone *time.Location
195 }
196
197 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
198         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
199         if err != nil {
200                 return nil, err
201         }
202         defer res.Body.Close()
203
204         if res.StatusCode >= 400 {
205                 data, _ := ioutil.ReadAll(res.Body)
206                 log.Errorf(ctx, "reading profile failed: %s", data)
207                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
208         }
209
210         var data struct {
211                 User struct {
212                         FullName            string
213                         OffsetFromUTCMillis int
214                         Timezone            string
215                 }
216         }
217         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
218                 return nil, err
219         }
220
221         loc, err := time.LoadLocation(data.User.Timezone)
222         if err != nil {
223                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
224         }
225
226         return &Profile{
227                 Name:     data.User.FullName,
228                 Timezone: loc,
229         }, nil
230 }