Package fitbit: Fix unsubscribing.
[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, _ := ioutil.ReadAll(res.Body)
174         log.Debugf(ctx, "GET %s -> %s", url, data)
175
176         var summary ActivitySummary
177         if err := json.Unmarshal(data, &summary); err != nil {
178                 return nil, err
179         }
180
181         return &summary, nil
182 }
183
184 func (c *Client) subscriberID(collection string) string {
185         return fmt.Sprintf("%s:%s", c.appUser.ID, collection)
186 }
187
188 func UserFromSubscriberID(ctx context.Context, subscriberID string) (*app.User, error) {
189         uid := strings.Split(subscriberID, ":")[0]
190         return app.UserByID(ctx, uid)
191 }
192
193 func (c *Client) Subscribe(ctx context.Context, collection string) error {
194         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
195                 c.fitbitUserID, collection, c.subscriberID(collection))
196         res, err := c.client.Post(url, "", nil)
197         if err != nil {
198                 return err
199         }
200         defer res.Body.Close()
201
202         if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
203                 data, _ := ioutil.ReadAll(res.Body)
204                 log.Errorf(ctx, "creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
205                 return fmt.Errorf("creating %q subscription failed", collection)
206         }
207         if res.StatusCode == http.StatusConflict {
208                 log.Infof(ctx, "creating %q subscription: already exists", collection)
209         }
210
211         return nil
212 }
213
214 func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscriptionID string) error {
215         if userID == "" {
216                 userID = c.fitbitUserID
217         }
218
219         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
220                 userID, collection, subscriptionID)
221         req, err := http.NewRequest(http.MethodDelete, url, nil)
222         if err != nil {
223                 return err
224         }
225
226         res, err := c.client.Do(req.WithContext(ctx))
227         if err != nil {
228                 return err
229         }
230         defer res.Body.Close()
231
232         if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
233                 data, _ := ioutil.ReadAll(res.Body)
234                 log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
235                 return fmt.Errorf("deleting %q subscription failed", collection)
236         }
237         if res.StatusCode == http.StatusNotFound {
238                 log.Infof(ctx, "deleting %q subscription: not found", collection)
239         }
240
241         return nil
242 }
243
244 func (c *Client) UnsubscribeAll(ctx context.Context) error {
245         var errs appengine.MultiError
246
247         for _, collection := range []string{"activities", "sleep"} {
248                 subs, err := c.ListSubscriptions(ctx, collection)
249                 if err != nil {
250                         errs = append(errs, err)
251                         continue
252                 }
253
254                 for _, sub := range subs {
255                         if err := c.unsubscribe(ctx, sub.OwnerID, sub.CollectionType, sub.SubscriptionID); err != nil {
256                                 errs = append(errs, err)
257                         }
258                 }
259         }
260         if len(errs) != 0 {
261                 return errs
262         }
263
264         return nil
265 }
266
267 func (c *Client) ListSubscriptions(ctx context.Context, collection string) ([]Subscription, error) {
268         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions.json", c.fitbitUserID, collection)
269         res, err := c.client.Get(url)
270         if err != nil {
271                 return nil, fmt.Errorf("Get(%q) = %v", url, err)
272         }
273         defer res.Body.Close()
274
275         if res.StatusCode == http.StatusNotFound {
276                 log.Infof(ctx, "get %q subscription: not found", collection)
277                 return nil, nil
278         }
279
280         data, err := ioutil.ReadAll(res.Body)
281         if err != nil {
282                 return nil, err
283         }
284         log.Debugf(ctx, "GET %s -> %s", url, data)
285
286         if res.StatusCode >= 400 {
287                 return nil, fmt.Errorf("Get(%q) = %d", url, res.StatusCode)
288         }
289
290         var parsed struct {
291                 Subscriptions []Subscription `json:"apiSubscriptions"`
292         }
293         if err := json.Unmarshal(data, &parsed); err != nil {
294                 return nil, err
295         }
296
297         var errs appengine.MultiError
298         var ret []Subscription
299         for _, sub := range parsed.Subscriptions {
300                 if sub.CollectionType != collection {
301                         errs = append(errs, fmt.Errorf("unexpected collection type: got %q, want %q", sub.CollectionType, collection))
302                         continue
303                 }
304                 if sub.SubscriptionID == "" {
305                         errs = append(errs, fmt.Errorf("missing subscription ID: %+v", sub))
306                         continue
307                 }
308                 if sub.OwnerID == "" {
309                         sub.OwnerID = c.fitbitUserID
310                 }
311                 ret = append(ret, sub)
312         }
313
314         if len(ret) == 0 && len(errs) != 0 {
315                 return nil, errs
316         }
317
318         for _, err := range errs {
319                 log.Warningf(ctx, err)
320         }
321
322         return ret, nil
323 }
324
325 func (c *Client) DeleteToken(ctx context.Context) error {
326         return c.appUser.DeleteToken(ctx, "Fitbit")
327 }
328
329 type Profile struct {
330         Name     string
331         Timezone *time.Location
332 }
333
334 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
335         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
336         if err != nil {
337                 return nil, err
338         }
339         defer res.Body.Close()
340
341         if res.StatusCode >= 400 {
342                 data, _ := ioutil.ReadAll(res.Body)
343                 log.Errorf(ctx, "reading profile failed: %s", data)
344                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
345         }
346
347         var data struct {
348                 User struct {
349                         FullName            string
350                         OffsetFromUTCMillis int
351                         Timezone            string
352                 }
353         }
354         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
355                 return nil, err
356         }
357
358         loc, err := time.LoadLocation(data.User.Timezone)
359         if err != nil {
360                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
361         }
362
363         return &Profile{
364                 Name:     data.User.FullName,
365                 Timezone: loc,
366         }, nil
367 }