Connect handlers: don't call {fitbit,gfit}.NewClient().
[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/log"
19 )
20
21 func oauthConfig() *oauth2.Config {
22         return &oauth2.Config{
23                 ClientID:     app.Config.FitbitClientID,
24                 ClientSecret: app.Config.FitbitClientSecret,
25                 Endpoint:     oauth2fitbit.Endpoint,
26                 RedirectURL:  "https://kraftakt.octo.it/fitbit/grant",
27                 Scopes: []string{
28                         "activity",
29                         "heartrate",
30                         "profile",
31                         "sleep",
32                 },
33         }
34 }
35
36 func AuthURL(ctx context.Context, u *app.User) string {
37         return oauthConfig().AuthCodeURL(u.Sign("Fitbit"), oauth2.AccessTypeOffline)
38 }
39
40 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
41         if state := r.FormValue("state"); state != u.Sign("Fitbit") {
42                 return fmt.Errorf("invalid state parameter: %q", state)
43         }
44
45         tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
46         if err != nil {
47                 return err
48         }
49
50         return u.SetToken(ctx, "Fitbit", tok)
51 }
52
53 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
54         signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
55         if err != nil {
56                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
57                 return false
58         }
59
60         mac := hmac.New(sha1.New, []byte(oauthConfig().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         ActivityParentName string    `json:"activityParentName"`
71         Calories           int       `json:"calories"`
72         Description        string    `json:"description"`
73         Distance           float64   `json:"distance"`
74         Duration           int       `json:"duration"`
75         HasStartTime       bool      `json:"hasStartTime"`
76         IsFavorite         bool      `json:"isFavorite"`
77         LastModified       time.Time `json:"lastModified"`
78         LogID              int       `json:"logId"`
79         Name               string    `json:"name"`
80         StartTime          string    `json:"startTime"`
81         StartDate          string    `json:"startDate"`
82         Steps              int       `json:"steps"`
83 }
84
85 type Distance struct {
86         Activity string  `json:"activity"`
87         Distance float64 `json:"distance"`
88 }
89
90 type HeartRateZone struct {
91         Name        string  `json:"name"`
92         Min         int     `json:"min"`
93         Max         int     `json:"max"`
94         Minutes     int     `json:"minutes"`
95         CaloriesOut float64 `json:"caloriesOut"`
96 }
97
98 type ActivitySummary struct {
99         Activities []Activity `json:"activities"`
100         Goals      struct {
101                 CaloriesOut int     `json:"caloriesOut"`
102                 Distance    float64 `json:"distance"`
103                 Floors      int     `json:"floors"`
104                 Steps       int     `json:"steps"`
105         } `json:"goals"`
106         Summary struct {
107                 ActiveScore          int             `json:"activeScore"`
108                 ActivityCalories     int             `json:"activityCalories"`
109                 CaloriesBMR          int             `json:"caloriesBMR"`
110                 CaloriesOut          float64         `json:"caloriesOut"`
111                 Distances            []Distance      `json:"distances"`
112                 Elevation            float64         `json:"elevation"`
113                 Floors               int             `json:"floors"`
114                 HeartRateZones       []HeartRateZone `json:"heartRateZones"`
115                 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
116                 MarginalCalories     int             `json:"marginalCalories"`
117                 RestingHeartRate     int             `json:"restingHeartRate"`
118                 Steps                int             `json:"steps"`
119                 SedentaryMinutes     int             `json:"sedentaryMinutes"`
120                 LightlyActiveMinutes int             `json:"lightlyActiveMinutes"`
121                 FairlyActiveMinutes  int             `json:"fairlyActiveMinutes"`
122                 VeryActiveMinutes    int             `json:"veryActiveMinutes"`
123         } `json:"summary"`
124 }
125
126 type Subscription struct {
127         CollectionType string `json:"collectionType"`
128         Date           string `json:"date"`
129         OwnerID        string `json:"ownerId"`
130         OwnerType      string `json:"ownerType"`
131         SubscriptionID string `json:"subscriptionId"`
132 }
133
134 type Client struct {
135         fitbitUserID string
136         appUser      *app.User
137         client       *http.Client
138 }
139
140 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
141         if fitbitUserID == "" {
142                 fitbitUserID = "-"
143         }
144
145         c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
146         if err != nil {
147                 return nil, err
148         }
149
150         return &Client{
151                 fitbitUserID: fitbitUserID,
152                 appUser:      u,
153                 client:       c,
154         }, nil
155 }
156
157 func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
158         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
159                 c.fitbitUserID, date)
160
161         res, err := c.client.Get(url)
162         if err != nil {
163                 return nil, err
164         }
165         defer res.Body.Close()
166
167         data, _ := ioutil.ReadAll(res.Body)
168         log.Debugf(ctx, "GET %s -> %s", url, data)
169
170         var summary ActivitySummary
171         if err := json.Unmarshal(data, &summary); err != nil {
172                 return nil, err
173         }
174
175         return &summary, nil
176 }
177
178 func (c *Client) subscriberID(collection string) string {
179         return fmt.Sprintf("%s:%s", c.appUser.ID, collection)
180 }
181
182 func UserFromSubscriberID(ctx context.Context, subscriberID string) (*app.User, error) {
183         uid := strings.Split(subscriberID, ":")[0]
184         return app.UserByID(ctx, uid)
185 }
186
187 func (c *Client) Subscribe(ctx context.Context, collection string) error {
188         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
189                 c.fitbitUserID, collection, c.subscriberID(collection))
190         res, err := c.client.Post(url, "", nil)
191         if err != nil {
192                 return err
193         }
194         defer res.Body.Close()
195
196         if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
197                 data, _ := ioutil.ReadAll(res.Body)
198                 log.Errorf(ctx, "creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
199                 return fmt.Errorf("creating %q subscription failed", collection)
200         }
201         if res.StatusCode == http.StatusConflict {
202                 log.Infof(ctx, "creating %q subscription: already exists", collection)
203         }
204
205         return nil
206 }
207
208 func (c *Client) Unsubscribe(ctx context.Context, collection string) error {
209         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
210                 c.fitbitUserID, collection, c.subscriberID(collection))
211         req, err := http.NewRequest(http.MethodDelete, url, nil)
212         if err != nil {
213                 return err
214         }
215
216         res, err := c.client.Do(req.WithContext(ctx))
217         if err != nil {
218                 return err
219         }
220         defer res.Body.Close()
221
222         if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
223                 data, _ := ioutil.ReadAll(res.Body)
224                 log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
225                 return fmt.Errorf("deleting %q subscription failed", collection)
226         }
227         if res.StatusCode == http.StatusNotFound {
228                 log.Infof(ctx, "deleting %q subscription: not found", collection)
229         }
230
231         return nil
232 }
233
234 func (c *Client) DeleteToken(ctx context.Context) error {
235         return c.appUser.DeleteToken(ctx, "Fitbit")
236 }
237
238 type Profile struct {
239         Name     string
240         Timezone *time.Location
241 }
242
243 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
244         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
245         if err != nil {
246                 return nil, err
247         }
248         defer res.Body.Close()
249
250         if res.StatusCode >= 400 {
251                 data, _ := ioutil.ReadAll(res.Body)
252                 log.Errorf(ctx, "reading profile failed: %s", data)
253                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
254         }
255
256         var data struct {
257                 User struct {
258                         FullName            string
259                         OffsetFromUTCMillis int
260                         Timezone            string
261                 }
262         }
263         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
264                 return nil, err
265         }
266
267         loc, err := time.LoadLocation(data.User.Timezone)
268         if err != nil {
269                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
270         }
271
272         return &Profile{
273                 Name:     data.User.FullName,
274                 Timezone: loc,
275         }, nil
276 }