Package fitbit: Implement UnsubscribeAll() and ListSubscriptions().
[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, collection string) error {
215         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
216                 c.fitbitUserID, collection, c.subscriberID(collection))
217         req, err := http.NewRequest(http.MethodDelete, url, nil)
218         if err != nil {
219                 return err
220         }
221
222         res, err := c.client.Do(req.WithContext(ctx))
223         if err != nil {
224                 return err
225         }
226         defer res.Body.Close()
227
228         if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
229                 data, _ := ioutil.ReadAll(res.Body)
230                 log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
231                 return fmt.Errorf("deleting %q subscription failed", collection)
232         }
233         if res.StatusCode == http.StatusNotFound {
234                 log.Infof(ctx, "deleting %q subscription: not found", collection)
235         }
236
237         return nil
238 }
239
240 func (c *Client) UnsubscribeAll(ctx context.Context) error {
241         subs, err := c.ListSubscriptions(ctx)
242         if err != nil {
243                 return err
244         }
245
246         var errs appengine.MultiError
247         for _, s := range subs {
248                 if s.OwnerType != "user" {
249                         log.Infof(ctx, "unexpected OwnerType: %q", s.OwnerType)
250                         continue
251                 }
252                 if err := c.Unsubscribe(ctx, s.CollectionType); err != nil {
253                         errs = append(errs, err)
254                 }
255         }
256         if len(errs) != 0 {
257                 return errs
258         }
259
260         return nil
261 }
262
263 func (c *Client) ListSubscriptions(ctx context.Context) ([]Subscription, error) {
264         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/apiSubscriptions.json", c.fitbitUserID)
265         res, err := c.client.Get(url)
266         if err != nil {
267                 return nil, fmt.Errorf("Get(%q) = %v", url, err)
268         }
269         defer res.Body.Close()
270
271         if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
272                 data, _ := ioutil.ReadAll(res.Body)
273                 log.Errorf(ctx, "listing subscriptions failed: status %d %q", res.StatusCode, data)
274                 return nil, fmt.Errorf("listing subscriptions failed")
275         }
276         if res.StatusCode == http.StatusNotFound {
277                 log.Infof(ctx, "listing subscriptions: not found")
278                 return nil, nil
279         }
280
281         var subscriptions []Subscription
282         if err := json.NewDecoder(res.Body).Decode(&subscriptions); err != nil {
283                 return nil, err
284         }
285
286         for i, s := range subscriptions {
287                 log.Debugf(ctx, "ListSubscriptions() = %d: %s", i, s)
288         }
289
290         return subscriptions, nil
291 }
292
293 func (c *Client) DeleteToken(ctx context.Context) error {
294         return c.appUser.DeleteToken(ctx, "Fitbit")
295 }
296
297 type Profile struct {
298         Name     string
299         Timezone *time.Location
300 }
301
302 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
303         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
304         if err != nil {
305                 return nil, err
306         }
307         defer res.Body.Close()
308
309         if res.StatusCode >= 400 {
310                 data, _ := ioutil.ReadAll(res.Body)
311                 log.Errorf(ctx, "reading profile failed: %s", data)
312                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
313         }
314
315         var data struct {
316                 User struct {
317                         FullName            string
318                         OffsetFromUTCMillis int
319                         Timezone            string
320                 }
321         }
322         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
323                 return nil, err
324         }
325
326         loc, err := time.LoadLocation(data.User.Timezone)
327         if err != nil {
328                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
329         }
330
331         return &Profile{
332                 Name:     data.User.FullName,
333                 Timezone: loc,
334         }, nil
335 }