7e38bf17a01ec4a1721cad7b9a1f6ea9df68bb8a
[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         "strings"
13         "time"
14
15         "github.com/octo/kraftakt/app"
16         "golang.org/x/oauth2"
17         oauth2fitbit "golang.org/x/oauth2/fitbit"
18         "google.golang.org/appengine"
19         "google.golang.org/appengine/log"
20 )
21
22 func oauthConfig() *oauth2.Config {
23         return &oauth2.Config{
24                 ClientID:     app.Config.FitbitClientID,
25                 ClientSecret: app.Config.FitbitClientSecret,
26                 Endpoint:     oauth2fitbit.Endpoint,
27                 RedirectURL:  "https://kraftakt.octo.it/fitbit/grant",
28                 Scopes: []string{
29                         "activity",
30                         "heartrate",
31                         "profile",
32                         "sleep",
33                 },
34         }
35 }
36
37 func AuthURL(ctx context.Context, u *app.User) string {
38         return oauthConfig().AuthCodeURL(u.Sign("Fitbit"), oauth2.AccessTypeOffline)
39 }
40
41 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
42         if state := r.FormValue("state"); state != u.Sign("Fitbit") {
43                 return fmt.Errorf("invalid state parameter: %q", state)
44         }
45
46         tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
47         if err != nil {
48                 return err
49         }
50
51         return u.SetToken(ctx, "Fitbit", tok)
52 }
53
54 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
55         signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
56         if err != nil {
57                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
58                 return false
59         }
60
61         mac := hmac.New(sha1.New, []byte(oauthConfig().ClientSecret+"&"))
62         mac.Write(payload)
63         signatureWant := mac.Sum(nil)
64
65         return hmac.Equal(signatureGot, signatureWant)
66 }
67
68 type Activity struct {
69         ActivityID         int       `json:"activityId"`
70         ActivityParentID   int       `json:"activityParentId"`
71         ActivityParentName string    `json:"activityParentName"`
72         Calories           int       `json:"calories"`
73         Description        string    `json:"description"`
74         Distance           float64   `json:"distance"`
75         Duration           int       `json:"duration"`
76         HasStartTime       bool      `json:"hasStartTime"`
77         IsFavorite         bool      `json:"isFavorite"`
78         LastModified       time.Time `json:"lastModified"`
79         LogID              int       `json:"logId"`
80         Name               string    `json:"name"`
81         StartTime          string    `json:"startTime"`
82         StartDate          string    `json:"startDate"`
83         Steps              int       `json:"steps"`
84 }
85
86 type Distance struct {
87         Activity string  `json:"activity"`
88         Distance float64 `json:"distance"`
89 }
90
91 type HeartRateZone struct {
92         Name        string  `json:"name"`
93         Min         int     `json:"min"`
94         Max         int     `json:"max"`
95         Minutes     int     `json:"minutes"`
96         CaloriesOut float64 `json:"caloriesOut"`
97 }
98
99 type ActivitySummary struct {
100         Activities []Activity `json:"activities"`
101         Goals      struct {
102                 CaloriesOut int     `json:"caloriesOut"`
103                 Distance    float64 `json:"distance"`
104                 Floors      int     `json:"floors"`
105                 Steps       int     `json:"steps"`
106         } `json:"goals"`
107         Summary struct {
108                 ActiveScore          int             `json:"activeScore"`
109                 ActivityCalories     int             `json:"activityCalories"`
110                 CaloriesBMR          int             `json:"caloriesBMR"`
111                 CaloriesOut          float64         `json:"caloriesOut"`
112                 Distances            []Distance      `json:"distances"`
113                 Elevation            float64         `json:"elevation"`
114                 Floors               int             `json:"floors"`
115                 HeartRateZones       []HeartRateZone `json:"heartRateZones"`
116                 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
117                 MarginalCalories     int             `json:"marginalCalories"`
118                 RestingHeartRate     int             `json:"restingHeartRate"`
119                 Steps                int             `json:"steps"`
120                 SedentaryMinutes     int             `json:"sedentaryMinutes"`
121                 LightlyActiveMinutes int             `json:"lightlyActiveMinutes"`
122                 FairlyActiveMinutes  int             `json:"fairlyActiveMinutes"`
123                 VeryActiveMinutes    int             `json:"veryActiveMinutes"`
124         } `json:"summary"`
125 }
126
127 type Subscription struct {
128         CollectionType string `json:"collectionType"`
129         Date           string `json:"date"`
130         OwnerID        string `json:"ownerId"`
131         OwnerType      string `json:"ownerType"`
132         SubscriptionID string `json:"subscriptionId"`
133 }
134
135 func (s Subscription) String() string {
136         return fmt.Sprintf("https://api.fitbit.com/1/%s/%s/%s/apiSubscriptions/%s.json",
137                 s.OwnerType, s.OwnerID, s.CollectionType, s.SubscriptionID)
138 }
139
140 type Client struct {
141         fitbitUserID string
142         appUser      *app.User
143         client       *http.Client
144 }
145
146 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
147         if fitbitUserID == "" {
148                 fitbitUserID = "-"
149         }
150
151         c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
152         if err != nil {
153                 return nil, fmt.Errorf("OAuthClient(%q) = %v", "Fitbit", err)
154         }
155
156         return &Client{
157                 fitbitUserID: fitbitUserID,
158                 appUser:      u,
159                 client:       c,
160         }, nil
161 }
162
163 func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
164         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
165                 c.fitbitUserID, date)
166
167         res, err := c.client.Get(url)
168         if err != nil {
169                 return nil, err
170         }
171         defer res.Body.Close()
172
173         data, err := ioutil.ReadAll(res.Body)
174         if err != nil {
175                 return nil, err
176         }
177         log.Debugf(ctx, "GET %s -> %s", url, data)
178
179         var summary ActivitySummary
180         if err := json.Unmarshal(data, &summary); err != nil {
181                 return nil, err
182         }
183
184         return &summary, nil
185 }
186
187 func (c *Client) subscriberID(collection string) string {
188         return fmt.Sprintf("%s:%s", c.appUser.ID, collection)
189 }
190
191 func UserFromSubscriberID(ctx context.Context, subscriberID string) (*app.User, error) {
192         uid := strings.Split(subscriberID, ":")[0]
193         return app.UserByID(ctx, uid)
194 }
195
196 func (c *Client) Subscribe(ctx context.Context, collection string) error {
197         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
198                 c.fitbitUserID, collection, c.subscriberID(collection))
199         res, err := c.client.Post(url, "", nil)
200         if err != nil {
201                 return err
202         }
203         defer res.Body.Close()
204
205         if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
206                 data, _ := ioutil.ReadAll(res.Body)
207                 log.Errorf(ctx, "creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
208                 return fmt.Errorf("creating %q subscription failed", collection)
209         }
210         if res.StatusCode == http.StatusConflict {
211                 log.Infof(ctx, "creating %q subscription: already exists", collection)
212         }
213
214         return nil
215 }
216
217 func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscriptionID string) error {
218         if userID == "" {
219                 userID = c.fitbitUserID
220         }
221
222         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
223                 userID, collection, subscriptionID)
224         req, err := http.NewRequest(http.MethodDelete, url, nil)
225         if err != nil {
226                 return err
227         }
228
229         res, err := c.client.Do(req.WithContext(ctx))
230         if err != nil {
231                 return err
232         }
233         defer res.Body.Close()
234
235         if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
236                 data, _ := ioutil.ReadAll(res.Body)
237                 log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
238                 return fmt.Errorf("deleting %q subscription failed", collection)
239         }
240         if res.StatusCode == http.StatusNotFound {
241                 log.Infof(ctx, "deleting %q subscription: not found", collection)
242         }
243
244         return nil
245 }
246
247 func (c *Client) UnsubscribeAll(ctx context.Context) error {
248         var errs appengine.MultiError
249
250         for _, collection := range []string{"activities", "sleep"} {
251                 subs, err := c.ListSubscriptions(ctx, collection)
252                 if err != nil {
253                         errs = append(errs, err)
254                         continue
255                 }
256
257                 for _, sub := range subs {
258                         if err := c.unsubscribe(ctx, sub.OwnerID, sub.CollectionType, sub.SubscriptionID); err != nil {
259                                 errs = append(errs, err)
260                         }
261                 }
262         }
263         if len(errs) != 0 {
264                 return errs
265         }
266
267         return nil
268 }
269
270 func (c *Client) ListSubscriptions(ctx context.Context, collection string) ([]Subscription, error) {
271         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions.json", c.fitbitUserID, collection)
272         res, err := c.client.Get(url)
273         if err != nil {
274                 return nil, fmt.Errorf("Get(%q) = %v", url, err)
275         }
276         defer res.Body.Close()
277
278         if res.StatusCode == http.StatusNotFound {
279                 log.Infof(ctx, "get %q subscription: not found", collection)
280                 return nil, nil
281         }
282
283         data, err := ioutil.ReadAll(res.Body)
284         if err != nil {
285                 return nil, err
286         }
287         log.Debugf(ctx, "GET %s -> %s", url, data)
288
289         if res.StatusCode >= 400 {
290                 return nil, fmt.Errorf("Get(%q) = %d", url, res.StatusCode)
291         }
292
293         var parsed struct {
294                 Subscriptions []Subscription `json:"apiSubscriptions"`
295         }
296         if err := json.Unmarshal(data, &parsed); err != nil {
297                 return nil, err
298         }
299
300         var errs appengine.MultiError
301         var ret []Subscription
302         for _, sub := range parsed.Subscriptions {
303                 if sub.CollectionType != collection {
304                         errs = append(errs, fmt.Errorf("unexpected collection type: got %q, want %q", sub.CollectionType, collection))
305                         continue
306                 }
307                 if sub.SubscriptionID == "" {
308                         errs = append(errs, fmt.Errorf("missing subscription ID: %+v", sub))
309                         continue
310                 }
311                 if sub.OwnerID == "" {
312                         sub.OwnerID = c.fitbitUserID
313                 }
314                 ret = append(ret, sub)
315         }
316
317         if len(ret) == 0 && len(errs) != 0 {
318                 return nil, errs
319         }
320
321         for _, err := range errs {
322                 log.Warningf(ctx, "%v", err)
323         }
324
325         return ret, nil
326 }
327
328 func (c *Client) DeleteToken(ctx context.Context) error {
329         return c.appUser.DeleteToken(ctx, "Fitbit")
330 }
331
332 type Profile struct {
333         Name     string
334         Timezone *time.Location
335 }
336
337 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
338         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
339         if err != nil {
340                 return nil, err
341         }
342         defer res.Body.Close()
343
344         if res.StatusCode >= 400 {
345                 data, _ := ioutil.ReadAll(res.Body)
346                 log.Errorf(ctx, "reading profile failed: %s", data)
347                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
348         }
349
350         var data struct {
351                 User struct {
352                         FullName            string
353                         OffsetFromUTCMillis int
354                         Timezone            string
355                 }
356         }
357         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
358                 return nil, err
359         }
360
361         loc, err := time.LoadLocation(data.User.Timezone)
362         if err != nil {
363                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
364         }
365
366         return &Profile{
367                 Name:     data.User.FullName,
368                 Timezone: loc,
369         }, nil
370 }